lang
stringclasses
1 value
license
stringclasses
13 values
stderr
stringlengths
0
350
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
7
45.1k
new_contents
stringlengths
0
1.87M
new_file
stringlengths
6
292
old_contents
stringlengths
0
1.87M
message
stringlengths
6
9.26k
old_file
stringlengths
6
292
subject
stringlengths
0
4.45k
Java
apache-2.0
6db757a212b95cc64a5397bdbb10ba30493e0482
0
gradle/gradle,blindpirate/gradle,blindpirate/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle
/* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api.plugins; import com.google.common.collect.ImmutableSet; import org.gradle.api.Action; import org.gradle.api.Incubating; import org.gradle.api.Plugin; import org.gradle.api.Project; import org.gradle.api.artifacts.Configuration; import org.gradle.api.artifacts.ConfigurationContainer; import org.gradle.api.artifacts.type.ArtifactTypeDefinition; import org.gradle.api.attributes.AttributesSchema; import org.gradle.api.attributes.LibraryElements; import org.gradle.api.attributes.Usage; import org.gradle.api.file.SourceDirectorySet; import org.gradle.api.internal.ConventionMapping; import org.gradle.api.internal.IConventionAware; import org.gradle.api.internal.artifacts.JavaEcosystemSupport; import org.gradle.api.internal.artifacts.configurations.ConfigurationInternal; import org.gradle.api.internal.artifacts.dsl.ComponentMetadataHandlerInternal; import org.gradle.api.internal.plugins.DslObject; import org.gradle.api.internal.project.ProjectInternal; import org.gradle.api.model.ObjectFactory; import org.gradle.api.plugins.internal.DefaultJavaPluginConvention; import org.gradle.api.plugins.internal.DefaultJavaPluginExtension; import org.gradle.api.plugins.internal.JvmPluginsHelper; import org.gradle.api.reporting.DirectoryReport; import org.gradle.api.reporting.ReportingExtension; import org.gradle.api.tasks.SourceSet; import org.gradle.api.tasks.SourceSetContainer; import org.gradle.api.tasks.TaskProvider; import org.gradle.api.tasks.compile.AbstractCompile; import org.gradle.api.tasks.compile.JavaCompile; import org.gradle.api.tasks.javadoc.Javadoc; import org.gradle.api.tasks.testing.JUnitXmlReport; import org.gradle.api.tasks.testing.Test; import org.gradle.internal.component.external.model.JavaEcosystemVariantDerivationStrategy; import org.gradle.internal.deprecation.DeprecatableConfiguration; import org.gradle.jvm.toolchain.JavaInstallationRegistry; import org.gradle.language.base.plugins.LifecycleBasePlugin; import org.gradle.language.jvm.tasks.ProcessResources; import javax.inject.Inject; import java.io.File; import java.util.Set; import java.util.concurrent.Callable; /** * <p>A {@link org.gradle.api.Plugin} which compiles and tests Java source, and assembles it into a JAR file.</p> */ public class JavaBasePlugin implements Plugin<ProjectInternal> { public static final String CHECK_TASK_NAME = LifecycleBasePlugin.CHECK_TASK_NAME; public static final String VERIFICATION_GROUP = LifecycleBasePlugin.VERIFICATION_GROUP; public static final String BUILD_TASK_NAME = LifecycleBasePlugin.BUILD_TASK_NAME; public static final String BUILD_DEPENDENTS_TASK_NAME = "buildDependents"; public static final String BUILD_NEEDED_TASK_NAME = "buildNeeded"; public static final String DOCUMENTATION_GROUP = "documentation"; /** * Set this property to use JARs build from subprojects, instead of the classes folder from these project, on the compile classpath. * The main use case for this is to mitigate performance issues on very large multi-projects building on Windows. * Setting this property will cause the 'jar' task of all subprojects in the dependency tree to always run during compilation. * * @since 5.6 */ @Incubating public static final String COMPILE_CLASSPATH_PACKAGING_SYSTEM_PROPERTY = "org.gradle.java.compile-classpath-packaging"; /** * A list of known artifact types which are known to prevent from * publication. * * @since 5.3 */ public static final Set<String> UNPUBLISHABLE_VARIANT_ARTIFACTS = ImmutableSet.of( ArtifactTypeDefinition.JVM_CLASS_DIRECTORY, ArtifactTypeDefinition.JVM_RESOURCES_DIRECTORY, ArtifactTypeDefinition.DIRECTORY_TYPE ); private final ObjectFactory objectFactory; private final JavaInstallationRegistry javaInstallationRegistry; private final boolean javaClasspathPackaging; @Inject public JavaBasePlugin(ObjectFactory objectFactory, JavaInstallationRegistry javaInstallationRegistry) { this.objectFactory = objectFactory; this.javaInstallationRegistry = javaInstallationRegistry; this.javaClasspathPackaging = Boolean.getBoolean(COMPILE_CLASSPATH_PACKAGING_SYSTEM_PROPERTY); } @Override public void apply(final ProjectInternal project) { project.getPluginManager().apply(BasePlugin.class); project.getPluginManager().apply(ReportingBasePlugin.class); JavaPluginConvention javaConvention = addExtensions(project); configureSourceSetDefaults(javaConvention); configureCompileDefaults(project, javaConvention); configureJavaDoc(project, javaConvention); configureTest(project, javaConvention); configureBuildNeeded(project); configureBuildDependents(project); configureSchema(project); bridgeToSoftwareModelIfNecessary(project); configureVariantDerivationStrategy(project); } private void configureVariantDerivationStrategy(ProjectInternal project) { ComponentMetadataHandlerInternal metadataHandler = (ComponentMetadataHandlerInternal) project.getDependencies().getComponents(); metadataHandler.setVariantDerivationStrategy(JavaEcosystemVariantDerivationStrategy.getInstance()); } private JavaPluginConvention addExtensions(final ProjectInternal project) { JavaPluginConvention javaConvention = new DefaultJavaPluginConvention(project, objectFactory); project.getConvention().getPlugins().put("java", javaConvention); project.getExtensions().add(SourceSetContainer.class, "sourceSets", javaConvention.getSourceSets()); project.getExtensions().create(JavaPluginExtension.class, "java", DefaultJavaPluginExtension.class, javaConvention, project); project.getExtensions().add(JavaInstallationRegistry.class, "javaInstalls", javaInstallationRegistry); return javaConvention; } private void bridgeToSoftwareModelIfNecessary(ProjectInternal project) { project.addRuleBasedPluginListener(targetProject -> { targetProject.getPluginManager().apply(JavaBasePluginRules.class); }); } private void configureSchema(ProjectInternal project) { AttributesSchema attributesSchema = project.getDependencies().getAttributesSchema(); JavaEcosystemSupport.configureSchema(attributesSchema, objectFactory); project.getDependencies().getArtifactTypes().create(ArtifactTypeDefinition.JAR_TYPE).getAttributes() .attribute(Usage.USAGE_ATTRIBUTE, objectFactory.named(Usage.class, Usage.JAVA_RUNTIME)) .attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, objectFactory.named(LibraryElements.class, LibraryElements.JAR)); } private void configureSourceSetDefaults(final JavaPluginConvention pluginConvention) { final Project project = pluginConvention.getProject(); pluginConvention.getSourceSets().all(sourceSet -> { ConventionMapping outputConventionMapping = ((IConventionAware) sourceSet.getOutput()).getConventionMapping(); ConfigurationContainer configurations = project.getConfigurations(); defineConfigurationsForSourceSet(sourceSet, configurations, pluginConvention); definePathsForSourceSet(sourceSet, outputConventionMapping, project); createProcessResourcesTask(sourceSet, sourceSet.getResources(), project); TaskProvider<JavaCompile> compileTask = createCompileJavaTask(sourceSet, sourceSet.getJava(), project); createClassesTask(sourceSet, project); configureLibraryElements(compileTask, sourceSet, configurations, project.getObjects()); configureTargetPlatform(compileTask, sourceSet, configurations, pluginConvention); JvmPluginsHelper.configureOutputDirectoryForSourceSet(sourceSet, sourceSet.getJava(), project, compileTask, compileTask.map(JavaCompile::getOptions)); }); } private void configureLibraryElements(TaskProvider<JavaCompile> compileTaskProvider, SourceSet sourceSet, ConfigurationContainer configurations, ObjectFactory objectFactory) { Action<ConfigurationInternal> configureLibraryElements = JvmPluginsHelper.configureLibraryElementsAttributeForCompileClasspath(javaClasspathPackaging, sourceSet, compileTaskProvider, objectFactory); ((ConfigurationInternal) configurations.getByName(sourceSet.getCompileClasspathConfigurationName())).beforeLocking(configureLibraryElements); } private void configureTargetPlatform(TaskProvider<JavaCompile> compileTaskProvider, SourceSet sourceSet, ConfigurationContainer configurations, JavaPluginConvention pluginConvention) { Action<ConfigurationInternal> configureDefaultTargetPlatform = JvmPluginsHelper.configureDefaultTargetPlatform(pluginConvention, false, compileTaskProvider); ((ConfigurationInternal) configurations.getByName(sourceSet.getCompileClasspathConfigurationName())).beforeLocking(configureDefaultTargetPlatform); ((ConfigurationInternal) configurations.getByName(sourceSet.getRuntimeClasspathConfigurationName())).beforeLocking(configureDefaultTargetPlatform); } private TaskProvider<JavaCompile> createCompileJavaTask(final SourceSet sourceSet, final SourceDirectorySet sourceDirectorySet, final Project target) { return target.getTasks().register(sourceSet.getCompileJavaTaskName(), JavaCompile.class, compileTask -> { compileTask.setDescription("Compiles " + sourceDirectorySet + "."); compileTask.setSource(sourceDirectorySet); ConventionMapping conventionMapping = compileTask.getConventionMapping(); conventionMapping.map("classpath", () -> sourceSet.getCompileClasspath()); JvmPluginsHelper.configureAnnotationProcessorPath(sourceSet, sourceDirectorySet, compileTask.getOptions(), target); String generatedHeadersDir = "generated/sources/headers/" + sourceDirectorySet.getName() + "/" + sourceSet.getName(); compileTask.getOptions().getHeaderOutputDirectory().convention(target.getLayout().getBuildDirectory().dir(generatedHeadersDir)); JavaPluginExtension javaPluginExtension = target.getExtensions().getByType(JavaPluginExtension.class); compileTask.getModularity().getInferModulePath().convention(javaPluginExtension.getModularity().getInferModulePath()); }); } private void createProcessResourcesTask(final SourceSet sourceSet, final SourceDirectorySet resourceSet, final Project target) { target.getTasks().register(sourceSet.getProcessResourcesTaskName(), ProcessResources.class, resourcesTask -> { resourcesTask.setDescription("Processes " + resourceSet + "."); new DslObject(resourcesTask.getRootSpec()) .getConventionMapping() .map("destinationDir", (Callable<File>) () -> sourceSet.getOutput().getResourcesDir()); resourcesTask.from(resourceSet); }); } private void createClassesTask(final SourceSet sourceSet, Project target) { sourceSet.compiledBy( target.getTasks().register(sourceSet.getClassesTaskName(), classesTask -> { classesTask.setGroup(LifecycleBasePlugin.BUILD_GROUP); classesTask.setDescription("Assembles " + sourceSet.getOutput() + "."); classesTask.dependsOn(sourceSet.getOutput().getDirs()); classesTask.dependsOn(sourceSet.getCompileJavaTaskName()); classesTask.dependsOn(sourceSet.getProcessResourcesTaskName()); }) ); } private void definePathsForSourceSet(final SourceSet sourceSet, ConventionMapping outputConventionMapping, final Project project) { outputConventionMapping.map("resourcesDir", () -> { String classesDirName = "resources/" + sourceSet.getName(); return new File(project.getBuildDir(), classesDirName); }); sourceSet.getJava().srcDir("src/" + sourceSet.getName() + "/java"); sourceSet.getResources().srcDir("src/" + sourceSet.getName() + "/resources"); } private void defineConfigurationsForSourceSet(SourceSet sourceSet, ConfigurationContainer configurations, final JavaPluginConvention convention) { String compileConfigurationName = sourceSet.getCompileConfigurationName(); String implementationConfigurationName = sourceSet.getImplementationConfigurationName(); String runtimeConfigurationName = sourceSet.getRuntimeConfigurationName(); String runtimeOnlyConfigurationName = sourceSet.getRuntimeOnlyConfigurationName(); String compileOnlyConfigurationName = sourceSet.getCompileOnlyConfigurationName(); String compileClasspathConfigurationName = sourceSet.getCompileClasspathConfigurationName(); String annotationProcessorConfigurationName = sourceSet.getAnnotationProcessorConfigurationName(); String runtimeClasspathConfigurationName = sourceSet.getRuntimeClasspathConfigurationName(); String apiElementsConfigurationName = sourceSet.getApiElementsConfigurationName(); String runtimeElementsConfigurationName = sourceSet.getRuntimeElementsConfigurationName(); String sourceSetName = sourceSet.toString(); DeprecatableConfiguration compileConfiguration = (DeprecatableConfiguration) configurations.maybeCreate(compileConfigurationName); compileConfiguration.setVisible(false); compileConfiguration.setDescription("Dependencies for " + sourceSetName + " (deprecated, use '" + implementationConfigurationName + "' instead)."); Configuration implementationConfiguration = configurations.maybeCreate(implementationConfigurationName); implementationConfiguration.setVisible(false); implementationConfiguration.setDescription("Implementation only dependencies for " + sourceSetName + "."); implementationConfiguration.setCanBeConsumed(false); implementationConfiguration.setCanBeResolved(false); implementationConfiguration.extendsFrom(compileConfiguration); DeprecatableConfiguration runtimeConfiguration = (DeprecatableConfiguration) configurations.maybeCreate(runtimeConfigurationName); runtimeConfiguration.setVisible(false); runtimeConfiguration.extendsFrom(compileConfiguration); runtimeConfiguration.setDescription("Runtime dependencies for " + sourceSetName + " (deprecated, use '" + runtimeOnlyConfigurationName + "' instead)."); DeprecatableConfiguration compileOnlyConfiguration = (DeprecatableConfiguration) configurations.maybeCreate(compileOnlyConfigurationName); compileOnlyConfiguration.setVisible(false); compileOnlyConfiguration.setDescription("Compile only dependencies for " + sourceSetName + "."); ConfigurationInternal compileClasspathConfiguration = (ConfigurationInternal) configurations.maybeCreate(compileClasspathConfigurationName); compileClasspathConfiguration.setVisible(false); compileClasspathConfiguration.extendsFrom(compileOnlyConfiguration, implementationConfiguration); compileClasspathConfiguration.setDescription("Compile classpath for " + sourceSetName + "."); compileClasspathConfiguration.setCanBeConsumed(false); JvmPluginsHelper.configureAttributesForCompileClasspath(compileClasspathConfiguration, objectFactory); ConfigurationInternal annotationProcessorConfiguration = (ConfigurationInternal) configurations.maybeCreate(annotationProcessorConfigurationName); annotationProcessorConfiguration.setVisible(false); annotationProcessorConfiguration.setDescription("Annotation processors and their dependencies for " + sourceSetName + "."); annotationProcessorConfiguration.setCanBeConsumed(false); annotationProcessorConfiguration.setCanBeResolved(true); JvmPluginsHelper.configureAttributesForRuntimeClasspath(annotationProcessorConfiguration, objectFactory); Configuration runtimeOnlyConfiguration = configurations.maybeCreate(runtimeOnlyConfigurationName); runtimeOnlyConfiguration.setVisible(false); runtimeOnlyConfiguration.setCanBeConsumed(false); runtimeOnlyConfiguration.setCanBeResolved(false); runtimeOnlyConfiguration.setDescription("Runtime only dependencies for " + sourceSetName + "."); ConfigurationInternal runtimeClasspathConfiguration = (ConfigurationInternal) configurations.maybeCreate(runtimeClasspathConfigurationName); runtimeClasspathConfiguration.setVisible(false); runtimeClasspathConfiguration.setCanBeConsumed(false); runtimeClasspathConfiguration.setCanBeResolved(true); runtimeClasspathConfiguration.setDescription("Runtime classpath of " + sourceSetName + "."); runtimeClasspathConfiguration.extendsFrom(runtimeOnlyConfiguration, runtimeConfiguration, implementationConfiguration); JvmPluginsHelper.configureAttributesForRuntimeClasspath(runtimeClasspathConfiguration, objectFactory); sourceSet.setCompileClasspath(compileClasspathConfiguration); sourceSet.setRuntimeClasspath(sourceSet.getOutput().plus(runtimeClasspathConfiguration)); sourceSet.setAnnotationProcessorPath(annotationProcessorConfiguration); compileConfiguration.deprecateForDeclaration(implementationConfigurationName); compileConfiguration.deprecateForConsumption(apiElementsConfigurationName); compileConfiguration.deprecateForResolution(compileClasspathConfigurationName); compileOnlyConfiguration.deprecateForConsumption(apiElementsConfigurationName); compileOnlyConfiguration.deprecateForResolution(compileClasspathConfigurationName); runtimeConfiguration.deprecateForDeclaration(runtimeOnlyConfigurationName); runtimeConfiguration.deprecateForConsumption(runtimeElementsConfigurationName); runtimeConfiguration.deprecateForResolution(runtimeClasspathConfigurationName); compileClasspathConfiguration.deprecateForDeclaration(implementationConfigurationName, compileOnlyConfigurationName); runtimeClasspathConfiguration.deprecateForDeclaration(implementationConfigurationName, compileOnlyConfigurationName, runtimeOnlyConfigurationName); } private void configureCompileDefaults(final Project project, final JavaPluginConvention javaConvention) { project.getTasks().withType(AbstractCompile.class).configureEach(compile -> { ConventionMapping conventionMapping = compile.getConventionMapping(); conventionMapping.map("sourceCompatibility", () -> javaConvention.getSourceCompatibility().toString()); conventionMapping.map("targetCompatibility", () -> javaConvention.getTargetCompatibility().toString()); }); } private void configureJavaDoc(final Project project, final JavaPluginConvention convention) { project.getTasks().withType(Javadoc.class).configureEach(javadoc -> { ConventionMapping conventionMapping = javadoc.getConventionMapping(); conventionMapping.map("destinationDir", () -> new File(convention.getDocsDir(), "javadoc")); conventionMapping.map("title", () -> project.getExtensions().getByType(ReportingExtension.class).getApiDocTitle()); }); } private void configureBuildNeeded(Project project) { project.getTasks().register(BUILD_NEEDED_TASK_NAME, buildTask -> { buildTask.setDescription("Assembles and tests this project and all projects it depends on."); buildTask.setGroup(BasePlugin.BUILD_GROUP); buildTask.dependsOn(BUILD_TASK_NAME); }); } private void configureBuildDependents(Project project) { project.getTasks().register(BUILD_DEPENDENTS_TASK_NAME, buildTask -> { buildTask.setDescription("Assembles and tests this project and all projects that depend on it."); buildTask.setGroup(BasePlugin.BUILD_GROUP); buildTask.dependsOn(BUILD_TASK_NAME); boolean hasIncludedBuilds = !buildTask.getProject().getGradle().getIncludedBuilds().isEmpty(); buildTask.doFirst(task -> { if (hasIncludedBuilds) { task.getLogger().warn("[composite-build] Warning: `" + task.getPath() + "` task does not build included builds."); } }); }); } private void configureTest(final Project project, final JavaPluginConvention convention) { project.getTasks().withType(Test.class).configureEach(test -> configureTestDefaults(test, project, convention)); } private void configureTestDefaults(final Test test, Project project, final JavaPluginConvention convention) { DirectoryReport htmlReport = test.getReports().getHtml(); JUnitXmlReport xmlReport = test.getReports().getJunitXml(); // TODO - should replace `testResultsDir` and `testReportDir` with `Property` types and map their values xmlReport.getOutputLocation().convention(project.getLayout().getProjectDirectory().dir(project.provider(() -> new File(convention.getTestResultsDir(), test.getName()).getAbsolutePath()))); htmlReport.getOutputLocation().convention(project.getLayout().getProjectDirectory().dir(project.provider(() -> new File(convention.getTestReportDir(), test.getName()).getAbsolutePath()))); test.getBinaryResultsDirectory().convention(project.getLayout().getProjectDirectory().dir(project.provider(() -> new File(convention.getTestResultsDir(), test.getName() + "/binary").getAbsolutePath()))); test.workingDir(project.getProjectDir()); } }
subprojects/plugins/src/main/java/org/gradle/api/plugins/JavaBasePlugin.java
/* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api.plugins; import com.google.common.collect.ImmutableSet; import org.gradle.api.Action; import org.gradle.api.Incubating; import org.gradle.api.Plugin; import org.gradle.api.Project; import org.gradle.api.Task; import org.gradle.api.artifacts.Configuration; import org.gradle.api.artifacts.ConfigurationContainer; import org.gradle.api.artifacts.type.ArtifactTypeDefinition; import org.gradle.api.attributes.AttributesSchema; import org.gradle.api.attributes.LibraryElements; import org.gradle.api.attributes.Usage; import org.gradle.api.file.SourceDirectorySet; import org.gradle.api.internal.ConventionMapping; import org.gradle.api.internal.IConventionAware; import org.gradle.api.internal.artifacts.JavaEcosystemSupport; import org.gradle.api.internal.artifacts.configurations.ConfigurationInternal; import org.gradle.api.internal.artifacts.dsl.ComponentMetadataHandlerInternal; import org.gradle.api.internal.plugins.DslObject; import org.gradle.api.internal.project.ProjectInternal; import org.gradle.api.model.ObjectFactory; import org.gradle.api.plugins.internal.DefaultJavaPluginConvention; import org.gradle.api.plugins.internal.DefaultJavaPluginExtension; import org.gradle.api.plugins.internal.JvmPluginsHelper; import org.gradle.api.provider.Provider; import org.gradle.api.reporting.DirectoryReport; import org.gradle.api.reporting.ReportingExtension; import org.gradle.api.tasks.SourceSet; import org.gradle.api.tasks.SourceSetContainer; import org.gradle.api.tasks.TaskProvider; import org.gradle.api.tasks.compile.AbstractCompile; import org.gradle.api.tasks.compile.JavaCompile; import org.gradle.api.tasks.javadoc.Javadoc; import org.gradle.api.tasks.testing.JUnitXmlReport; import org.gradle.api.tasks.testing.Test; import org.gradle.internal.component.external.model.JavaEcosystemVariantDerivationStrategy; import org.gradle.internal.deprecation.DeprecatableConfiguration; import org.gradle.internal.model.RuleBasedPluginListener; import org.gradle.jvm.toolchain.JavaInstallationRegistry; import org.gradle.language.base.plugins.LifecycleBasePlugin; import org.gradle.language.jvm.tasks.ProcessResources; import javax.inject.Inject; import java.io.File; import java.util.Set; import java.util.concurrent.Callable; /** * <p>A {@link org.gradle.api.Plugin} which compiles and tests Java source, and assembles it into a JAR file.</p> */ public class JavaBasePlugin implements Plugin<ProjectInternal> { public static final String CHECK_TASK_NAME = LifecycleBasePlugin.CHECK_TASK_NAME; public static final String VERIFICATION_GROUP = LifecycleBasePlugin.VERIFICATION_GROUP; public static final String BUILD_TASK_NAME = LifecycleBasePlugin.BUILD_TASK_NAME; public static final String BUILD_DEPENDENTS_TASK_NAME = "buildDependents"; public static final String BUILD_NEEDED_TASK_NAME = "buildNeeded"; public static final String DOCUMENTATION_GROUP = "documentation"; /** * Set this property to use JARs build from subprojects, instead of the classes folder from these project, on the compile classpath. * The main use case for this is to mitigate performance issues on very large multi-projects building on Windows. * Setting this property will cause the 'jar' task of all subprojects in the dependency tree to always run during compilation. * * @since 5.6 */ @Incubating public static final String COMPILE_CLASSPATH_PACKAGING_SYSTEM_PROPERTY = "org.gradle.java.compile-classpath-packaging"; /** * A list of known artifact types which are known to prevent from * publication. * * @since 5.3 */ public static final Set<String> UNPUBLISHABLE_VARIANT_ARTIFACTS = ImmutableSet.of( ArtifactTypeDefinition.JVM_CLASS_DIRECTORY, ArtifactTypeDefinition.JVM_RESOURCES_DIRECTORY, ArtifactTypeDefinition.DIRECTORY_TYPE ); private final ObjectFactory objectFactory; private final JavaInstallationRegistry javaInstallationRegistry; private final boolean javaClasspathPackaging; @Inject public JavaBasePlugin(ObjectFactory objectFactory, JavaInstallationRegistry javaInstallationRegistry) { this.objectFactory = objectFactory; this.javaInstallationRegistry = javaInstallationRegistry; this.javaClasspathPackaging = Boolean.getBoolean(COMPILE_CLASSPATH_PACKAGING_SYSTEM_PROPERTY); } @Override public void apply(final ProjectInternal project) { project.getPluginManager().apply(BasePlugin.class); project.getPluginManager().apply(ReportingBasePlugin.class); JavaPluginConvention javaConvention = addExtensions(project); configureSourceSetDefaults(javaConvention); configureCompileDefaults(project, javaConvention); configureJavaDoc(project, javaConvention); configureTest(project, javaConvention); configureBuildNeeded(project); configureBuildDependents(project); configureSchema(project); bridgeToSoftwareModelIfNecessary(project); configureVariantDerivationStrategy(project); } private void configureVariantDerivationStrategy(ProjectInternal project) { ComponentMetadataHandlerInternal metadataHandler = (ComponentMetadataHandlerInternal) project.getDependencies().getComponents(); metadataHandler.setVariantDerivationStrategy(JavaEcosystemVariantDerivationStrategy.getInstance()); } private JavaPluginConvention addExtensions(final ProjectInternal project) { JavaPluginConvention javaConvention = new DefaultJavaPluginConvention(project, objectFactory); project.getConvention().getPlugins().put("java", javaConvention); project.getExtensions().add(SourceSetContainer.class, "sourceSets", javaConvention.getSourceSets()); project.getExtensions().create(JavaPluginExtension.class, "java", DefaultJavaPluginExtension.class, javaConvention, project); project.getExtensions().add(JavaInstallationRegistry.class, "javaInstalls", javaInstallationRegistry); return javaConvention; } private void bridgeToSoftwareModelIfNecessary(ProjectInternal project) { project.addRuleBasedPluginListener(new RuleBasedPluginListener() { @Override public void prepareForRuleBasedPlugins(Project project) { project.getPluginManager().apply(JavaBasePluginRules.class); } }); } private void configureSchema(ProjectInternal project) { AttributesSchema attributesSchema = project.getDependencies().getAttributesSchema(); JavaEcosystemSupport.configureSchema(attributesSchema, objectFactory); project.getDependencies().getArtifactTypes().create(ArtifactTypeDefinition.JAR_TYPE).getAttributes() .attribute(Usage.USAGE_ATTRIBUTE, objectFactory.named(Usage.class, Usage.JAVA_RUNTIME)) .attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, objectFactory.named(LibraryElements.class, LibraryElements.JAR)); } private void configureSourceSetDefaults(final JavaPluginConvention pluginConvention) { final Project project = pluginConvention.getProject(); pluginConvention.getSourceSets().all(new Action<SourceSet>() { @Override public void execute(final SourceSet sourceSet) { ConventionMapping outputConventionMapping = ((IConventionAware) sourceSet.getOutput()).getConventionMapping(); ConfigurationContainer configurations = project.getConfigurations(); defineConfigurationsForSourceSet(sourceSet, configurations, pluginConvention); definePathsForSourceSet(sourceSet, outputConventionMapping, project); createProcessResourcesTask(sourceSet, sourceSet.getResources(), project); TaskProvider<JavaCompile> compileTask = createCompileJavaTask(sourceSet, sourceSet.getJava(), project); createClassesTask(sourceSet, project); configureLibraryElements(compileTask, sourceSet, configurations, project.getObjects()); configureTargetPlatform(compileTask, sourceSet, configurations, pluginConvention); JvmPluginsHelper.configureOutputDirectoryForSourceSet(sourceSet, sourceSet.getJava(), project, compileTask, compileTask.map(JavaCompile::getOptions)); } }); } private void configureLibraryElements(TaskProvider<JavaCompile> compileTaskProvider, SourceSet sourceSet, ConfigurationContainer configurations, ObjectFactory objectFactory) { Action<ConfigurationInternal> configureLibraryElements = JvmPluginsHelper.configureLibraryElementsAttributeForCompileClasspath(javaClasspathPackaging, sourceSet, compileTaskProvider, objectFactory); ((ConfigurationInternal) configurations.getByName(sourceSet.getCompileClasspathConfigurationName())).beforeLocking(configureLibraryElements); } private void configureTargetPlatform(TaskProvider<JavaCompile> compileTaskProvider, SourceSet sourceSet, ConfigurationContainer configurations, JavaPluginConvention pluginConvention) { Action<ConfigurationInternal> configureDefaultTargetPlatform = JvmPluginsHelper.configureDefaultTargetPlatform(pluginConvention, false, compileTaskProvider); ((ConfigurationInternal) configurations.getByName(sourceSet.getCompileClasspathConfigurationName())).beforeLocking(configureDefaultTargetPlatform); ((ConfigurationInternal) configurations.getByName(sourceSet.getRuntimeClasspathConfigurationName())).beforeLocking(configureDefaultTargetPlatform); } private TaskProvider<JavaCompile> createCompileJavaTask(final SourceSet sourceSet, final SourceDirectorySet sourceDirectorySet, final Project target) { return target.getTasks().register(sourceSet.getCompileJavaTaskName(), JavaCompile.class, new Action<JavaCompile>() { @Override public void execute(JavaCompile compileTask) { compileTask.setDescription("Compiles " + sourceDirectorySet + "."); compileTask.setSource(sourceDirectorySet); ConventionMapping conventionMapping = compileTask.getConventionMapping(); conventionMapping.map("classpath", new Callable<Object>() { @Override public Object call() { return sourceSet.getCompileClasspath(); } }); JvmPluginsHelper.configureAnnotationProcessorPath(sourceSet, sourceDirectorySet, compileTask.getOptions(), target); String generatedHeadersDir = "generated/sources/headers/" + sourceDirectorySet.getName() + "/" + sourceSet.getName(); compileTask.getOptions().getHeaderOutputDirectory().convention(target.getLayout().getBuildDirectory().dir(generatedHeadersDir)); JavaPluginExtension javaPluginExtension = target.getExtensions().getByType(JavaPluginExtension.class); compileTask.getModularity().getInferModulePath().convention(javaPluginExtension.getModularity().getInferModulePath()); } }); } private void createProcessResourcesTask(final SourceSet sourceSet, final SourceDirectorySet resourceSet, final Project target) { target.getTasks().register(sourceSet.getProcessResourcesTaskName(), ProcessResources.class, new Action<ProcessResources>() { @Override public void execute(ProcessResources resourcesTask) { resourcesTask.setDescription("Processes " + resourceSet + "."); new DslObject(resourcesTask.getRootSpec()).getConventionMapping().map("destinationDir", new Callable<File>() { @Override public File call() { return sourceSet.getOutput().getResourcesDir(); } }); resourcesTask.from(resourceSet); } }); } private void createClassesTask(final SourceSet sourceSet, Project target) { Provider<Task> classesTask = target.getTasks().register(sourceSet.getClassesTaskName(), new Action<Task>() { @Override public void execute(Task classesTask) { classesTask.setGroup(LifecycleBasePlugin.BUILD_GROUP); classesTask.setDescription("Assembles " + sourceSet.getOutput() + "."); classesTask.dependsOn(sourceSet.getOutput().getDirs()); classesTask.dependsOn(sourceSet.getCompileJavaTaskName()); classesTask.dependsOn(sourceSet.getProcessResourcesTaskName()); } }); sourceSet.compiledBy(classesTask); } private void definePathsForSourceSet(final SourceSet sourceSet, ConventionMapping outputConventionMapping, final Project project) { outputConventionMapping.map("resourcesDir", new Callable<Object>() { @Override public Object call() { String classesDirName = "resources/" + sourceSet.getName(); return new File(project.getBuildDir(), classesDirName); } }); sourceSet.getJava().srcDir("src/" + sourceSet.getName() + "/java"); sourceSet.getResources().srcDir("src/" + sourceSet.getName() + "/resources"); } private void defineConfigurationsForSourceSet(SourceSet sourceSet, ConfigurationContainer configurations, final JavaPluginConvention convention) { String compileConfigurationName = sourceSet.getCompileConfigurationName(); String implementationConfigurationName = sourceSet.getImplementationConfigurationName(); String runtimeConfigurationName = sourceSet.getRuntimeConfigurationName(); String runtimeOnlyConfigurationName = sourceSet.getRuntimeOnlyConfigurationName(); String compileOnlyConfigurationName = sourceSet.getCompileOnlyConfigurationName(); String compileClasspathConfigurationName = sourceSet.getCompileClasspathConfigurationName(); String annotationProcessorConfigurationName = sourceSet.getAnnotationProcessorConfigurationName(); String runtimeClasspathConfigurationName = sourceSet.getRuntimeClasspathConfigurationName(); String apiElementsConfigurationName = sourceSet.getApiElementsConfigurationName(); String runtimeElementsConfigurationName = sourceSet.getRuntimeElementsConfigurationName(); String sourceSetName = sourceSet.toString(); DeprecatableConfiguration compileConfiguration = (DeprecatableConfiguration) configurations.maybeCreate(compileConfigurationName); compileConfiguration.setVisible(false); compileConfiguration.setDescription("Dependencies for " + sourceSetName + " (deprecated, use '" + implementationConfigurationName + "' instead)."); Configuration implementationConfiguration = configurations.maybeCreate(implementationConfigurationName); implementationConfiguration.setVisible(false); implementationConfiguration.setDescription("Implementation only dependencies for " + sourceSetName + "."); implementationConfiguration.setCanBeConsumed(false); implementationConfiguration.setCanBeResolved(false); implementationConfiguration.extendsFrom(compileConfiguration); DeprecatableConfiguration runtimeConfiguration = (DeprecatableConfiguration) configurations.maybeCreate(runtimeConfigurationName); runtimeConfiguration.setVisible(false); runtimeConfiguration.extendsFrom(compileConfiguration); runtimeConfiguration.setDescription("Runtime dependencies for " + sourceSetName + " (deprecated, use '" + runtimeOnlyConfigurationName + "' instead)."); DeprecatableConfiguration compileOnlyConfiguration = (DeprecatableConfiguration) configurations.maybeCreate(compileOnlyConfigurationName); compileOnlyConfiguration.setVisible(false); compileOnlyConfiguration.setDescription("Compile only dependencies for " + sourceSetName + "."); ConfigurationInternal compileClasspathConfiguration = (ConfigurationInternal) configurations.maybeCreate(compileClasspathConfigurationName); compileClasspathConfiguration.setVisible(false); compileClasspathConfiguration.extendsFrom(compileOnlyConfiguration, implementationConfiguration); compileClasspathConfiguration.setDescription("Compile classpath for " + sourceSetName + "."); compileClasspathConfiguration.setCanBeConsumed(false); JvmPluginsHelper.configureAttributesForCompileClasspath(compileClasspathConfiguration, objectFactory); ConfigurationInternal annotationProcessorConfiguration = (ConfigurationInternal) configurations.maybeCreate(annotationProcessorConfigurationName); annotationProcessorConfiguration.setVisible(false); annotationProcessorConfiguration.setDescription("Annotation processors and their dependencies for " + sourceSetName + "."); annotationProcessorConfiguration.setCanBeConsumed(false); annotationProcessorConfiguration.setCanBeResolved(true); JvmPluginsHelper.configureAttributesForRuntimeClasspath(annotationProcessorConfiguration, objectFactory); Configuration runtimeOnlyConfiguration = configurations.maybeCreate(runtimeOnlyConfigurationName); runtimeOnlyConfiguration.setVisible(false); runtimeOnlyConfiguration.setCanBeConsumed(false); runtimeOnlyConfiguration.setCanBeResolved(false); runtimeOnlyConfiguration.setDescription("Runtime only dependencies for " + sourceSetName + "."); ConfigurationInternal runtimeClasspathConfiguration = (ConfigurationInternal) configurations.maybeCreate(runtimeClasspathConfigurationName); runtimeClasspathConfiguration.setVisible(false); runtimeClasspathConfiguration.setCanBeConsumed(false); runtimeClasspathConfiguration.setCanBeResolved(true); runtimeClasspathConfiguration.setDescription("Runtime classpath of " + sourceSetName + "."); runtimeClasspathConfiguration.extendsFrom(runtimeOnlyConfiguration, runtimeConfiguration, implementationConfiguration); JvmPluginsHelper.configureAttributesForRuntimeClasspath(runtimeClasspathConfiguration, objectFactory); sourceSet.setCompileClasspath(compileClasspathConfiguration); sourceSet.setRuntimeClasspath(sourceSet.getOutput().plus(runtimeClasspathConfiguration)); sourceSet.setAnnotationProcessorPath(annotationProcessorConfiguration); compileConfiguration.deprecateForDeclaration(implementationConfigurationName); compileConfiguration.deprecateForConsumption(apiElementsConfigurationName); compileConfiguration.deprecateForResolution(compileClasspathConfigurationName); compileOnlyConfiguration.deprecateForConsumption(apiElementsConfigurationName); compileOnlyConfiguration.deprecateForResolution(compileClasspathConfigurationName); runtimeConfiguration.deprecateForDeclaration(runtimeOnlyConfigurationName); runtimeConfiguration.deprecateForConsumption(runtimeElementsConfigurationName); runtimeConfiguration.deprecateForResolution(runtimeClasspathConfigurationName); compileClasspathConfiguration.deprecateForDeclaration(implementationConfigurationName, compileOnlyConfigurationName); runtimeClasspathConfiguration.deprecateForDeclaration(implementationConfigurationName, compileOnlyConfigurationName, runtimeOnlyConfigurationName); } private void configureCompileDefaults(final Project project, final JavaPluginConvention javaConvention) { project.getTasks().withType(AbstractCompile.class).configureEach(new Action<AbstractCompile>() { @Override public void execute(final AbstractCompile compile) { ConventionMapping conventionMapping = compile.getConventionMapping(); conventionMapping.map("sourceCompatibility", new Callable<Object>() { @Override public Object call() { return javaConvention.getSourceCompatibility().toString(); } }); conventionMapping.map("targetCompatibility", new Callable<Object>() { @Override public Object call() { return javaConvention.getTargetCompatibility().toString(); } }); } }); } private void configureJavaDoc(final Project project, final JavaPluginConvention convention) { project.getTasks().withType(Javadoc.class).configureEach(new Action<Javadoc>() { @Override public void execute(Javadoc javadoc) { javadoc.getConventionMapping().map("destinationDir", new Callable<Object>() { @Override public Object call() { return new File(convention.getDocsDir(), "javadoc"); } }); javadoc.getConventionMapping().map("title", new Callable<Object>() { @Override public Object call() { return project.getExtensions().getByType(ReportingExtension.class).getApiDocTitle(); } }); } }); } private void configureBuildNeeded(Project project) { project.getTasks().register(BUILD_NEEDED_TASK_NAME, new Action<Task>() { @Override public void execute(Task buildTask) { buildTask.setDescription("Assembles and tests this project and all projects it depends on."); buildTask.setGroup(BasePlugin.BUILD_GROUP); buildTask.dependsOn(BUILD_TASK_NAME); } }); } private void configureBuildDependents(Project project) { project.getTasks().register(BUILD_DEPENDENTS_TASK_NAME, new Action<Task>() { @Override public void execute(Task buildTask) { buildTask.setDescription("Assembles and tests this project and all projects that depend on it."); buildTask.setGroup(BasePlugin.BUILD_GROUP); buildTask.dependsOn(BUILD_TASK_NAME); boolean hasIncludedBuilds = !buildTask.getProject().getGradle().getIncludedBuilds().isEmpty(); buildTask.doFirst(new Action<Task>() { @Override public void execute(Task task) { if (hasIncludedBuilds) { task.getLogger().warn("[composite-build] Warning: `" + task.getPath() + "` task does not build included builds."); } } }); } }); } private void configureTest(final Project project, final JavaPluginConvention convention) { project.getTasks().withType(Test.class).configureEach(test -> configureTestDefaults(test, project, convention)); } private void configureTestDefaults(final Test test, Project project, final JavaPluginConvention convention) { DirectoryReport htmlReport = test.getReports().getHtml(); JUnitXmlReport xmlReport = test.getReports().getJunitXml(); // TODO - should replace `testResultsDir` and `testReportDir` with `Property` types and map their values xmlReport.getOutputLocation().convention(project.getLayout().getProjectDirectory().dir(project.provider(() -> new File(convention.getTestResultsDir(), test.getName()).getAbsolutePath()))); htmlReport.getOutputLocation().convention(project.getLayout().getProjectDirectory().dir(project.provider(() -> new File(convention.getTestReportDir(), test.getName()).getAbsolutePath()))); test.getBinaryResultsDirectory().convention(project.getLayout().getProjectDirectory().dir(project.provider(() -> new File(convention.getTestResultsDir(), test.getName() + "/binary").getAbsolutePath()))); test.workingDir(project.getProjectDir()); } }
Replace anonymous by lambda in `JavaBasePlugin`
subprojects/plugins/src/main/java/org/gradle/api/plugins/JavaBasePlugin.java
Replace anonymous by lambda in `JavaBasePlugin`
Java
apache-2.0
a472f2d86d4c725eaf589262892f1a4801a38b70
0
caskdata/cdap,chtyim/cdap,chtyim/cdap,chtyim/cdap,chtyim/cdap,mpouttuclarke/cdap,mpouttuclarke/cdap,anthcp/cdap,anthcp/cdap,caskdata/cdap,mpouttuclarke/cdap,mpouttuclarke/cdap,chtyim/cdap,caskdata/cdap,hsaputra/cdap,hsaputra/cdap,anthcp/cdap,mpouttuclarke/cdap,hsaputra/cdap,chtyim/cdap,anthcp/cdap,caskdata/cdap,anthcp/cdap,caskdata/cdap,caskdata/cdap,hsaputra/cdap,hsaputra/cdap
/* * Copyright © 2014 Cask Data, 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 co.cask.cdap.api.dataset.lib; import co.cask.cdap.api.app.ApplicationConfigurer; import co.cask.cdap.api.dataset.DatasetProperties; import co.cask.cdap.internal.io.ReflectionSchemaGenerator; import co.cask.cdap.internal.io.Schema; import co.cask.cdap.internal.io.SchemaTypeAdapter; import co.cask.cdap.internal.io.TypeRepresentation; import co.cask.cdap.internal.io.UnsupportedTypeException; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.lang.reflect.Type; /** * Utility for describing {@link ObjectStore} and similar datasets within application configuration. */ public final class ObjectStores { private static final Gson GSON = new GsonBuilder() .registerTypeAdapter(Schema.class, new SchemaTypeAdapter()) .create(); private ObjectStores() {} /** * Adds {@link ObjectStore} dataset to be created at application deploy if not exists. * @param configurer application configurer * @param datasetName dataset name * @param type type of objects to be stored in {@link ObjectStore} * @param props any additional dataset properties * @throws UnsupportedTypeException */ public static void createObjectStore(ApplicationConfigurer configurer, String datasetName, Type type, DatasetProperties props) throws UnsupportedTypeException { configurer.createDataset(datasetName, ObjectStore.class, objectStoreProperties(type, props)); } /** * Same as {@link #createObjectStore(ApplicationConfigurer, String, Type, DatasetProperties)} but with empty * properties. */ public static void createObjectStore(ApplicationConfigurer configurer, String datasetName, Type type) throws UnsupportedTypeException { createObjectStore(configurer, datasetName, type, DatasetProperties.EMPTY); } /** * Adds {@link IndexedObjectStore} dataset to be created at application deploy if not exists. * @param configurer application configurer * @param datasetName dataset name * @param type type of objects to be stored in {@link IndexedObjectStore} * @param props any additional dataset properties * @throws UnsupportedTypeException */ public static void createIndexedObjectStore(ApplicationConfigurer configurer, String datasetName, Type type, DatasetProperties props) throws UnsupportedTypeException { configurer.createDataset(datasetName, IndexedObjectStore.class, objectStoreProperties(type, props)); } /** * Same as {@link #createIndexedObjectStore(ApplicationConfigurer, String, Type, DatasetProperties)} but with empty * properties. */ public static void createIndexedObjectStore(ApplicationConfigurer configurer, String datasetName, Type type) throws UnsupportedTypeException { createIndexedObjectStore(configurer, datasetName, type, DatasetProperties.EMPTY); } /** * Creates properties for {@link ObjectStore} dataset instance. * @param type type of objects to be stored in dataset * @return {@link DatasetProperties} for the dataset * @throws UnsupportedTypeException */ public static DatasetProperties objectStoreProperties(Type type, DatasetProperties props) throws UnsupportedTypeException { Schema schema = new ReflectionSchemaGenerator().generate(type); TypeRepresentation typeRep = new TypeRepresentation(type); return DatasetProperties.builder() .add("schema", GSON.toJson(schema)) .add("type", GSON.toJson(typeRep)) .addAll(props.getProperties()) .build(); } }
cdap-api/src/main/java/co/cask/cdap/api/dataset/lib/ObjectStores.java
/* * Copyright © 2014 Cask Data, 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 co.cask.cdap.api.dataset.lib; import co.cask.cdap.api.app.ApplicationConfigurer; import co.cask.cdap.api.dataset.DatasetProperties; import co.cask.cdap.internal.io.ReflectionSchemaGenerator; import co.cask.cdap.internal.io.Schema; import co.cask.cdap.internal.io.SchemaTypeAdapter; import co.cask.cdap.internal.io.TypeRepresentation; import co.cask.cdap.internal.io.UnsupportedTypeException; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.lang.reflect.Type; /** * Utility for describing {@link ObjectStore} and similar data sets within application configuration. */ public final class ObjectStores { private static final Gson GSON = new GsonBuilder() .registerTypeAdapter(Schema.class, new SchemaTypeAdapter()) .create(); private ObjectStores() {} /** * Adds {@link ObjectStore} data set to be created at application deploy if not exists. * @param configurer application configurer * @param datasetName data set name * @param type type of objects to be stored in {@link ObjectStore} * @param props any additional data set properties * @throws UnsupportedTypeException */ public static void createObjectStore(ApplicationConfigurer configurer, String datasetName, Type type, DatasetProperties props) throws UnsupportedTypeException { configurer.createDataset(datasetName, ObjectStore.class, objectStoreProperties(type, props)); } /** * Same as {@link #createObjectStore(ApplicationConfigurer, String, Type, DatasetProperties)} but with empty * properties. */ public static void createObjectStore(ApplicationConfigurer configurer, String datasetName, Type type) throws UnsupportedTypeException { createObjectStore(configurer, datasetName, type, DatasetProperties.EMPTY); } /** * Adds {@link IndexedObjectStore} data set to be created at application deploy if not exists. * @param configurer application configurer * @param datasetName data set name * @param type type of objects to be stored in {@link IndexedObjectStore} * @param props any additional data set properties * @throws UnsupportedTypeException */ public static void createIndexedObjectStore(ApplicationConfigurer configurer, String datasetName, Type type, DatasetProperties props) throws UnsupportedTypeException { configurer.createDataset(datasetName, IndexedObjectStore.class, objectStoreProperties(type, props)); } /** * Same as {@link #createIndexedObjectStore(ApplicationConfigurer, String, Type, DatasetProperties)} but with empty * properties. */ public static void createIndexedObjectStore(ApplicationConfigurer configurer, String datasetName, Type type) throws UnsupportedTypeException { createIndexedObjectStore(configurer, datasetName, type, DatasetProperties.EMPTY); } /** * Creates properties for {@link ObjectStore} data set instance. * @param type type of objects to be stored in data set * @return {@link DatasetProperties} for the data set * @throws UnsupportedTypeException */ public static DatasetProperties objectStoreProperties(Type type, DatasetProperties props) throws UnsupportedTypeException { Schema schema = new ReflectionSchemaGenerator().generate(type); TypeRepresentation typeRep = new TypeRepresentation(type); return DatasetProperties.builder() .add("schema", GSON.toJson(schema)) .add("type", GSON.toJson(typeRep)) .addAll(props.getProperties()) .build(); } }
Datasets: some renaming from data set to dataset
cdap-api/src/main/java/co/cask/cdap/api/dataset/lib/ObjectStores.java
Datasets: some renaming from data set to dataset
Java
apache-2.0
9ab20241f93f8047a52d949f9fc01b3846bcf01b
0
robin13/elasticsearch,nknize/elasticsearch,nknize/elasticsearch,nknize/elasticsearch,robin13/elasticsearch,GlenRSmith/elasticsearch,GlenRSmith/elasticsearch,GlenRSmith/elasticsearch,robin13/elasticsearch,robin13/elasticsearch,nknize/elasticsearch,GlenRSmith/elasticsearch,robin13/elasticsearch,nknize/elasticsearch,GlenRSmith/elasticsearch
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.ml.integration; import org.elasticsearch.ResourceNotFoundException; import org.elasticsearch.Version; import org.elasticsearch.action.admin.cluster.node.hotthreads.NodeHotThreads; import org.elasticsearch.action.admin.cluster.node.hotthreads.NodesHotThreadsResponse; import org.elasticsearch.action.support.master.AcknowledgedResponse; import org.elasticsearch.common.CheckedRunnable; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.util.concurrent.ConcurrentCollections; import org.elasticsearch.common.util.concurrent.ConcurrentMapLong; import org.elasticsearch.xpack.core.ml.action.DeleteDatafeedAction; import org.elasticsearch.xpack.core.ml.action.GetDatafeedsStatsAction; import org.elasticsearch.xpack.core.ml.action.GetJobsStatsAction; import org.elasticsearch.xpack.core.ml.action.KillProcessAction; import org.elasticsearch.xpack.core.ml.action.PutJobAction; import org.elasticsearch.xpack.core.ml.action.StopDatafeedAction; import org.elasticsearch.xpack.core.ml.datafeed.ChunkingConfig; import org.elasticsearch.xpack.core.ml.datafeed.DatafeedConfig; import org.elasticsearch.xpack.core.ml.datafeed.DatafeedState; import org.elasticsearch.xpack.core.ml.datafeed.DatafeedUpdate; import org.elasticsearch.xpack.core.ml.job.config.Job; import org.elasticsearch.xpack.core.ml.job.config.JobState; import org.elasticsearch.xpack.core.ml.job.process.autodetect.state.DataCounts; import org.hamcrest.Matcher; import org.junit.After; import java.time.Duration; import java.time.Instant; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import static org.elasticsearch.xpack.ml.support.BaseMlIntegTestCase.createDatafeed; import static org.elasticsearch.xpack.ml.support.BaseMlIntegTestCase.createDatafeedBuilder; import static org.elasticsearch.xpack.ml.support.BaseMlIntegTestCase.createScheduledJob; import static org.elasticsearch.xpack.ml.support.BaseMlIntegTestCase.getDataCounts; import static org.elasticsearch.xpack.ml.support.BaseMlIntegTestCase.indexDocs; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.hasSize; public class DatafeedJobsIT extends MlNativeAutodetectIntegTestCase { @After public void cleanup() { cleanUp(); } public void testLookbackOnly() throws Exception { client().admin().indices().prepareCreate("data-1") .setMapping("time", "type=date") .get(); long numDocs = randomIntBetween(32, 2048); long now = System.currentTimeMillis(); long oneWeekAgo = now - 604800000; long twoWeeksAgo = oneWeekAgo - 604800000; indexDocs(logger, "data-1", numDocs, twoWeeksAgo, oneWeekAgo); client().admin().indices().prepareCreate("data-2") .setMapping("time", "type=date") .get(); client().admin().cluster().prepareHealth("data-1", "data-2").setWaitForYellowStatus().get(); long numDocs2 = randomIntBetween(32, 2048); indexDocs(logger, "data-2", numDocs2, oneWeekAgo, now); Job.Builder job = createScheduledJob("lookback-job"); registerJob(job); PutJobAction.Response putJobResponse = putJob(job); assertThat(putJobResponse.getResponse().getJobVersion(), equalTo(Version.CURRENT)); openJob(job.getId()); assertBusy(() -> assertEquals(getJobStats(job.getId()).get(0).getState(), JobState.OPENED)); // Having a pattern with missing indices is acceptable List<String> indices = Arrays.asList("data-*", "missing-*"); DatafeedConfig datafeedConfig = createDatafeed(job.getId() + "-datafeed", job.getId(), indices); registerDatafeed(datafeedConfig); putDatafeed(datafeedConfig); startDatafeed(datafeedConfig.getId(), 0L, now); assertBusy(() -> { DataCounts dataCounts = getDataCounts(job.getId()); assertThat(dataCounts.getProcessedRecordCount(), equalTo(numDocs + numDocs2)); assertThat(dataCounts.getOutOfOrderTimeStampCount(), equalTo(0L)); GetDatafeedsStatsAction.Request request = new GetDatafeedsStatsAction.Request(datafeedConfig.getId()); GetDatafeedsStatsAction.Response response = client().execute(GetDatafeedsStatsAction.INSTANCE, request).actionGet(); assertThat(response.getResponse().results().get(0).getDatafeedState(), equalTo(DatafeedState.STOPPED)); }, 60, TimeUnit.SECONDS); waitUntilJobIsClosed(job.getId()); } public void testLookbackOnlyDataStream() throws Exception { String mapping = "{\n" + " \"properties\": {\n" + " \"time\": {\n" + " \"type\": \"date\"\n" + " }," + " \"@timestamp\": {\n" + " \"type\": \"date\"\n" + " }" + " }\n" + " }"; createDataStreamAndTemplate("datafeed_data_stream", mapping); long numDocs = randomIntBetween(32, 2048); long now = System.currentTimeMillis(); long oneWeekAgo = now - 604800000; long twoWeeksAgo = oneWeekAgo - 604800000; indexDocs(logger, "datafeed_data_stream", numDocs, twoWeeksAgo, oneWeekAgo); client().admin().cluster().prepareHealth("datafeed_data_stream").setWaitForYellowStatus().get(); Job.Builder job = createScheduledJob("lookback-data-stream-job"); registerJob(job); PutJobAction.Response putJobResponse = putJob(job); assertThat(putJobResponse.getResponse().getJobVersion(), equalTo(Version.CURRENT)); openJob(job.getId()); assertBusy(() -> assertEquals(getJobStats(job.getId()).get(0).getState(), JobState.OPENED)); DatafeedConfig datafeedConfig = createDatafeed(job.getId() + "-datafeed", job.getId(), Collections.singletonList("datafeed_data_stream")); registerDatafeed(datafeedConfig); putDatafeed(datafeedConfig); startDatafeed(datafeedConfig.getId(), 0L, now); assertBusy(() -> { DataCounts dataCounts = getDataCounts(job.getId()); assertThat(dataCounts.getProcessedRecordCount(), equalTo(numDocs)); assertThat(dataCounts.getOutOfOrderTimeStampCount(), equalTo(0L)); GetDatafeedsStatsAction.Request request = new GetDatafeedsStatsAction.Request(datafeedConfig.getId()); GetDatafeedsStatsAction.Response response = client().execute(GetDatafeedsStatsAction.INSTANCE, request).actionGet(); assertThat(response.getResponse().results().get(0).getDatafeedState(), equalTo(DatafeedState.STOPPED)); }, 60, TimeUnit.SECONDS); waitUntilJobIsClosed(job.getId()); } @AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/63973") public void testDatafeedTimingStats_DatafeedRecreated() throws Exception { client().admin().indices().prepareCreate("data") .setMapping("time", "type=date") .get(); long numDocs = randomIntBetween(32, 2048); Instant now = Instant.now(); indexDocs(logger, "data", numDocs, now.minus(Duration.ofDays(14)).toEpochMilli(), now.toEpochMilli()); Job.Builder job = createScheduledJob("lookback-job-datafeed-recreated"); String datafeedId = "lookback-datafeed-datafeed-recreated"; DatafeedConfig datafeedConfig = createDatafeed(datafeedId, job.getId(), Collections.singletonList("data")); registerJob(job); putJob(job); CheckedRunnable<Exception> openAndRunJob = () -> { openJob(job.getId()); assertBusy(() -> assertEquals(getJobStats(job.getId()).get(0).getState(), JobState.OPENED)); registerDatafeed(datafeedConfig); putDatafeed(datafeedConfig); // Datafeed did not do anything yet, hence search_count is equal to 0. assertDatafeedStats(datafeedId, DatafeedState.STOPPED, job.getId(), equalTo(0L)); startDatafeed(datafeedId, 0L, now.toEpochMilli()); assertBusy(() -> { assertThat(getDataCounts(job.getId()).getProcessedRecordCount(), equalTo(numDocs)); // Datafeed processed numDocs documents so search_count must be greater than 0. assertDatafeedStats(datafeedId, DatafeedState.STOPPED, job.getId(), greaterThan(0L)); }, 60, TimeUnit.SECONDS); deleteDatafeed(datafeedId); waitUntilJobIsClosed(job.getId()); }; openAndRunJob.run(); openAndRunJob.run(); } public void testDatafeedTimingStats_QueryDelayUpdated_TimingStatsNotReset() throws Exception { client().admin().indices().prepareCreate("data") .setMapping("time", "type=date") .get(); long numDocs = randomIntBetween(32, 2048); Instant now = Instant.now(); indexDocs(logger, "data", numDocs, now.minus(Duration.ofDays(14)).toEpochMilli(), now.toEpochMilli()); Job.Builder job = createScheduledJob("lookback-job-query-delay-updated"); registerJob(job); putJob(job); String datafeedId = "lookback-datafeed-query-delay-updated"; DatafeedConfig datafeedConfig = createDatafeed(datafeedId, job.getId(), Collections.singletonList("data")); registerDatafeed(datafeedConfig); putDatafeed(datafeedConfig); openJob(job.getId()); assertBusy(() -> assertEquals(getJobStats(job.getId()).get(0).getState(), JobState.OPENED)); // Datafeed did not do anything yet, hence search_count is equal to 0. assertDatafeedStats(datafeedId, DatafeedState.STOPPED, job.getId(), equalTo(0L)); startDatafeed(datafeedId, 0L, now.toEpochMilli()); assertBusy(() -> { assertThat(getDataCounts(job.getId()).getProcessedRecordCount(), equalTo(numDocs)); // Datafeed processed numDocs documents so search_count must be greater than 0. assertDatafeedStats(datafeedId, DatafeedState.STOPPED, job.getId(), greaterThan(0L)); }, 60, TimeUnit.SECONDS); waitUntilJobIsClosed(job.getId()); // Change something different than jobId, here: queryDelay. updateDatafeed(new DatafeedUpdate.Builder(datafeedId).setQueryDelay(TimeValue.timeValueSeconds(777)).build()); // Search_count is still greater than 0 (i.e. has not been reset by datafeed update) assertDatafeedStats(datafeedId, DatafeedState.STOPPED, job.getId(), greaterThan(0L)); } private void assertDatafeedStats(String datafeedId, DatafeedState state, String jobId, Matcher<Long> searchCountMatcher) { GetDatafeedsStatsAction.Request request = new GetDatafeedsStatsAction.Request(datafeedId); GetDatafeedsStatsAction.Response response = client().execute(GetDatafeedsStatsAction.INSTANCE, request).actionGet(); assertThat(response.getResponse().results(), hasSize(1)); GetDatafeedsStatsAction.Response.DatafeedStats stats = response.getResponse().results().get(0); assertThat(stats.getDatafeedState(), equalTo(state)); assertThat(stats.getTimingStats().getJobId(), equalTo(jobId)); assertThat(stats.getTimingStats().getSearchCount(), searchCountMatcher); } public void testRealtime() throws Exception { String jobId = "realtime-job"; String datafeedId = jobId + "-datafeed"; startRealtime(jobId); try { StopDatafeedAction.Response stopJobResponse = stopDatafeed(datafeedId); assertTrue(stopJobResponse.isStopped()); } catch (Exception e) { NodesHotThreadsResponse nodesHotThreadsResponse = client().admin().cluster().prepareNodesHotThreads().get(); int i = 0; for (NodeHotThreads nodeHotThreads : nodesHotThreadsResponse.getNodes()) { logger.info(i++ + ":\n" +nodeHotThreads.getHotThreads()); } throw e; } assertBusy(() -> { GetDatafeedsStatsAction.Request request = new GetDatafeedsStatsAction.Request(datafeedId); GetDatafeedsStatsAction.Response response = client().execute(GetDatafeedsStatsAction.INSTANCE, request).actionGet(); assertThat(response.getResponse().results().get(0).getDatafeedState(), equalTo(DatafeedState.STOPPED)); }); } public void testRealtime_noDataAndAutoStop() throws Exception { String jobId = "realtime-job-auto-stop"; String datafeedId = jobId + "-datafeed"; startRealtime(jobId, randomIntBetween(1, 3)); // Datafeed should auto-stop... assertBusy(() -> { GetDatafeedsStatsAction.Request request = new GetDatafeedsStatsAction.Request(datafeedId); GetDatafeedsStatsAction.Response response = client().execute(GetDatafeedsStatsAction.INSTANCE, request).actionGet(); assertThat(response.getResponse().results().get(0).getDatafeedState(), equalTo(DatafeedState.STOPPED)); }); // ...and should have auto-closed the job too assertBusy(() -> { GetJobsStatsAction.Request request = new GetJobsStatsAction.Request(jobId); GetJobsStatsAction.Response response = client().execute(GetJobsStatsAction.INSTANCE, request).actionGet(); assertThat(response.getResponse().results().get(0).getState(), equalTo(JobState.CLOSED)); }); } public void testRealtime_multipleStopCalls() throws Exception { String jobId = "realtime-job-multiple-stop"; final String datafeedId = jobId + "-datafeed"; startRealtime(jobId); ConcurrentMapLong<AssertionError> exceptions = ConcurrentCollections.newConcurrentMapLong(); // It's practically impossible to assert that a stop request has waited // for a concurrently executing request to finish before returning. // But we can assert the data feed has stopped after the request returns. Runnable stopDataFeed = () -> { StopDatafeedAction.Response stopJobResponse = stopDatafeed(datafeedId); if (stopJobResponse.isStopped() == false) { exceptions.put(Thread.currentThread().getId(), new AssertionError("Job is not stopped")); } GetDatafeedsStatsAction.Request request = new GetDatafeedsStatsAction.Request(datafeedId); GetDatafeedsStatsAction.Response response = client().execute(GetDatafeedsStatsAction.INSTANCE, request).actionGet(); if (response.getResponse().results().get(0).getDatafeedState() != DatafeedState.STOPPED) { exceptions.put(Thread.currentThread().getId(), new AssertionError("Expected STOPPED datafeed state got " + response.getResponse().results().get(0).getDatafeedState())); } }; // The idea is to hit the situation where one request waits for // the other to complete. This is difficult to schedule but // hopefully it will happen in CI int numThreads = 5; Thread [] threads = new Thread[numThreads]; for (int i=0; i<numThreads; i++) { threads[i] = new Thread(stopDataFeed); } for (int i=0; i<numThreads; i++) { threads[i].start(); } for (int i=0; i<numThreads; i++) { threads[i].join(); } if (exceptions.isEmpty() == false) { throw exceptions.values().iterator().next(); } } public void testRealtime_givenSimultaneousStopAndForceDelete() throws Throwable { String jobId = "realtime-job-stop-and-force-delete"; final String datafeedId = jobId + "-datafeed"; startRealtime(jobId); AtomicReference<Throwable> exception = new AtomicReference<>(); // The UI now force deletes datafeeds, which means they can be deleted while running. // The first step is to isolate the datafeed. But if it was already being stopped then // the datafeed may not be running by the time the isolate action is executed. This // test will sometimes (depending on thread scheduling) achieve this situation and ensure // the code is robust to it. Thread deleteDatafeedThread = new Thread(() -> { try { DeleteDatafeedAction.Request request = new DeleteDatafeedAction.Request(datafeedId); request.setForce(true); AcknowledgedResponse response = client().execute(DeleteDatafeedAction.INSTANCE, request).actionGet(); if (response.isAcknowledged()) { GetDatafeedsStatsAction.Request statsRequest = new GetDatafeedsStatsAction.Request(datafeedId); expectThrows(ResourceNotFoundException.class, () -> client().execute(GetDatafeedsStatsAction.INSTANCE, statsRequest).actionGet()); } else { exception.set(new AssertionError("Job is not deleted")); } } catch (AssertionError | Exception e) { exception.set(e); } }); deleteDatafeedThread.start(); try { stopDatafeed(datafeedId); } catch (ResourceNotFoundException e) { // This is OK - it means the thread running the delete fully completed before the stop started to execute } finally { deleteDatafeedThread.join(); } if (exception.get() != null) { throw exception.get(); } } public void testRealtime_GivenProcessIsKilled() throws Exception { String jobId = "realtime-job-given-process-is-killed"; String datafeedId = jobId + "-datafeed"; startRealtime(jobId); KillProcessAction.Request killRequest = new KillProcessAction.Request(jobId); client().execute(KillProcessAction.INSTANCE, killRequest).actionGet(); assertBusy(() -> { GetDatafeedsStatsAction.Request request = new GetDatafeedsStatsAction.Request(datafeedId); GetDatafeedsStatsAction.Response response = client().execute(GetDatafeedsStatsAction.INSTANCE, request).actionGet(); assertThat(response.getResponse().results().get(0).getDatafeedState(), equalTo(DatafeedState.STOPPED)); }); } /** * Stopping a lookback closes the associated job _after_ the stop call returns. * This test ensures that a kill request submitted during this close doesn't * put the job into the "failed" state. */ public void testStopLookbackFollowedByProcessKill() throws Exception { client().admin().indices().prepareCreate("data") .setMapping("time", "type=date") .get(); long numDocs = randomIntBetween(1024, 2048); long now = System.currentTimeMillis(); long oneWeekAgo = now - 604800000; long twoWeeksAgo = oneWeekAgo - 604800000; indexDocs(logger, "data", numDocs, twoWeeksAgo, oneWeekAgo); Job.Builder job = createScheduledJob("lookback-job-stopped-then-killed"); registerJob(job); PutJobAction.Response putJobResponse = putJob(job); assertThat(putJobResponse.getResponse().getJobVersion(), equalTo(Version.CURRENT)); openJob(job.getId()); assertBusy(() -> assertEquals(getJobStats(job.getId()).get(0).getState(), JobState.OPENED)); List<String> t = Collections.singletonList("data"); DatafeedConfig.Builder datafeedConfigBuilder = createDatafeedBuilder(job.getId() + "-datafeed", job.getId(), t); // Use lots of chunks so we have time to stop the lookback before it completes datafeedConfigBuilder.setChunkingConfig(ChunkingConfig.newManual(new TimeValue(1, TimeUnit.SECONDS))); DatafeedConfig datafeedConfig = datafeedConfigBuilder.build(); registerDatafeed(datafeedConfig); putDatafeed(datafeedConfig); startDatafeed(datafeedConfig.getId(), 0L, now); assertBusy(() -> { DataCounts dataCounts = getDataCounts(job.getId()); assertThat(dataCounts.getProcessedRecordCount(), greaterThan(0L)); }, 60, TimeUnit.SECONDS); stopDatafeed(datafeedConfig.getId()); // At this point, stopping the datafeed will have submitted a request for the job to close. // Depending on thread scheduling, the following kill request might overtake it. The Thread.sleep() // call here makes it more likely; to make it inevitable for testing also add a Thread.sleep(10) // immediately before the checkProcessIsAlive() call in AutodetectCommunicator.close(). Thread.sleep(randomIntBetween(1, 9)); KillProcessAction.Request killRequest = new KillProcessAction.Request(job.getId()); client().execute(KillProcessAction.INSTANCE, killRequest).actionGet(); // This should close very quickly, as we killed the process. If the job goes into the "failed" // state that's wrong and this test will fail. waitUntilJobIsClosed(job.getId(), TimeValue.timeValueSeconds(2)); } private void startRealtime(String jobId) throws Exception { startRealtime(jobId, null); } private void startRealtime(String jobId, Integer maxEmptySearches) throws Exception { client().admin().indices().prepareCreate("data") .setMapping("time", "type=date") .get(); long now = System.currentTimeMillis(); long numDocs1; if (maxEmptySearches == null) { numDocs1 = randomIntBetween(32, 2048); long lastWeek = now - 604800000; indexDocs(logger, "data", numDocs1, lastWeek, now); } else { numDocs1 = 0; } Job.Builder job = createScheduledJob(jobId); registerJob(job); putJob(job); openJob(job.getId()); assertBusy(() -> assertEquals(getJobStats(job.getId()).get(0).getState(), JobState.OPENED)); DatafeedConfig.Builder datafeedConfigBuilder = createDatafeedBuilder(job.getId() + "-datafeed", job.getId(), Collections.singletonList("data")); if (maxEmptySearches != null) { datafeedConfigBuilder.setMaxEmptySearches(maxEmptySearches); } DatafeedConfig datafeedConfig = datafeedConfigBuilder.build(); registerDatafeed(datafeedConfig); putDatafeed(datafeedConfig); startDatafeed(datafeedConfig.getId(), 0L, null); assertBusy(() -> { DataCounts dataCounts = getDataCounts(job.getId()); assertThat(dataCounts.getProcessedRecordCount(), equalTo(numDocs1)); assertThat(dataCounts.getOutOfOrderTimeStampCount(), equalTo(0L)); }); now = System.currentTimeMillis(); long numDocs2; if (maxEmptySearches == null) { numDocs2 = randomIntBetween(2, 64); indexDocs(logger, "data", numDocs2, now + 5000, now + 6000); } else { numDocs2 = 0; } assertBusy(() -> { DataCounts dataCounts = getDataCounts(job.getId()); assertThat(dataCounts.getProcessedRecordCount(), equalTo(numDocs1 + numDocs2)); assertThat(dataCounts.getOutOfOrderTimeStampCount(), equalTo(0L)); }, 30, TimeUnit.SECONDS); } }
x-pack/plugin/ml/qa/native-multi-node-tests/src/javaRestTest/java/org/elasticsearch/xpack/ml/integration/DatafeedJobsIT.java
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.ml.integration; import org.elasticsearch.ResourceNotFoundException; import org.elasticsearch.Version; import org.elasticsearch.action.admin.cluster.node.hotthreads.NodeHotThreads; import org.elasticsearch.action.admin.cluster.node.hotthreads.NodesHotThreadsResponse; import org.elasticsearch.action.support.master.AcknowledgedResponse; import org.elasticsearch.common.CheckedRunnable; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.util.concurrent.ConcurrentCollections; import org.elasticsearch.common.util.concurrent.ConcurrentMapLong; import org.elasticsearch.xpack.core.ml.action.DeleteDatafeedAction; import org.elasticsearch.xpack.core.ml.action.GetDatafeedsStatsAction; import org.elasticsearch.xpack.core.ml.action.GetJobsStatsAction; import org.elasticsearch.xpack.core.ml.action.KillProcessAction; import org.elasticsearch.xpack.core.ml.action.PutJobAction; import org.elasticsearch.xpack.core.ml.action.StopDatafeedAction; import org.elasticsearch.xpack.core.ml.datafeed.ChunkingConfig; import org.elasticsearch.xpack.core.ml.datafeed.DatafeedConfig; import org.elasticsearch.xpack.core.ml.datafeed.DatafeedState; import org.elasticsearch.xpack.core.ml.datafeed.DatafeedUpdate; import org.elasticsearch.xpack.core.ml.job.config.Job; import org.elasticsearch.xpack.core.ml.job.config.JobState; import org.elasticsearch.xpack.core.ml.job.process.autodetect.state.DataCounts; import org.hamcrest.Matcher; import org.junit.After; import java.time.Duration; import java.time.Instant; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import static org.elasticsearch.xpack.ml.support.BaseMlIntegTestCase.createDatafeed; import static org.elasticsearch.xpack.ml.support.BaseMlIntegTestCase.createDatafeedBuilder; import static org.elasticsearch.xpack.ml.support.BaseMlIntegTestCase.createScheduledJob; import static org.elasticsearch.xpack.ml.support.BaseMlIntegTestCase.getDataCounts; import static org.elasticsearch.xpack.ml.support.BaseMlIntegTestCase.indexDocs; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.hasSize; public class DatafeedJobsIT extends MlNativeAutodetectIntegTestCase { @After public void cleanup() { cleanUp(); } public void testLookbackOnly() throws Exception { client().admin().indices().prepareCreate("data-1") .setMapping("time", "type=date") .get(); long numDocs = randomIntBetween(32, 2048); long now = System.currentTimeMillis(); long oneWeekAgo = now - 604800000; long twoWeeksAgo = oneWeekAgo - 604800000; indexDocs(logger, "data-1", numDocs, twoWeeksAgo, oneWeekAgo); client().admin().indices().prepareCreate("data-2") .setMapping("time", "type=date") .get(); client().admin().cluster().prepareHealth("data-1", "data-2").setWaitForYellowStatus().get(); long numDocs2 = randomIntBetween(32, 2048); indexDocs(logger, "data-2", numDocs2, oneWeekAgo, now); Job.Builder job = createScheduledJob("lookback-job"); registerJob(job); PutJobAction.Response putJobResponse = putJob(job); assertThat(putJobResponse.getResponse().getJobVersion(), equalTo(Version.CURRENT)); openJob(job.getId()); assertBusy(() -> assertEquals(getJobStats(job.getId()).get(0).getState(), JobState.OPENED)); // Having a pattern with missing indices is acceptable List<String> indices = Arrays.asList("data-*", "missing-*"); DatafeedConfig datafeedConfig = createDatafeed(job.getId() + "-datafeed", job.getId(), indices); registerDatafeed(datafeedConfig); putDatafeed(datafeedConfig); startDatafeed(datafeedConfig.getId(), 0L, now); assertBusy(() -> { DataCounts dataCounts = getDataCounts(job.getId()); assertThat(dataCounts.getProcessedRecordCount(), equalTo(numDocs + numDocs2)); assertThat(dataCounts.getOutOfOrderTimeStampCount(), equalTo(0L)); GetDatafeedsStatsAction.Request request = new GetDatafeedsStatsAction.Request(datafeedConfig.getId()); GetDatafeedsStatsAction.Response response = client().execute(GetDatafeedsStatsAction.INSTANCE, request).actionGet(); assertThat(response.getResponse().results().get(0).getDatafeedState(), equalTo(DatafeedState.STOPPED)); }, 60, TimeUnit.SECONDS); waitUntilJobIsClosed(job.getId()); } public void testLookbackOnlyDataStream() throws Exception { String mapping = "{\n" + " \"properties\": {\n" + " \"time\": {\n" + " \"type\": \"date\"\n" + " }," + " \"@timestamp\": {\n" + " \"type\": \"date\"\n" + " }" + " }\n" + " }"; createDataStreamAndTemplate("datafeed_data_stream", mapping); long numDocs = randomIntBetween(32, 2048); long now = System.currentTimeMillis(); long oneWeekAgo = now - 604800000; long twoWeeksAgo = oneWeekAgo - 604800000; indexDocs(logger, "datafeed_data_stream", numDocs, twoWeeksAgo, oneWeekAgo); client().admin().cluster().prepareHealth("datafeed_data_stream").setWaitForYellowStatus().get(); Job.Builder job = createScheduledJob("lookback-data-stream-job"); registerJob(job); PutJobAction.Response putJobResponse = putJob(job); assertThat(putJobResponse.getResponse().getJobVersion(), equalTo(Version.CURRENT)); openJob(job.getId()); assertBusy(() -> assertEquals(getJobStats(job.getId()).get(0).getState(), JobState.OPENED)); DatafeedConfig datafeedConfig = createDatafeed(job.getId() + "-datafeed", job.getId(), Collections.singletonList("datafeed_data_stream")); registerDatafeed(datafeedConfig); putDatafeed(datafeedConfig); startDatafeed(datafeedConfig.getId(), 0L, now); assertBusy(() -> { DataCounts dataCounts = getDataCounts(job.getId()); assertThat(dataCounts.getProcessedRecordCount(), equalTo(numDocs)); assertThat(dataCounts.getOutOfOrderTimeStampCount(), equalTo(0L)); GetDatafeedsStatsAction.Request request = new GetDatafeedsStatsAction.Request(datafeedConfig.getId()); GetDatafeedsStatsAction.Response response = client().execute(GetDatafeedsStatsAction.INSTANCE, request).actionGet(); assertThat(response.getResponse().results().get(0).getDatafeedState(), equalTo(DatafeedState.STOPPED)); }, 60, TimeUnit.SECONDS); waitUntilJobIsClosed(job.getId()); } public void testDatafeedTimingStats_DatafeedRecreated() throws Exception { client().admin().indices().prepareCreate("data") .setMapping("time", "type=date") .get(); long numDocs = randomIntBetween(32, 2048); Instant now = Instant.now(); indexDocs(logger, "data", numDocs, now.minus(Duration.ofDays(14)).toEpochMilli(), now.toEpochMilli()); Job.Builder job = createScheduledJob("lookback-job-datafeed-recreated"); String datafeedId = "lookback-datafeed-datafeed-recreated"; DatafeedConfig datafeedConfig = createDatafeed(datafeedId, job.getId(), Collections.singletonList("data")); registerJob(job); putJob(job); CheckedRunnable<Exception> openAndRunJob = () -> { openJob(job.getId()); assertBusy(() -> assertEquals(getJobStats(job.getId()).get(0).getState(), JobState.OPENED)); registerDatafeed(datafeedConfig); putDatafeed(datafeedConfig); // Datafeed did not do anything yet, hence search_count is equal to 0. assertDatafeedStats(datafeedId, DatafeedState.STOPPED, job.getId(), equalTo(0L)); startDatafeed(datafeedId, 0L, now.toEpochMilli()); assertBusy(() -> { assertThat(getDataCounts(job.getId()).getProcessedRecordCount(), equalTo(numDocs)); // Datafeed processed numDocs documents so search_count must be greater than 0. assertDatafeedStats(datafeedId, DatafeedState.STOPPED, job.getId(), greaterThan(0L)); }, 60, TimeUnit.SECONDS); deleteDatafeed(datafeedId); waitUntilJobIsClosed(job.getId()); }; openAndRunJob.run(); openAndRunJob.run(); } public void testDatafeedTimingStats_QueryDelayUpdated_TimingStatsNotReset() throws Exception { client().admin().indices().prepareCreate("data") .setMapping("time", "type=date") .get(); long numDocs = randomIntBetween(32, 2048); Instant now = Instant.now(); indexDocs(logger, "data", numDocs, now.minus(Duration.ofDays(14)).toEpochMilli(), now.toEpochMilli()); Job.Builder job = createScheduledJob("lookback-job-query-delay-updated"); registerJob(job); putJob(job); String datafeedId = "lookback-datafeed-query-delay-updated"; DatafeedConfig datafeedConfig = createDatafeed(datafeedId, job.getId(), Collections.singletonList("data")); registerDatafeed(datafeedConfig); putDatafeed(datafeedConfig); openJob(job.getId()); assertBusy(() -> assertEquals(getJobStats(job.getId()).get(0).getState(), JobState.OPENED)); // Datafeed did not do anything yet, hence search_count is equal to 0. assertDatafeedStats(datafeedId, DatafeedState.STOPPED, job.getId(), equalTo(0L)); startDatafeed(datafeedId, 0L, now.toEpochMilli()); assertBusy(() -> { assertThat(getDataCounts(job.getId()).getProcessedRecordCount(), equalTo(numDocs)); // Datafeed processed numDocs documents so search_count must be greater than 0. assertDatafeedStats(datafeedId, DatafeedState.STOPPED, job.getId(), greaterThan(0L)); }, 60, TimeUnit.SECONDS); waitUntilJobIsClosed(job.getId()); // Change something different than jobId, here: queryDelay. updateDatafeed(new DatafeedUpdate.Builder(datafeedId).setQueryDelay(TimeValue.timeValueSeconds(777)).build()); // Search_count is still greater than 0 (i.e. has not been reset by datafeed update) assertDatafeedStats(datafeedId, DatafeedState.STOPPED, job.getId(), greaterThan(0L)); } private void assertDatafeedStats(String datafeedId, DatafeedState state, String jobId, Matcher<Long> searchCountMatcher) { GetDatafeedsStatsAction.Request request = new GetDatafeedsStatsAction.Request(datafeedId); GetDatafeedsStatsAction.Response response = client().execute(GetDatafeedsStatsAction.INSTANCE, request).actionGet(); assertThat(response.getResponse().results(), hasSize(1)); GetDatafeedsStatsAction.Response.DatafeedStats stats = response.getResponse().results().get(0); assertThat(stats.getDatafeedState(), equalTo(state)); assertThat(stats.getTimingStats().getJobId(), equalTo(jobId)); assertThat(stats.getTimingStats().getSearchCount(), searchCountMatcher); } public void testRealtime() throws Exception { String jobId = "realtime-job"; String datafeedId = jobId + "-datafeed"; startRealtime(jobId); try { StopDatafeedAction.Response stopJobResponse = stopDatafeed(datafeedId); assertTrue(stopJobResponse.isStopped()); } catch (Exception e) { NodesHotThreadsResponse nodesHotThreadsResponse = client().admin().cluster().prepareNodesHotThreads().get(); int i = 0; for (NodeHotThreads nodeHotThreads : nodesHotThreadsResponse.getNodes()) { logger.info(i++ + ":\n" +nodeHotThreads.getHotThreads()); } throw e; } assertBusy(() -> { GetDatafeedsStatsAction.Request request = new GetDatafeedsStatsAction.Request(datafeedId); GetDatafeedsStatsAction.Response response = client().execute(GetDatafeedsStatsAction.INSTANCE, request).actionGet(); assertThat(response.getResponse().results().get(0).getDatafeedState(), equalTo(DatafeedState.STOPPED)); }); } public void testRealtime_noDataAndAutoStop() throws Exception { String jobId = "realtime-job-auto-stop"; String datafeedId = jobId + "-datafeed"; startRealtime(jobId, randomIntBetween(1, 3)); // Datafeed should auto-stop... assertBusy(() -> { GetDatafeedsStatsAction.Request request = new GetDatafeedsStatsAction.Request(datafeedId); GetDatafeedsStatsAction.Response response = client().execute(GetDatafeedsStatsAction.INSTANCE, request).actionGet(); assertThat(response.getResponse().results().get(0).getDatafeedState(), equalTo(DatafeedState.STOPPED)); }); // ...and should have auto-closed the job too assertBusy(() -> { GetJobsStatsAction.Request request = new GetJobsStatsAction.Request(jobId); GetJobsStatsAction.Response response = client().execute(GetJobsStatsAction.INSTANCE, request).actionGet(); assertThat(response.getResponse().results().get(0).getState(), equalTo(JobState.CLOSED)); }); } public void testRealtime_multipleStopCalls() throws Exception { String jobId = "realtime-job-multiple-stop"; final String datafeedId = jobId + "-datafeed"; startRealtime(jobId); ConcurrentMapLong<AssertionError> exceptions = ConcurrentCollections.newConcurrentMapLong(); // It's practically impossible to assert that a stop request has waited // for a concurrently executing request to finish before returning. // But we can assert the data feed has stopped after the request returns. Runnable stopDataFeed = () -> { StopDatafeedAction.Response stopJobResponse = stopDatafeed(datafeedId); if (stopJobResponse.isStopped() == false) { exceptions.put(Thread.currentThread().getId(), new AssertionError("Job is not stopped")); } GetDatafeedsStatsAction.Request request = new GetDatafeedsStatsAction.Request(datafeedId); GetDatafeedsStatsAction.Response response = client().execute(GetDatafeedsStatsAction.INSTANCE, request).actionGet(); if (response.getResponse().results().get(0).getDatafeedState() != DatafeedState.STOPPED) { exceptions.put(Thread.currentThread().getId(), new AssertionError("Expected STOPPED datafeed state got " + response.getResponse().results().get(0).getDatafeedState())); } }; // The idea is to hit the situation where one request waits for // the other to complete. This is difficult to schedule but // hopefully it will happen in CI int numThreads = 5; Thread [] threads = new Thread[numThreads]; for (int i=0; i<numThreads; i++) { threads[i] = new Thread(stopDataFeed); } for (int i=0; i<numThreads; i++) { threads[i].start(); } for (int i=0; i<numThreads; i++) { threads[i].join(); } if (exceptions.isEmpty() == false) { throw exceptions.values().iterator().next(); } } public void testRealtime_givenSimultaneousStopAndForceDelete() throws Throwable { String jobId = "realtime-job-stop-and-force-delete"; final String datafeedId = jobId + "-datafeed"; startRealtime(jobId); AtomicReference<Throwable> exception = new AtomicReference<>(); // The UI now force deletes datafeeds, which means they can be deleted while running. // The first step is to isolate the datafeed. But if it was already being stopped then // the datafeed may not be running by the time the isolate action is executed. This // test will sometimes (depending on thread scheduling) achieve this situation and ensure // the code is robust to it. Thread deleteDatafeedThread = new Thread(() -> { try { DeleteDatafeedAction.Request request = new DeleteDatafeedAction.Request(datafeedId); request.setForce(true); AcknowledgedResponse response = client().execute(DeleteDatafeedAction.INSTANCE, request).actionGet(); if (response.isAcknowledged()) { GetDatafeedsStatsAction.Request statsRequest = new GetDatafeedsStatsAction.Request(datafeedId); expectThrows(ResourceNotFoundException.class, () -> client().execute(GetDatafeedsStatsAction.INSTANCE, statsRequest).actionGet()); } else { exception.set(new AssertionError("Job is not deleted")); } } catch (AssertionError | Exception e) { exception.set(e); } }); deleteDatafeedThread.start(); try { stopDatafeed(datafeedId); } catch (ResourceNotFoundException e) { // This is OK - it means the thread running the delete fully completed before the stop started to execute } finally { deleteDatafeedThread.join(); } if (exception.get() != null) { throw exception.get(); } } public void testRealtime_GivenProcessIsKilled() throws Exception { String jobId = "realtime-job-given-process-is-killed"; String datafeedId = jobId + "-datafeed"; startRealtime(jobId); KillProcessAction.Request killRequest = new KillProcessAction.Request(jobId); client().execute(KillProcessAction.INSTANCE, killRequest).actionGet(); assertBusy(() -> { GetDatafeedsStatsAction.Request request = new GetDatafeedsStatsAction.Request(datafeedId); GetDatafeedsStatsAction.Response response = client().execute(GetDatafeedsStatsAction.INSTANCE, request).actionGet(); assertThat(response.getResponse().results().get(0).getDatafeedState(), equalTo(DatafeedState.STOPPED)); }); } /** * Stopping a lookback closes the associated job _after_ the stop call returns. * This test ensures that a kill request submitted during this close doesn't * put the job into the "failed" state. */ public void testStopLookbackFollowedByProcessKill() throws Exception { client().admin().indices().prepareCreate("data") .setMapping("time", "type=date") .get(); long numDocs = randomIntBetween(1024, 2048); long now = System.currentTimeMillis(); long oneWeekAgo = now - 604800000; long twoWeeksAgo = oneWeekAgo - 604800000; indexDocs(logger, "data", numDocs, twoWeeksAgo, oneWeekAgo); Job.Builder job = createScheduledJob("lookback-job-stopped-then-killed"); registerJob(job); PutJobAction.Response putJobResponse = putJob(job); assertThat(putJobResponse.getResponse().getJobVersion(), equalTo(Version.CURRENT)); openJob(job.getId()); assertBusy(() -> assertEquals(getJobStats(job.getId()).get(0).getState(), JobState.OPENED)); List<String> t = Collections.singletonList("data"); DatafeedConfig.Builder datafeedConfigBuilder = createDatafeedBuilder(job.getId() + "-datafeed", job.getId(), t); // Use lots of chunks so we have time to stop the lookback before it completes datafeedConfigBuilder.setChunkingConfig(ChunkingConfig.newManual(new TimeValue(1, TimeUnit.SECONDS))); DatafeedConfig datafeedConfig = datafeedConfigBuilder.build(); registerDatafeed(datafeedConfig); putDatafeed(datafeedConfig); startDatafeed(datafeedConfig.getId(), 0L, now); assertBusy(() -> { DataCounts dataCounts = getDataCounts(job.getId()); assertThat(dataCounts.getProcessedRecordCount(), greaterThan(0L)); }, 60, TimeUnit.SECONDS); stopDatafeed(datafeedConfig.getId()); // At this point, stopping the datafeed will have submitted a request for the job to close. // Depending on thread scheduling, the following kill request might overtake it. The Thread.sleep() // call here makes it more likely; to make it inevitable for testing also add a Thread.sleep(10) // immediately before the checkProcessIsAlive() call in AutodetectCommunicator.close(). Thread.sleep(randomIntBetween(1, 9)); KillProcessAction.Request killRequest = new KillProcessAction.Request(job.getId()); client().execute(KillProcessAction.INSTANCE, killRequest).actionGet(); // This should close very quickly, as we killed the process. If the job goes into the "failed" // state that's wrong and this test will fail. waitUntilJobIsClosed(job.getId(), TimeValue.timeValueSeconds(2)); } private void startRealtime(String jobId) throws Exception { startRealtime(jobId, null); } private void startRealtime(String jobId, Integer maxEmptySearches) throws Exception { client().admin().indices().prepareCreate("data") .setMapping("time", "type=date") .get(); long now = System.currentTimeMillis(); long numDocs1; if (maxEmptySearches == null) { numDocs1 = randomIntBetween(32, 2048); long lastWeek = now - 604800000; indexDocs(logger, "data", numDocs1, lastWeek, now); } else { numDocs1 = 0; } Job.Builder job = createScheduledJob(jobId); registerJob(job); putJob(job); openJob(job.getId()); assertBusy(() -> assertEquals(getJobStats(job.getId()).get(0).getState(), JobState.OPENED)); DatafeedConfig.Builder datafeedConfigBuilder = createDatafeedBuilder(job.getId() + "-datafeed", job.getId(), Collections.singletonList("data")); if (maxEmptySearches != null) { datafeedConfigBuilder.setMaxEmptySearches(maxEmptySearches); } DatafeedConfig datafeedConfig = datafeedConfigBuilder.build(); registerDatafeed(datafeedConfig); putDatafeed(datafeedConfig); startDatafeed(datafeedConfig.getId(), 0L, null); assertBusy(() -> { DataCounts dataCounts = getDataCounts(job.getId()); assertThat(dataCounts.getProcessedRecordCount(), equalTo(numDocs1)); assertThat(dataCounts.getOutOfOrderTimeStampCount(), equalTo(0L)); }); now = System.currentTimeMillis(); long numDocs2; if (maxEmptySearches == null) { numDocs2 = randomIntBetween(2, 64); indexDocs(logger, "data", numDocs2, now + 5000, now + 6000); } else { numDocs2 = 0; } assertBusy(() -> { DataCounts dataCounts = getDataCounts(job.getId()); assertThat(dataCounts.getProcessedRecordCount(), equalTo(numDocs1 + numDocs2)); assertThat(dataCounts.getOutOfOrderTimeStampCount(), equalTo(0L)); }, 30, TimeUnit.SECONDS); } }
Mute DatafeedJobsIT#testDatafeedTimingStats_DatafeedRecreated (#63974) Relates to #63973
x-pack/plugin/ml/qa/native-multi-node-tests/src/javaRestTest/java/org/elasticsearch/xpack/ml/integration/DatafeedJobsIT.java
Mute DatafeedJobsIT#testDatafeedTimingStats_DatafeedRecreated (#63974)
Java
apache-2.0
e4bfacaf9383925c8e11b826271796f9957a8678
0
bonigarcia/selenium-jupiter,bonigarcia/selenium-jupiter
/* * (C) Copyright 2017 Boni Garcia (http://bonigarcia.github.io/) * * 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.bonigarcia; import static io.github.bonigarcia.BrowserType.CHROME; import static io.github.bonigarcia.BrowserType.FIREFOX; import static io.github.bonigarcia.BrowserType.OPERA; import static java.lang.invoke.MethodHandles.lookup; import static org.openqa.selenium.OutputType.BASE64; import static org.slf4j.LoggerFactory.getLogger; import java.lang.reflect.Parameter; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.junit.jupiter.api.extension.AfterEachCallback; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.ParameterContext; import org.junit.jupiter.api.extension.ParameterResolver; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.edge.EdgeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.opera.OperaDriver; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.safari.SafariDriver; import org.slf4j.Logger; import io.appium.java_client.AppiumDriver; import io.github.bonigarcia.handler.AppiumDriverHandler; import io.github.bonigarcia.handler.ChromeDriverHandler; import io.github.bonigarcia.handler.DockerDriverHandler; import io.github.bonigarcia.handler.EdgeDriverHandler; import io.github.bonigarcia.handler.FirefoxDriverHandler; import io.github.bonigarcia.handler.OperaDriverHandler; import io.github.bonigarcia.handler.OtherDriverHandler; import io.github.bonigarcia.handler.RemoteDriverHandler; import io.github.bonigarcia.handler.SafariDriverHandler; import io.github.bonigarcia.wdm.WebDriverManager; /** * Selenium extension for Jupiter (JUnit 5) tests. * * @author Boni Garcia ([email protected]) * @since 1.0.0 */ public class SeleniumExtension implements ParameterResolver, AfterEachCallback { final Logger log = getLogger(lookup().lookupClass()); private List<WebDriver> webDriverList = new ArrayList<>(); private List<Class<?>> typeList = new ArrayList<>(); @Override public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { Class<?> type = parameterContext.getParameter().getType(); return WebDriver.class.isAssignableFrom(type) && !type.isInterface(); } @Override public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { Parameter parameter = parameterContext.getParameter(); Optional<Object> testInstance = extensionContext.getTestInstance(); Class<?> type = parameter.getType(); // WebDriverManager if (!typeList.contains(type)) { typeList.add(type); WebDriverManager.getInstance(type).setup(); } // Instantiate WebDriver WebDriver webDriver = null; if (type == ChromeDriver.class) { webDriver = ChromeDriverHandler.getInstance().resolve(parameter, testInstance); } else if (type == FirefoxDriver.class) { webDriver = FirefoxDriverHandler.getInstance().resolve(parameter, testInstance); } else if (type == EdgeDriver.class) { webDriver = EdgeDriverHandler.getInstance().resolve(parameter, testInstance); } else if (type == OperaDriver.class) { webDriver = OperaDriverHandler.getInstance().resolve(parameter, testInstance); } else if (type == SafariDriver.class) { webDriver = SafariDriverHandler.getInstance().resolve(parameter, testInstance); } else if (type == RemoteWebDriver.class) { webDriver = RemoteDriverHandler.getInstance().resolve(parameter, testInstance); } else if (type == AppiumDriver.class) { webDriver = AppiumDriverHandler.getInstance().resolve(parameter, testInstance); } else if (type == DockerChromeDriver.class) { webDriver = DockerDriverHandler.getInstance().resolve(CHROME, parameter, testInstance); } else if (type == DockerFirefoxDriver.class) { webDriver = DockerDriverHandler.getInstance().resolve(FIREFOX, parameter, testInstance); } else if (type == DockerOperaDriver.class) { webDriver = DockerDriverHandler.getInstance().resolve(OPERA, parameter, testInstance); } else { // Other WebDriver type webDriver = OtherDriverHandler.getInstance().resolve(parameter, testInstance); } if (webDriver != null) { webDriverList.add(webDriver); } return webDriver; } @Override public void afterEach(ExtensionContext context) { Optional<Throwable> executionException = context .getExecutionException(); if (executionException.isPresent()) { webDriverList.forEach(this::logBase64Screenshot); } webDriverList.forEach(WebDriver::quit); webDriverList.clear(); AppiumDriverHandler.getInstance().closeLocalServiceIfNecessary(); DockerDriverHandler.getInstance().clearContainersIfNecessary(); } void logBase64Screenshot(WebDriver driver) { if (driver != null) { try { String screenshotBase64 = ((TakesScreenshot) driver) .getScreenshotAs(BASE64); log.debug("Screenshot (in Base64) at the end of session {} " + "(copy&paste this string as URL in browser to watch it):\r\n" + "data:image/png;base64,{}", ((RemoteWebDriver) driver).getSessionId(), screenshotBase64); } catch (Exception e) { log.trace("Exception getting screenshot", e); } } } }
src/main/java/io/github/bonigarcia/SeleniumExtension.java
/* * (C) Copyright 2017 Boni Garcia (http://bonigarcia.github.io/) * * 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.bonigarcia; import static io.github.bonigarcia.BrowserType.CHROME; import static io.github.bonigarcia.BrowserType.FIREFOX; import static io.github.bonigarcia.BrowserType.OPERA; import static java.lang.invoke.MethodHandles.lookup; import static org.openqa.selenium.OutputType.BASE64; import static org.slf4j.LoggerFactory.getLogger; import java.lang.reflect.Parameter; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.junit.jupiter.api.extension.AfterEachCallback; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.ParameterContext; import org.junit.jupiter.api.extension.ParameterResolver; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.edge.EdgeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.opera.OperaDriver; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.safari.SafariDriver; import org.slf4j.Logger; import io.appium.java_client.AppiumDriver; import io.github.bonigarcia.handler.AppiumDriverHandler; import io.github.bonigarcia.handler.ChromeDriverHandler; import io.github.bonigarcia.handler.DockerDriverHandler; import io.github.bonigarcia.handler.EdgeDriverHandler; import io.github.bonigarcia.handler.FirefoxDriverHandler; import io.github.bonigarcia.handler.OperaDriverHandler; import io.github.bonigarcia.handler.OtherDriverHandler; import io.github.bonigarcia.handler.RemoteDriverHandler; import io.github.bonigarcia.handler.SafariDriverHandler; import io.github.bonigarcia.wdm.WebDriverManager; /** * Selenium extension for Jupiter (JUnit 5) tests. * * @author Boni Garcia ([email protected]) * @since 1.0.0 */ public class SeleniumExtension implements ParameterResolver, AfterEachCallback { final Logger log = getLogger(lookup().lookupClass()); private List<WebDriver> webDriverList = new ArrayList<>(); private List<Class<?>> typeList = new ArrayList<>(); @Override public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { Class<?> type = parameterContext.getParameter().getType(); return WebDriver.class.isAssignableFrom(type) && !type.isInterface(); } @Override public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { Parameter parameter = parameterContext.getParameter(); Optional<Object> testInstance = extensionContext.getTestInstance(); Class<?> type = parameter.getType(); // WebDriverManager if (!typeList.contains(type)) { typeList.add(type); WebDriverManager.getInstance(type).setup(); } // Instantiate WebDriver WebDriver webDriver = null; if (type == ChromeDriver.class) { webDriver = ChromeDriverHandler.getInstance().resolve(parameter, testInstance); } else if (type == FirefoxDriver.class) { webDriver = FirefoxDriverHandler.getInstance().resolve(parameter, testInstance); } else if (type == EdgeDriver.class) { webDriver = EdgeDriverHandler.getInstance().resolve(parameter, testInstance); } else if (type == OperaDriver.class) { webDriver = OperaDriverHandler.getInstance().resolve(parameter, testInstance); } else if (type == SafariDriver.class) { webDriver = SafariDriverHandler.getInstance().resolve(parameter, testInstance); } else if (type == RemoteWebDriver.class) { webDriver = RemoteDriverHandler.getInstance().resolve(parameter, testInstance); } else if (type == AppiumDriver.class) { webDriver = AppiumDriverHandler.getInstance().resolve(parameter, testInstance); } else if (type == DockerChromeDriver.class) { webDriver = DockerDriverHandler.getInstance().resolve(CHROME, parameter, testInstance); } else if (type == DockerFirefoxDriver.class) { webDriver = DockerDriverHandler.getInstance().resolve(FIREFOX, parameter, testInstance); } else if (type == DockerOperaDriver.class) { webDriver = DockerDriverHandler.getInstance().resolve(OPERA, parameter, testInstance); } else { // Other WebDriver type webDriver = OtherDriverHandler.getInstance().resolve(parameter, testInstance); } if (webDriver != null) { webDriverList.add(webDriver); } return webDriver; } @Override public void afterEach(ExtensionContext context) { Optional<Throwable> executionException = context .getExecutionException(); if (executionException.isPresent()) { webDriverList.forEach(this::logBase64Screenshot); } webDriverList.forEach(WebDriver::quit); webDriverList.clear(); AppiumDriverHandler.getInstance().closeLocalServiceIfNecessary(); DockerDriverHandler.getInstance().clearContainersIfNecessary(); } void logBase64Screenshot(WebDriver driver) { if (driver != null) { try { String screenshotBase64 = ((TakesScreenshot) driver) .getScreenshotAs(BASE64); log.debug("Screenshot (in Base64) at the end of session {} " + "(copy&paste this string as URL in browser to watch it)\n" + "data:image/png;base64,{}", ((RemoteWebDriver) driver).getSessionId(), screenshotBase64); } catch (Exception e) { log.trace("Exception getting screenshot", e); } } } }
Improve logging
src/main/java/io/github/bonigarcia/SeleniumExtension.java
Improve logging
Java
bsd-2-clause
61658d1ad33736c972529c74a3bb53f5ed4ef02a
0
marschall/pgjdbc,pgjdbc/pgjdbc,marschall/pgjdbc,jorsol/pgjdbc,pgjdbc/pgjdbc,jorsol/pgjdbc,jorsol/pgjdbc,pgjdbc/pgjdbc,marschall/pgjdbc,pgjdbc/pgjdbc,marschall/pgjdbc,jorsol/pgjdbc
/* * Copyright (c) 2004, PostgreSQL Global Development Group * See the LICENSE file in the project root for more information. */ package org.postgresql.jdbc; import static org.postgresql.util.internal.Nullness.castNonNull; import org.postgresql.Driver; import org.postgresql.PGNotification; import org.postgresql.PGProperty; import org.postgresql.copy.CopyManager; import org.postgresql.core.BaseConnection; import org.postgresql.core.BaseStatement; import org.postgresql.core.CachedQuery; import org.postgresql.core.ConnectionFactory; import org.postgresql.core.Encoding; import org.postgresql.core.Oid; import org.postgresql.core.Query; import org.postgresql.core.QueryExecutor; import org.postgresql.core.ReplicationProtocol; import org.postgresql.core.ResultHandlerBase; import org.postgresql.core.ServerVersion; import org.postgresql.core.SqlCommand; import org.postgresql.core.TransactionState; import org.postgresql.core.TypeInfo; import org.postgresql.core.Utils; import org.postgresql.core.Version; import org.postgresql.fastpath.Fastpath; import org.postgresql.largeobject.LargeObjectManager; import org.postgresql.replication.PGReplicationConnection; import org.postgresql.replication.PGReplicationConnectionImpl; import org.postgresql.util.GT; import org.postgresql.util.HostSpec; import org.postgresql.util.LruCache; import org.postgresql.util.PGBinaryObject; import org.postgresql.util.PGobject; import org.postgresql.util.PSQLException; import org.postgresql.util.PSQLState; import org.postgresql.xml.DefaultPGXmlFactoryFactory; import org.postgresql.xml.LegacyInsecurePGXmlFactoryFactory; import org.postgresql.xml.PGXmlFactoryFactory; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.PolyNull; import org.checkerframework.dataflow.qual.Pure; import java.io.IOException; import java.sql.Array; import java.sql.Blob; import java.sql.CallableStatement; import java.sql.ClientInfoStatus; import java.sql.Clob; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.NClob; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLClientInfoException; import java.sql.SQLException; import java.sql.SQLPermission; import java.sql.SQLWarning; import java.sql.SQLXML; import java.sql.Savepoint; import java.sql.Statement; import java.sql.Struct; import java.sql.Types; import java.util.Arrays; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.NoSuchElementException; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.Executor; import java.util.logging.Level; import java.util.logging.Logger; public class PgConnection implements BaseConnection { private static final Logger LOGGER = Logger.getLogger(PgConnection.class.getName()); private static final Set<Integer> SUPPORTED_BINARY_OIDS = getSupportedBinaryOids(); private static final SQLPermission SQL_PERMISSION_ABORT = new SQLPermission("callAbort"); private static final SQLPermission SQL_PERMISSION_NETWORK_TIMEOUT = new SQLPermission("setNetworkTimeout"); private enum ReadOnlyBehavior { ignore, transaction, always; } // // Data initialized on construction: // private final Properties clientInfo; /* URL we were created via */ private final String creatingURL; private final ReadOnlyBehavior readOnlyBehavior; private @Nullable Throwable openStackTrace; /* Actual network handler */ private final QueryExecutor queryExecutor; /* Query that runs COMMIT */ private final Query commitQuery; /* Query that runs ROLLBACK */ private final Query rollbackQuery; private final CachedQuery setSessionReadOnly; private final CachedQuery setSessionNotReadOnly; private final TypeInfo typeCache; private boolean disableColumnSanitiser = false; // Default statement prepare threshold. protected int prepareThreshold; /** * Default fetch size for statement. * * @see PGProperty#DEFAULT_ROW_FETCH_SIZE */ protected int defaultFetchSize; // Default forcebinary option. protected boolean forcebinary = false; private int rsHoldability = ResultSet.CLOSE_CURSORS_AT_COMMIT; private int savepointId = 0; // Connection's autocommit state. private boolean autoCommit = true; // Connection's readonly state. private boolean readOnly = false; // Filter out database objects for which the current user has no privileges granted from the DatabaseMetaData private boolean hideUnprivilegedObjects ; // Whether to include error details in logging and exceptions private final boolean logServerErrorDetail; // Bind String to UNSPECIFIED or VARCHAR? private final boolean bindStringAsVarchar; // Current warnings; there might be more on queryExecutor too. private @Nullable SQLWarning firstWarning; // Timer for scheduling TimerTasks for this connection. // Only instantiated if a task is actually scheduled. private volatile @Nullable Timer cancelTimer; private @Nullable PreparedStatement checkConnectionQuery; /** * Replication protocol in current version postgresql(10devel) supports a limited number of * commands. */ private final boolean replicationConnection; private final LruCache<FieldMetadata.Key, FieldMetadata> fieldMetadataCache; private final @Nullable String xmlFactoryFactoryClass; private @Nullable PGXmlFactoryFactory xmlFactoryFactory; final CachedQuery borrowQuery(String sql) throws SQLException { return queryExecutor.borrowQuery(sql); } final CachedQuery borrowCallableQuery(String sql) throws SQLException { return queryExecutor.borrowCallableQuery(sql); } private CachedQuery borrowReturningQuery(String sql, String @Nullable [] columnNames) throws SQLException { return queryExecutor.borrowReturningQuery(sql, columnNames); } @Override public CachedQuery createQuery(String sql, boolean escapeProcessing, boolean isParameterized, String... columnNames) throws SQLException { return queryExecutor.createQuery(sql, escapeProcessing, isParameterized, columnNames); } void releaseQuery(CachedQuery cachedQuery) { queryExecutor.releaseQuery(cachedQuery); } @Override public void setFlushCacheOnDeallocate(boolean flushCacheOnDeallocate) { queryExecutor.setFlushCacheOnDeallocate(flushCacheOnDeallocate); LOGGER.log(Level.FINE, " setFlushCacheOnDeallocate = {0}", flushCacheOnDeallocate); } // // Ctor. // @SuppressWarnings({"method.invocation.invalid", "argument.type.incompatible"}) public PgConnection(HostSpec[] hostSpecs, String user, String database, Properties info, String url) throws SQLException { // Print out the driver version number LOGGER.log(Level.FINE, org.postgresql.util.DriverInfo.DRIVER_FULL_NAME); this.creatingURL = url; this.readOnlyBehavior = getReadOnlyBehavior(PGProperty.READ_ONLY_MODE.get(info)); setDefaultFetchSize(PGProperty.DEFAULT_ROW_FETCH_SIZE.getInt(info)); setPrepareThreshold(PGProperty.PREPARE_THRESHOLD.getInt(info)); if (prepareThreshold == -1) { setForceBinary(true); } // Now make the initial connection and set up local state this.queryExecutor = ConnectionFactory.openConnection(hostSpecs, user, database, info); // WARNING for unsupported servers (8.1 and lower are not supported) if (LOGGER.isLoggable(Level.WARNING) && !haveMinimumServerVersion(ServerVersion.v8_2)) { LOGGER.log(Level.WARNING, "Unsupported Server Version: {0}", queryExecutor.getServerVersion()); } setSessionReadOnly = createQuery("SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY", false, true); setSessionNotReadOnly = createQuery("SET SESSION CHARACTERISTICS AS TRANSACTION READ WRITE", false, true); // Set read-only early if requested if (PGProperty.READ_ONLY.getBoolean(info)) { setReadOnly(true); } this.hideUnprivilegedObjects = PGProperty.HIDE_UNPRIVILEGED_OBJECTS.getBoolean(info); Set<Integer> binaryOids = getBinaryOids(info); // split for receive and send for better control Set<Integer> useBinarySendForOids = new HashSet<Integer>(binaryOids); Set<Integer> useBinaryReceiveForOids = new HashSet<Integer>(binaryOids); /* * Does not pass unit tests because unit tests expect setDate to have millisecond accuracy * whereas the binary transfer only supports date accuracy. */ useBinarySendForOids.remove(Oid.DATE); queryExecutor.setBinaryReceiveOids(useBinaryReceiveForOids); queryExecutor.setBinarySendOids(useBinarySendForOids); if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, " types using binary send = {0}", oidsToString(useBinarySendForOids)); LOGGER.log(Level.FINEST, " types using binary receive = {0}", oidsToString(useBinaryReceiveForOids)); LOGGER.log(Level.FINEST, " integer date/time = {0}", queryExecutor.getIntegerDateTimes()); } // // String -> text or unknown? // String stringType = PGProperty.STRING_TYPE.get(info); if (stringType != null) { if (stringType.equalsIgnoreCase("unspecified")) { bindStringAsVarchar = false; } else if (stringType.equalsIgnoreCase("varchar")) { bindStringAsVarchar = true; } else { throw new PSQLException( GT.tr("Unsupported value for stringtype parameter: {0}", stringType), PSQLState.INVALID_PARAMETER_VALUE); } } else { bindStringAsVarchar = true; } // Initialize timestamp stuff timestampUtils = new TimestampUtils(!queryExecutor.getIntegerDateTimes(), new QueryExecutorTimeZoneProvider(queryExecutor)); // Initialize common queries. // isParameterized==true so full parse is performed and the engine knows the query // is not a compound query with ; inside, so it could use parse/bind/exec messages commitQuery = createQuery("COMMIT", false, true).query; rollbackQuery = createQuery("ROLLBACK", false, true).query; int unknownLength = PGProperty.UNKNOWN_LENGTH.getInt(info); // Initialize object handling typeCache = createTypeInfo(this, unknownLength); initObjectTypes(info); if (PGProperty.LOG_UNCLOSED_CONNECTIONS.getBoolean(info)) { openStackTrace = new Throwable("Connection was created at this point:"); } this.logServerErrorDetail = PGProperty.LOG_SERVER_ERROR_DETAIL.getBoolean(info); this.disableColumnSanitiser = PGProperty.DISABLE_COLUMN_SANITISER.getBoolean(info); if (haveMinimumServerVersion(ServerVersion.v8_3)) { typeCache.addCoreType("uuid", Oid.UUID, Types.OTHER, "java.util.UUID", Oid.UUID_ARRAY); typeCache.addCoreType("xml", Oid.XML, Types.SQLXML, "java.sql.SQLXML", Oid.XML_ARRAY); } this.clientInfo = new Properties(); if (haveMinimumServerVersion(ServerVersion.v9_0)) { String appName = PGProperty.APPLICATION_NAME.get(info); if (appName == null) { appName = ""; } this.clientInfo.put("ApplicationName", appName); } fieldMetadataCache = new LruCache<FieldMetadata.Key, FieldMetadata>( Math.max(0, PGProperty.DATABASE_METADATA_CACHE_FIELDS.getInt(info)), Math.max(0, PGProperty.DATABASE_METADATA_CACHE_FIELDS_MIB.getInt(info) * 1024L * 1024L), false); replicationConnection = PGProperty.REPLICATION.get(info) != null; xmlFactoryFactoryClass = PGProperty.XML_FACTORY_FACTORY.get(info); } private static ReadOnlyBehavior getReadOnlyBehavior(String property) { try { return ReadOnlyBehavior.valueOf(property); } catch (IllegalArgumentException e) { try { return ReadOnlyBehavior.valueOf(property.toLowerCase(Locale.US)); } catch (IllegalArgumentException e2) { return ReadOnlyBehavior.transaction; } } } private static Set<Integer> getSupportedBinaryOids() { return new HashSet<Integer>(Arrays.asList( Oid.BYTEA, Oid.INT2, Oid.INT4, Oid.INT8, Oid.FLOAT4, Oid.FLOAT8, Oid.NUMERIC, Oid.TIME, Oid.DATE, Oid.TIMETZ, Oid.TIMESTAMP, Oid.TIMESTAMPTZ, Oid.BYTEA_ARRAY, Oid.INT2_ARRAY, Oid.INT4_ARRAY, Oid.INT8_ARRAY, Oid.OID_ARRAY, Oid.FLOAT4_ARRAY, Oid.FLOAT8_ARRAY, Oid.VARCHAR_ARRAY, Oid.TEXT_ARRAY, Oid.POINT, Oid.BOX, Oid.UUID)); } private static Set<Integer> getBinaryOids(Properties info) throws PSQLException { boolean binaryTransfer = PGProperty.BINARY_TRANSFER.getBoolean(info); // Formats that currently have binary protocol support Set<Integer> binaryOids = new HashSet<Integer>(32); if (binaryTransfer) { binaryOids.addAll(SUPPORTED_BINARY_OIDS); } String oids = PGProperty.BINARY_TRANSFER_ENABLE.get(info); if (oids != null) { binaryOids.addAll(getOidSet(oids)); } oids = PGProperty.BINARY_TRANSFER_DISABLE.get(info); if (oids != null) { binaryOids.removeAll(getOidSet(oids)); } return binaryOids; } private static Set<Integer> getOidSet(String oidList) throws PSQLException { Set<Integer> oids = new HashSet<Integer>(); StringTokenizer tokenizer = new StringTokenizer(oidList, ","); while (tokenizer.hasMoreTokens()) { String oid = tokenizer.nextToken(); oids.add(Oid.valueOf(oid)); } return oids; } private String oidsToString(Set<Integer> oids) { StringBuilder sb = new StringBuilder(); for (Integer oid : oids) { sb.append(Oid.toString(oid)); sb.append(','); } if (sb.length() > 0) { sb.setLength(sb.length() - 1); } else { sb.append(" <none>"); } return sb.toString(); } private final TimestampUtils timestampUtils; public TimestampUtils getTimestampUtils() { return timestampUtils; } /** * The current type mappings. */ protected Map<String, Class<?>> typemap = new HashMap<String, Class<?>>(); @Override public Statement createStatement() throws SQLException { // We now follow the spec and default to TYPE_FORWARD_ONLY. return createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); } @Override public PreparedStatement prepareStatement(String sql) throws SQLException { return prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); } @Override public CallableStatement prepareCall(String sql) throws SQLException { return prepareCall(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); } @Override public Map<String, Class<?>> getTypeMap() throws SQLException { checkClosed(); return typemap; } public QueryExecutor getQueryExecutor() { return queryExecutor; } public ReplicationProtocol getReplicationProtocol() { return queryExecutor.getReplicationProtocol(); } /** * This adds a warning to the warning chain. * * @param warn warning to add */ public void addWarning(SQLWarning warn) { // Add the warning to the chain if (firstWarning != null) { firstWarning.setNextWarning(warn); } else { firstWarning = warn; } } @Override public ResultSet execSQLQuery(String s) throws SQLException { return execSQLQuery(s, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); } @Override public ResultSet execSQLQuery(String s, int resultSetType, int resultSetConcurrency) throws SQLException { BaseStatement stat = (BaseStatement) createStatement(resultSetType, resultSetConcurrency); boolean hasResultSet = stat.executeWithFlags(s, QueryExecutor.QUERY_SUPPRESS_BEGIN); while (!hasResultSet && stat.getUpdateCount() != -1) { hasResultSet = stat.getMoreResults(); } if (!hasResultSet) { throw new PSQLException(GT.tr("No results were returned by the query."), PSQLState.NO_DATA); } // Transfer warnings to the connection, since the user never // has a chance to see the statement itself. SQLWarning warnings = stat.getWarnings(); if (warnings != null) { addWarning(warnings); } return castNonNull(stat.getResultSet(), "hasResultSet==true, yet getResultSet()==null"); } @Override public void execSQLUpdate(String s) throws SQLException { BaseStatement stmt = (BaseStatement) createStatement(); if (stmt.executeWithFlags(s, QueryExecutor.QUERY_NO_METADATA | QueryExecutor.QUERY_NO_RESULTS | QueryExecutor.QUERY_SUPPRESS_BEGIN)) { throw new PSQLException(GT.tr("A result was returned when none was expected."), PSQLState.TOO_MANY_RESULTS); } // Transfer warnings to the connection, since the user never // has a chance to see the statement itself. SQLWarning warnings = stmt.getWarnings(); if (warnings != null) { addWarning(warnings); } stmt.close(); } void execSQLUpdate(CachedQuery query) throws SQLException { BaseStatement stmt = (BaseStatement) createStatement(); if (stmt.executeWithFlags(query, QueryExecutor.QUERY_NO_METADATA | QueryExecutor.QUERY_NO_RESULTS | QueryExecutor.QUERY_SUPPRESS_BEGIN)) { throw new PSQLException(GT.tr("A result was returned when none was expected."), PSQLState.TOO_MANY_RESULTS); } // Transfer warnings to the connection, since the user never // has a chance to see the statement itself. SQLWarning warnings = stmt.getWarnings(); if (warnings != null) { addWarning(warnings); } stmt.close(); } /** * <p>In SQL, a result table can be retrieved through a cursor that is named. The current row of a * result can be updated or deleted using a positioned update/delete statement that references the * cursor name.</p> * * <p>We do not support positioned update/delete, so this is a no-op.</p> * * @param cursor the cursor name * @throws SQLException if a database access error occurs */ public void setCursorName(String cursor) throws SQLException { checkClosed(); // No-op. } /** * getCursorName gets the cursor name. * * @return the current cursor name * @throws SQLException if a database access error occurs */ public @Nullable String getCursorName() throws SQLException { checkClosed(); return null; } /** * <p>We are required to bring back certain information by the DatabaseMetaData class. These * functions do that.</p> * * <p>Method getURL() brings back the URL (good job we saved it)</p> * * @return the url * @throws SQLException just in case... */ public String getURL() throws SQLException { return creatingURL; } /** * Method getUserName() brings back the User Name (again, we saved it). * * @return the user name * @throws SQLException just in case... */ public String getUserName() throws SQLException { return queryExecutor.getUser(); } public Fastpath getFastpathAPI() throws SQLException { checkClosed(); if (fastpath == null) { fastpath = new Fastpath(this); } return fastpath; } // This holds a reference to the Fastpath API if already open private @Nullable Fastpath fastpath; public LargeObjectManager getLargeObjectAPI() throws SQLException { checkClosed(); if (largeobject == null) { largeobject = new LargeObjectManager(this); } return largeobject; } // This holds a reference to the LargeObject API if already open private @Nullable LargeObjectManager largeobject; /* * This method is used internally to return an object based around org.postgresql's more unique * data types. * * <p>It uses an internal HashMap to get the handling class. If the type is not supported, then an * instance of org.postgresql.util.PGobject is returned. * * You can use the getValue() or setValue() methods to handle the returned object. Custom objects * can have their own methods. * * @return PGobject for this type, and set to value * * @exception SQLException if value is not correct for this type */ @Override public Object getObject(String type, @Nullable String value, byte @Nullable [] byteValue) throws SQLException { if (typemap != null) { Class<?> c = typemap.get(type); if (c != null) { // Handle the type (requires SQLInput & SQLOutput classes to be implemented) throw new PSQLException(GT.tr("Custom type maps are not supported."), PSQLState.NOT_IMPLEMENTED); } } PGobject obj = null; if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "Constructing object from type={0} value=<{1}>", new Object[]{type, value}); } try { Class<? extends PGobject> klass = typeCache.getPGobject(type); // If className is not null, then try to instantiate it, // It must be basetype PGobject // This is used to implement the org.postgresql unique types (like lseg, // point, etc). if (klass != null) { obj = klass.newInstance(); obj.setType(type); if (byteValue != null && obj instanceof PGBinaryObject) { PGBinaryObject binObj = (PGBinaryObject) obj; binObj.setByteValue(byteValue, 0); } else { obj.setValue(value); } } else { // If className is null, then the type is unknown. // so return a PGobject with the type set, and the value set obj = new PGobject(); obj.setType(type); obj.setValue(value); } return obj; } catch (SQLException sx) { // rethrow the exception. Done because we capture any others next throw sx; } catch (Exception ex) { throw new PSQLException(GT.tr("Failed to create object for: {0}.", type), PSQLState.CONNECTION_FAILURE, ex); } } protected TypeInfo createTypeInfo(BaseConnection conn, int unknownLength) { return new TypeInfoCache(conn, unknownLength); } public TypeInfo getTypeInfo() { return typeCache; } @Override public void addDataType(String type, String name) { try { addDataType(type, Class.forName(name).asSubclass(PGobject.class)); } catch (Exception e) { throw new RuntimeException("Cannot register new type: " + e); } } @Override public void addDataType(String type, Class<? extends PGobject> klass) throws SQLException { checkClosed(); typeCache.addDataType(type, klass); } // This initialises the objectTypes hash map private void initObjectTypes(Properties info) throws SQLException { // Add in the types that come packaged with the driver. // These can be overridden later if desired. addDataType("box", org.postgresql.geometric.PGbox.class); addDataType("circle", org.postgresql.geometric.PGcircle.class); addDataType("line", org.postgresql.geometric.PGline.class); addDataType("lseg", org.postgresql.geometric.PGlseg.class); addDataType("path", org.postgresql.geometric.PGpath.class); addDataType("point", org.postgresql.geometric.PGpoint.class); addDataType("polygon", org.postgresql.geometric.PGpolygon.class); addDataType("money", org.postgresql.util.PGmoney.class); addDataType("interval", org.postgresql.util.PGInterval.class); Enumeration<?> e = info.propertyNames(); while (e.hasMoreElements()) { String propertyName = (String) e.nextElement(); if (propertyName != null && propertyName.startsWith("datatype.")) { String typeName = propertyName.substring(9); String className = castNonNull(info.getProperty(propertyName)); Class<?> klass; try { klass = Class.forName(className); } catch (ClassNotFoundException cnfe) { throw new PSQLException( GT.tr("Unable to load the class {0} responsible for the datatype {1}", className, typeName), PSQLState.SYSTEM_ERROR, cnfe); } addDataType(typeName, klass.asSubclass(PGobject.class)); } } } /** * <B>Note:</B> even though {@code Statement} is automatically closed when it is garbage * collected, it is better to close it explicitly to lower resource consumption. * The spec says that calling close on a closed connection is a no-op. * * {@inheritDoc} */ @Override public void close() throws SQLException { if (queryExecutor == null) { // This might happen in case constructor throws an exception (e.g. host being not available). // When that happens the connection is still registered in the finalizer queue, so it gets finalized return; } if (queryExecutor.isClosed()) { return; } releaseTimer(); queryExecutor.close(); openStackTrace = null; } @Override public String nativeSQL(String sql) throws SQLException { checkClosed(); CachedQuery cachedQuery = queryExecutor.createQuery(sql, false, true); return cachedQuery.query.getNativeSql(); } @Override public synchronized @Nullable SQLWarning getWarnings() throws SQLException { checkClosed(); SQLWarning newWarnings = queryExecutor.getWarnings(); // NB: also clears them. if (firstWarning == null) { firstWarning = newWarnings; } else if (newWarnings != null) { firstWarning.setNextWarning(newWarnings); // Chain them on. } return firstWarning; } @Override public synchronized void clearWarnings() throws SQLException { checkClosed(); //noinspection ThrowableNotThrown queryExecutor.getWarnings(); // Clear and discard. firstWarning = null; } @Override public void setReadOnly(boolean readOnly) throws SQLException { checkClosed(); if (queryExecutor.getTransactionState() != TransactionState.IDLE) { throw new PSQLException( GT.tr("Cannot change transaction read-only property in the middle of a transaction."), PSQLState.ACTIVE_SQL_TRANSACTION); } if (readOnly != this.readOnly && autoCommit && this.readOnlyBehavior == ReadOnlyBehavior.always) { execSQLUpdate(readOnly ? setSessionReadOnly : setSessionNotReadOnly); } this.readOnly = readOnly; LOGGER.log(Level.FINE, " setReadOnly = {0}", readOnly); } @Override public boolean isReadOnly() throws SQLException { checkClosed(); return readOnly; } @Override public boolean hintReadOnly() { return readOnly && readOnlyBehavior != ReadOnlyBehavior.ignore; } @Override public void setAutoCommit(boolean autoCommit) throws SQLException { checkClosed(); if (this.autoCommit == autoCommit) { return; } if (!this.autoCommit) { commit(); } // if the connection is read only, we need to make sure session settings are // correct when autocommit status changed if (this.readOnly && readOnlyBehavior == ReadOnlyBehavior.always) { // if we are turning on autocommit, we need to set session // to read only if (autoCommit) { this.autoCommit = true; execSQLUpdate(setSessionReadOnly); } else { // if we are turning auto commit off, we need to // disable session execSQLUpdate(setSessionNotReadOnly); } } this.autoCommit = autoCommit; LOGGER.log(Level.FINE, " setAutoCommit = {0}", autoCommit); } @Override public boolean getAutoCommit() throws SQLException { checkClosed(); return this.autoCommit; } private void executeTransactionCommand(Query query) throws SQLException { int flags = QueryExecutor.QUERY_NO_METADATA | QueryExecutor.QUERY_NO_RESULTS | QueryExecutor.QUERY_SUPPRESS_BEGIN; if (prepareThreshold == 0) { flags |= QueryExecutor.QUERY_ONESHOT; } try { getQueryExecutor().execute(query, null, new TransactionCommandHandler(), 0, 0, flags); } catch (SQLException e) { // Don't retry composite queries as it might get partially executed if (query.getSubqueries() != null || !queryExecutor.willHealOnRetry(e)) { throw e; } query.close(); // retry getQueryExecutor().execute(query, null, new TransactionCommandHandler(), 0, 0, flags); } } @Override public void commit() throws SQLException { checkClosed(); if (autoCommit) { throw new PSQLException(GT.tr("Cannot commit when autoCommit is enabled."), PSQLState.NO_ACTIVE_SQL_TRANSACTION); } if (queryExecutor.getTransactionState() != TransactionState.IDLE) { executeTransactionCommand(commitQuery); } } protected void checkClosed() throws SQLException { if (isClosed()) { throw new PSQLException(GT.tr("This connection has been closed."), PSQLState.CONNECTION_DOES_NOT_EXIST); } } @Override public void rollback() throws SQLException { checkClosed(); if (autoCommit) { throw new PSQLException(GT.tr("Cannot rollback when autoCommit is enabled."), PSQLState.NO_ACTIVE_SQL_TRANSACTION); } if (queryExecutor.getTransactionState() != TransactionState.IDLE) { executeTransactionCommand(rollbackQuery); } else { // just log for debugging LOGGER.log(Level.FINE, "Rollback requested but no transaction in progress"); } } public TransactionState getTransactionState() { return queryExecutor.getTransactionState(); } public int getTransactionIsolation() throws SQLException { checkClosed(); String level = null; final ResultSet rs = execSQLQuery("SHOW TRANSACTION ISOLATION LEVEL"); // nb: no BEGIN triggered if (rs.next()) { level = rs.getString(1); } rs.close(); // TODO revisit: throw exception instead of silently eating the error in unknown cases? if (level == null) { return Connection.TRANSACTION_READ_COMMITTED; // Best guess. } level = level.toUpperCase(Locale.US); if (level.equals("READ COMMITTED")) { return Connection.TRANSACTION_READ_COMMITTED; } if (level.equals("READ UNCOMMITTED")) { return Connection.TRANSACTION_READ_UNCOMMITTED; } if (level.equals("REPEATABLE READ")) { return Connection.TRANSACTION_REPEATABLE_READ; } if (level.equals("SERIALIZABLE")) { return Connection.TRANSACTION_SERIALIZABLE; } return Connection.TRANSACTION_READ_COMMITTED; // Best guess. } public void setTransactionIsolation(int level) throws SQLException { checkClosed(); if (queryExecutor.getTransactionState() != TransactionState.IDLE) { throw new PSQLException( GT.tr("Cannot change transaction isolation level in the middle of a transaction."), PSQLState.ACTIVE_SQL_TRANSACTION); } String isolationLevelName = getIsolationLevelName(level); if (isolationLevelName == null) { throw new PSQLException(GT.tr("Transaction isolation level {0} not supported.", level), PSQLState.NOT_IMPLEMENTED); } String isolationLevelSQL = "SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL " + isolationLevelName; execSQLUpdate(isolationLevelSQL); // nb: no BEGIN triggered LOGGER.log(Level.FINE, " setTransactionIsolation = {0}", isolationLevelName); } protected @Nullable String getIsolationLevelName(int level) { switch (level) { case Connection.TRANSACTION_READ_COMMITTED: return "READ COMMITTED"; case Connection.TRANSACTION_SERIALIZABLE: return "SERIALIZABLE"; case Connection.TRANSACTION_READ_UNCOMMITTED: return "READ UNCOMMITTED"; case Connection.TRANSACTION_REPEATABLE_READ: return "REPEATABLE READ"; default: return null; } } public void setCatalog(String catalog) throws SQLException { checkClosed(); // no-op } public String getCatalog() throws SQLException { checkClosed(); return queryExecutor.getDatabase(); } public boolean getHideUnprivilegedObjects() { return hideUnprivilegedObjects; } /** * <p>Overrides finalize(). If called, it closes the connection.</p> * * <p>This was done at the request of <a href="mailto:[email protected]">Rachel * Greenham</a> who hit a problem where multiple clients didn't close the connection, and once a * fortnight enough clients were open to kill the postgres server.</p> */ protected void finalize() throws Throwable { try { if (openStackTrace != null) { LOGGER.log(Level.WARNING, GT.tr("Finalizing a Connection that was never closed:"), openStackTrace); } close(); } finally { super.finalize(); } } /** * Get server version number. * * @return server version number */ public String getDBVersionNumber() { return queryExecutor.getServerVersion(); } /** * Get server major version. * * @return server major version */ public int getServerMajorVersion() { try { StringTokenizer versionTokens = new StringTokenizer(queryExecutor.getServerVersion(), "."); // aaXbb.ccYdd return integerPart(versionTokens.nextToken()); // return X } catch (NoSuchElementException e) { return 0; } } /** * Get server minor version. * * @return server minor version */ public int getServerMinorVersion() { try { StringTokenizer versionTokens = new StringTokenizer(queryExecutor.getServerVersion(), "."); // aaXbb.ccYdd versionTokens.nextToken(); // Skip aaXbb return integerPart(versionTokens.nextToken()); // return Y } catch (NoSuchElementException e) { return 0; } } @Override public boolean haveMinimumServerVersion(int ver) { return queryExecutor.getServerVersionNum() >= ver; } @Override public boolean haveMinimumServerVersion(Version ver) { return haveMinimumServerVersion(ver.getVersionNum()); } @Pure @Override public Encoding getEncoding() { return queryExecutor.getEncoding(); } @Override public byte @PolyNull [] encodeString(@PolyNull String str) throws SQLException { try { return getEncoding().encode(str); } catch (IOException ioe) { throw new PSQLException(GT.tr("Unable to translate data into the desired encoding."), PSQLState.DATA_ERROR, ioe); } } @Override public String escapeString(String str) throws SQLException { return Utils.escapeLiteral(null, str, queryExecutor.getStandardConformingStrings()) .toString(); } @Override public boolean getStandardConformingStrings() { return queryExecutor.getStandardConformingStrings(); } // This is a cache of the DatabaseMetaData instance for this connection protected java.sql.@Nullable DatabaseMetaData metadata; @Override public boolean isClosed() throws SQLException { return queryExecutor.isClosed(); } @Override public void cancelQuery() throws SQLException { checkClosed(); queryExecutor.sendQueryCancel(); } @Override public PGNotification[] getNotifications() throws SQLException { return getNotifications(-1); } @Override public PGNotification[] getNotifications(int timeoutMillis) throws SQLException { checkClosed(); getQueryExecutor().processNotifies(timeoutMillis); // Backwards-compatibility hand-holding. PGNotification[] notifications = queryExecutor.getNotifications(); return notifications; } /** * Handler for transaction queries. */ private class TransactionCommandHandler extends ResultHandlerBase { public void handleCompletion() throws SQLException { SQLWarning warning = getWarning(); if (warning != null) { PgConnection.this.addWarning(warning); } super.handleCompletion(); } } public int getPrepareThreshold() { return prepareThreshold; } public void setDefaultFetchSize(int fetchSize) throws SQLException { if (fetchSize < 0) { throw new PSQLException(GT.tr("Fetch size must be a value greater to or equal to 0."), PSQLState.INVALID_PARAMETER_VALUE); } this.defaultFetchSize = fetchSize; LOGGER.log(Level.FINE, " setDefaultFetchSize = {0}", fetchSize); } public int getDefaultFetchSize() { return defaultFetchSize; } public void setPrepareThreshold(int newThreshold) { this.prepareThreshold = newThreshold; LOGGER.log(Level.FINE, " setPrepareThreshold = {0}", newThreshold); } public boolean getForceBinary() { return forcebinary; } public void setForceBinary(boolean newValue) { this.forcebinary = newValue; LOGGER.log(Level.FINE, " setForceBinary = {0}", newValue); } public void setTypeMapImpl(Map<String, Class<?>> map) throws SQLException { typemap = map; } public Logger getLogger() { return LOGGER; } public int getProtocolVersion() { return queryExecutor.getProtocolVersion(); } public boolean getStringVarcharFlag() { return bindStringAsVarchar; } private @Nullable CopyManager copyManager; public CopyManager getCopyAPI() throws SQLException { checkClosed(); if (copyManager == null) { copyManager = new CopyManager(this); } return copyManager; } public boolean binaryTransferSend(int oid) { return queryExecutor.useBinaryForSend(oid); } public int getBackendPID() { return queryExecutor.getBackendPID(); } public boolean isColumnSanitiserDisabled() { return this.disableColumnSanitiser; } public void setDisableColumnSanitiser(boolean disableColumnSanitiser) { this.disableColumnSanitiser = disableColumnSanitiser; LOGGER.log(Level.FINE, " setDisableColumnSanitiser = {0}", disableColumnSanitiser); } @Override public PreferQueryMode getPreferQueryMode() { return queryExecutor.getPreferQueryMode(); } @Override public AutoSave getAutosave() { return queryExecutor.getAutoSave(); } @Override public void setAutosave(AutoSave autoSave) { queryExecutor.setAutoSave(autoSave); LOGGER.log(Level.FINE, " setAutosave = {0}", autoSave.value()); } protected void abort() { queryExecutor.abort(); } private synchronized Timer getTimer() { if (cancelTimer == null) { cancelTimer = Driver.getSharedTimer().getTimer(); } return cancelTimer; } private synchronized void releaseTimer() { if (cancelTimer != null) { cancelTimer = null; Driver.getSharedTimer().releaseTimer(); } } @Override public void addTimerTask(TimerTask timerTask, long milliSeconds) { Timer timer = getTimer(); timer.schedule(timerTask, milliSeconds); } @Override public void purgeTimerTasks() { Timer timer = cancelTimer; if (timer != null) { timer.purge(); } } @Override public String escapeIdentifier(String identifier) throws SQLException { return Utils.escapeIdentifier(null, identifier).toString(); } @Override public String escapeLiteral(String literal) throws SQLException { return Utils.escapeLiteral(null, literal, queryExecutor.getStandardConformingStrings()) .toString(); } @Override public LruCache<FieldMetadata.Key, FieldMetadata> getFieldMetadataCache() { return fieldMetadataCache; } @Override public PGReplicationConnection getReplicationAPI() { return new PGReplicationConnectionImpl(this); } // Parse a "dirty" integer surrounded by non-numeric characters private static int integerPart(String dirtyString) { int start = 0; while (start < dirtyString.length() && !Character.isDigit(dirtyString.charAt(start))) { ++start; } int end = start; while (end < dirtyString.length() && Character.isDigit(dirtyString.charAt(end))) { ++end; } if (start == end) { return 0; } return Integer.parseInt(dirtyString.substring(start, end)); } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkClosed(); return new PgStatement(this, resultSetType, resultSetConcurrency, resultSetHoldability); } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkClosed(); return new PgPreparedStatement(this, sql, resultSetType, resultSetConcurrency, resultSetHoldability); } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkClosed(); return new PgCallableStatement(this, sql, resultSetType, resultSetConcurrency, resultSetHoldability); } @Override public DatabaseMetaData getMetaData() throws SQLException { checkClosed(); if (metadata == null) { metadata = new PgDatabaseMetaData(this); } return metadata; } @Override public void setTypeMap(Map<String, Class<?>> map) throws SQLException { setTypeMapImpl(map); LOGGER.log(Level.FINE, " setTypeMap = {0}", map); } protected Array makeArray(int oid, @Nullable String fieldString) throws SQLException { return new PgArray(this, oid, fieldString); } protected Blob makeBlob(long oid) throws SQLException { return new PgBlob(this, oid); } protected Clob makeClob(long oid) throws SQLException { return new PgClob(this, oid); } protected SQLXML makeSQLXML() throws SQLException { return new PgSQLXML(this); } @Override public Clob createClob() throws SQLException { checkClosed(); throw org.postgresql.Driver.notImplemented(this.getClass(), "createClob()"); } @Override public Blob createBlob() throws SQLException { checkClosed(); throw org.postgresql.Driver.notImplemented(this.getClass(), "createBlob()"); } @Override public NClob createNClob() throws SQLException { checkClosed(); throw org.postgresql.Driver.notImplemented(this.getClass(), "createNClob()"); } @Override public SQLXML createSQLXML() throws SQLException { checkClosed(); return makeSQLXML(); } @Override public Struct createStruct(String typeName, Object[] attributes) throws SQLException { checkClosed(); throw org.postgresql.Driver.notImplemented(this.getClass(), "createStruct(String, Object[])"); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public Array createArrayOf(String typeName, @Nullable Object elements) throws SQLException { checkClosed(); final TypeInfo typeInfo = getTypeInfo(); final int oid = typeInfo.getPGArrayType(typeName); final char delim = typeInfo.getArrayDelimiter(oid); if (oid == Oid.UNSPECIFIED) { throw new PSQLException(GT.tr("Unable to find server array type for provided name {0}.", typeName), PSQLState.INVALID_NAME); } if (elements == null) { return makeArray(oid, null); } final ArrayEncoding.ArrayEncoder arraySupport = ArrayEncoding.getArrayEncoder(elements); if (arraySupport.supportBinaryRepresentation(oid) && getPreferQueryMode() != PreferQueryMode.SIMPLE) { return new PgArray(this, oid, arraySupport.toBinaryRepresentation(this, elements, oid)); } final String arrayString = arraySupport.toArrayString(delim, elements); return makeArray(oid, arrayString); } @Override public Array createArrayOf(String typeName, @Nullable Object @Nullable [] elements) throws SQLException { return createArrayOf(typeName, (Object) elements); } @Override public boolean isValid(int timeout) throws SQLException { if (timeout < 0) { throw new PSQLException(GT.tr("Invalid timeout ({0}<0).", timeout), PSQLState.INVALID_PARAMETER_VALUE); } if (isClosed()) { return false; } boolean changedNetworkTimeout = false; try { int oldNetworkTimeout = getNetworkTimeout(); int newNetworkTimeout = (int) Math.min(timeout * 1000L, Integer.MAX_VALUE); try { // change network timeout only if the new value is less than the current // (zero means infinite timeout) if (newNetworkTimeout != 0 && (oldNetworkTimeout == 0 || newNetworkTimeout < oldNetworkTimeout)) { changedNetworkTimeout = true; setNetworkTimeout(null, newNetworkTimeout); } if (replicationConnection) { Statement statement = createStatement(); statement.execute("IDENTIFY_SYSTEM"); statement.close(); } else { if (checkConnectionQuery == null) { checkConnectionQuery = prepareStatement(""); } checkConnectionQuery.executeUpdate(); } return true; } finally { if (changedNetworkTimeout) { setNetworkTimeout(null, oldNetworkTimeout); } } } catch (SQLException e) { if (PSQLState.IN_FAILED_SQL_TRANSACTION.getState().equals(e.getSQLState())) { // "current transaction aborted", assume the connection is up and running return true; } LOGGER.log(Level.FINE, GT.tr("Validating connection."), e); } return false; } @Override public void setClientInfo(String name, @Nullable String value) throws SQLClientInfoException { try { checkClosed(); } catch (final SQLException cause) { Map<String, ClientInfoStatus> failures = new HashMap<String, ClientInfoStatus>(); failures.put(name, ClientInfoStatus.REASON_UNKNOWN); throw new SQLClientInfoException(GT.tr("This connection has been closed."), failures, cause); } if (haveMinimumServerVersion(ServerVersion.v9_0) && "ApplicationName".equals(name)) { if (value == null) { value = ""; } final String oldValue = queryExecutor.getApplicationName(); if (value.equals(oldValue)) { return; } try { StringBuilder sql = new StringBuilder("SET application_name = '"); Utils.escapeLiteral(sql, value, getStandardConformingStrings()); sql.append("'"); execSQLUpdate(sql.toString()); } catch (SQLException sqle) { Map<String, ClientInfoStatus> failures = new HashMap<String, ClientInfoStatus>(); failures.put(name, ClientInfoStatus.REASON_UNKNOWN); throw new SQLClientInfoException( GT.tr("Failed to set ClientInfo property: {0}", "ApplicationName"), sqle.getSQLState(), failures, sqle); } if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, " setClientInfo = {0} {1}", new Object[]{name, value}); } clientInfo.put(name, value); return; } addWarning(new SQLWarning(GT.tr("ClientInfo property not supported."), PSQLState.NOT_IMPLEMENTED.getState())); } @Override public void setClientInfo(Properties properties) throws SQLClientInfoException { try { checkClosed(); } catch (final SQLException cause) { Map<String, ClientInfoStatus> failures = new HashMap<String, ClientInfoStatus>(); for (Map.Entry<Object, Object> e : properties.entrySet()) { failures.put((String) e.getKey(), ClientInfoStatus.REASON_UNKNOWN); } throw new SQLClientInfoException(GT.tr("This connection has been closed."), failures, cause); } Map<String, ClientInfoStatus> failures = new HashMap<String, ClientInfoStatus>(); for (String name : new String[]{"ApplicationName"}) { try { setClientInfo(name, properties.getProperty(name, null)); } catch (SQLClientInfoException e) { failures.putAll(e.getFailedProperties()); } } if (!failures.isEmpty()) { throw new SQLClientInfoException(GT.tr("One or more ClientInfo failed."), PSQLState.NOT_IMPLEMENTED.getState(), failures); } } @Override public @Nullable String getClientInfo(String name) throws SQLException { checkClosed(); clientInfo.put("ApplicationName", queryExecutor.getApplicationName()); return clientInfo.getProperty(name); } @Override public Properties getClientInfo() throws SQLException { checkClosed(); clientInfo.put("ApplicationName", queryExecutor.getApplicationName()); return clientInfo; } public <T> T createQueryObject(Class<T> ifc) throws SQLException { checkClosed(); throw org.postgresql.Driver.notImplemented(this.getClass(), "createQueryObject(Class<T>)"); } public boolean getLogServerErrorDetail() { return logServerErrorDetail; } @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { checkClosed(); return iface.isAssignableFrom(getClass()); } @Override public <T> T unwrap(Class<T> iface) throws SQLException { checkClosed(); if (iface.isAssignableFrom(getClass())) { return iface.cast(this); } throw new SQLException("Cannot unwrap to " + iface.getName()); } public @Nullable String getSchema() throws SQLException { checkClosed(); Statement stmt = createStatement(); try { ResultSet rs = stmt.executeQuery("select current_schema()"); try { if (!rs.next()) { return null; // Is it ever possible? } return rs.getString(1); } finally { rs.close(); } } finally { stmt.close(); } } public void setSchema(@Nullable String schema) throws SQLException { checkClosed(); Statement stmt = createStatement(); try { if (schema == null) { stmt.executeUpdate("SET SESSION search_path TO DEFAULT"); } else { StringBuilder sb = new StringBuilder(); sb.append("SET SESSION search_path TO '"); Utils.escapeLiteral(sb, schema, getStandardConformingStrings()); sb.append("'"); stmt.executeUpdate(sb.toString()); LOGGER.log(Level.FINE, " setSchema = {0}", schema); } } finally { stmt.close(); } } public class AbortCommand implements Runnable { public void run() { abort(); } } public void abort(Executor executor) throws SQLException { if (executor == null) { throw new SQLException("executor is null"); } if (isClosed()) { return; } SQL_PERMISSION_ABORT.checkGuard(this); AbortCommand command = new AbortCommand(); executor.execute(command); } public void setNetworkTimeout(@Nullable Executor executor /*not used*/, int milliseconds) throws SQLException { checkClosed(); if (milliseconds < 0) { throw new PSQLException(GT.tr("Network timeout must be a value greater than or equal to 0."), PSQLState.INVALID_PARAMETER_VALUE); } SecurityManager securityManager = System.getSecurityManager(); if (securityManager != null) { securityManager.checkPermission(SQL_PERMISSION_NETWORK_TIMEOUT); } try { queryExecutor.setNetworkTimeout(milliseconds); } catch (IOException ioe) { throw new PSQLException(GT.tr("Unable to set network timeout."), PSQLState.COMMUNICATION_ERROR, ioe); } } public int getNetworkTimeout() throws SQLException { checkClosed(); try { return queryExecutor.getNetworkTimeout(); } catch (IOException ioe) { throw new PSQLException(GT.tr("Unable to get network timeout."), PSQLState.COMMUNICATION_ERROR, ioe); } } @Override public void setHoldability(int holdability) throws SQLException { checkClosed(); switch (holdability) { case ResultSet.CLOSE_CURSORS_AT_COMMIT: rsHoldability = holdability; break; case ResultSet.HOLD_CURSORS_OVER_COMMIT: rsHoldability = holdability; break; default: throw new PSQLException(GT.tr("Unknown ResultSet holdability setting: {0}.", holdability), PSQLState.INVALID_PARAMETER_VALUE); } LOGGER.log(Level.FINE, " setHoldability = {0}", holdability); } @Override public int getHoldability() throws SQLException { checkClosed(); return rsHoldability; } @Override public Savepoint setSavepoint() throws SQLException { checkClosed(); String pgName; if (getAutoCommit()) { throw new PSQLException(GT.tr("Cannot establish a savepoint in auto-commit mode."), PSQLState.NO_ACTIVE_SQL_TRANSACTION); } PSQLSavepoint savepoint = new PSQLSavepoint(savepointId++); pgName = savepoint.getPGName(); // Note we can't use execSQLUpdate because we don't want // to suppress BEGIN. Statement stmt = createStatement(); stmt.executeUpdate("SAVEPOINT " + pgName); stmt.close(); return savepoint; } @Override public Savepoint setSavepoint(String name) throws SQLException { checkClosed(); if (getAutoCommit()) { throw new PSQLException(GT.tr("Cannot establish a savepoint in auto-commit mode."), PSQLState.NO_ACTIVE_SQL_TRANSACTION); } PSQLSavepoint savepoint = new PSQLSavepoint(name); // Note we can't use execSQLUpdate because we don't want // to suppress BEGIN. Statement stmt = createStatement(); stmt.executeUpdate("SAVEPOINT " + savepoint.getPGName()); stmt.close(); return savepoint; } @Override public void rollback(Savepoint savepoint) throws SQLException { checkClosed(); PSQLSavepoint pgSavepoint = (PSQLSavepoint) savepoint; execSQLUpdate("ROLLBACK TO SAVEPOINT " + pgSavepoint.getPGName()); } @Override public void releaseSavepoint(Savepoint savepoint) throws SQLException { checkClosed(); PSQLSavepoint pgSavepoint = (PSQLSavepoint) savepoint; execSQLUpdate("RELEASE SAVEPOINT " + pgSavepoint.getPGName()); pgSavepoint.invalidate(); } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { checkClosed(); return createStatement(resultSetType, resultSetConcurrency, getHoldability()); } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { checkClosed(); return prepareStatement(sql, resultSetType, resultSetConcurrency, getHoldability()); } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { checkClosed(); return prepareCall(sql, resultSetType, resultSetConcurrency, getHoldability()); } @Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { if (autoGeneratedKeys != Statement.RETURN_GENERATED_KEYS) { return prepareStatement(sql); } return prepareStatement(sql, (String[]) null); } @Override public PreparedStatement prepareStatement(String sql, int @Nullable [] columnIndexes) throws SQLException { if (columnIndexes != null && columnIndexes.length == 0) { return prepareStatement(sql); } checkClosed(); throw new PSQLException(GT.tr("Returning autogenerated keys is not supported."), PSQLState.NOT_IMPLEMENTED); } @Override public PreparedStatement prepareStatement(String sql, String @Nullable[] columnNames) throws SQLException { if (columnNames != null && columnNames.length == 0) { return prepareStatement(sql); } CachedQuery cachedQuery = borrowReturningQuery(sql, columnNames); PgPreparedStatement ps = new PgPreparedStatement(this, cachedQuery, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, getHoldability()); Query query = cachedQuery.query; SqlCommand sqlCommand = query.getSqlCommand(); if (sqlCommand != null) { ps.wantsGeneratedKeysAlways = sqlCommand.isReturningKeywordPresent(); } else { // If composite query is given, just ignore "generated keys" arguments } return ps; } @Override public final Map<String,String> getParameterStatuses() { return queryExecutor.getParameterStatuses(); } @Override public final @Nullable String getParameterStatus(String parameterName) { return queryExecutor.getParameterStatus(parameterName); } @Override public boolean getAdaptiveFetch() { return queryExecutor.getAdaptiveFetch(); } @Override public void setAdaptiveFetch(boolean adaptiveFetch) { queryExecutor.setAdaptiveFetch(adaptiveFetch); } @Override public PGXmlFactoryFactory getXmlFactoryFactory() throws SQLException { PGXmlFactoryFactory xmlFactoryFactory = this.xmlFactoryFactory; if (xmlFactoryFactory != null) { return xmlFactoryFactory; } if (xmlFactoryFactoryClass == null || xmlFactoryFactoryClass.equals("")) { xmlFactoryFactory = DefaultPGXmlFactoryFactory.INSTANCE; } else if (xmlFactoryFactoryClass.equals("LEGACY_INSECURE")) { xmlFactoryFactory = LegacyInsecurePGXmlFactoryFactory.INSTANCE; } else { Class<?> clazz; try { clazz = Class.forName(xmlFactoryFactoryClass); } catch (ClassNotFoundException ex) { throw new PSQLException( GT.tr("Could not instantiate xmlFactoryFactory: {0}", xmlFactoryFactoryClass), PSQLState.INVALID_PARAMETER_VALUE, ex); } if (!clazz.isAssignableFrom(PGXmlFactoryFactory.class)) { throw new PSQLException( GT.tr("Connection property xmlFactoryFactory must implement PGXmlFactoryFactory: {0}", xmlFactoryFactoryClass), PSQLState.INVALID_PARAMETER_VALUE); } try { xmlFactoryFactory = (PGXmlFactoryFactory) clazz.newInstance(); } catch (Exception ex) { throw new PSQLException( GT.tr("Could not instantiate xmlFactoryFactory: {0}", xmlFactoryFactoryClass), PSQLState.INVALID_PARAMETER_VALUE, ex); } } this.xmlFactoryFactory = xmlFactoryFactory; return xmlFactoryFactory; } }
pgjdbc/src/main/java/org/postgresql/jdbc/PgConnection.java
/* * Copyright (c) 2004, PostgreSQL Global Development Group * See the LICENSE file in the project root for more information. */ package org.postgresql.jdbc; import static org.postgresql.util.internal.Nullness.castNonNull; import org.postgresql.Driver; import org.postgresql.PGNotification; import org.postgresql.PGProperty; import org.postgresql.copy.CopyManager; import org.postgresql.core.BaseConnection; import org.postgresql.core.BaseStatement; import org.postgresql.core.CachedQuery; import org.postgresql.core.ConnectionFactory; import org.postgresql.core.Encoding; import org.postgresql.core.Oid; import org.postgresql.core.Query; import org.postgresql.core.QueryExecutor; import org.postgresql.core.ReplicationProtocol; import org.postgresql.core.ResultHandlerBase; import org.postgresql.core.ServerVersion; import org.postgresql.core.SqlCommand; import org.postgresql.core.TransactionState; import org.postgresql.core.TypeInfo; import org.postgresql.core.Utils; import org.postgresql.core.Version; import org.postgresql.fastpath.Fastpath; import org.postgresql.largeobject.LargeObjectManager; import org.postgresql.replication.PGReplicationConnection; import org.postgresql.replication.PGReplicationConnectionImpl; import org.postgresql.util.GT; import org.postgresql.util.HostSpec; import org.postgresql.util.LruCache; import org.postgresql.util.PGBinaryObject; import org.postgresql.util.PGobject; import org.postgresql.util.PSQLException; import org.postgresql.util.PSQLState; import org.postgresql.xml.DefaultPGXmlFactoryFactory; import org.postgresql.xml.LegacyInsecurePGXmlFactoryFactory; import org.postgresql.xml.PGXmlFactoryFactory; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.PolyNull; import org.checkerframework.dataflow.qual.Pure; import java.io.IOException; import java.sql.Array; import java.sql.Blob; import java.sql.CallableStatement; import java.sql.ClientInfoStatus; import java.sql.Clob; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.NClob; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLClientInfoException; import java.sql.SQLException; import java.sql.SQLPermission; import java.sql.SQLWarning; import java.sql.SQLXML; import java.sql.Savepoint; import java.sql.Statement; import java.sql.Struct; import java.sql.Types; import java.util.Arrays; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.NoSuchElementException; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.Executor; import java.util.logging.Level; import java.util.logging.Logger; public class PgConnection implements BaseConnection { private static final Logger LOGGER = Logger.getLogger(PgConnection.class.getName()); private static final Set<Integer> SUPPORTED_BINARY_OIDS = getSupportedBinaryOids(); private static final SQLPermission SQL_PERMISSION_ABORT = new SQLPermission("callAbort"); private static final SQLPermission SQL_PERMISSION_NETWORK_TIMEOUT = new SQLPermission("setNetworkTimeout"); private enum ReadOnlyBehavior { ignore, transaction, always; } // // Data initialized on construction: // private final Properties clientInfo; /* URL we were created via */ private final String creatingURL; private final ReadOnlyBehavior readOnlyBehavior; private @Nullable Throwable openStackTrace; /* Actual network handler */ private final QueryExecutor queryExecutor; /* Query that runs COMMIT */ private final Query commitQuery; /* Query that runs ROLLBACK */ private final Query rollbackQuery; private final CachedQuery setSessionReadOnly; private final CachedQuery setSessionNotReadOnly; private final TypeInfo typeCache; private boolean disableColumnSanitiser = false; // Default statement prepare threshold. protected int prepareThreshold; /** * Default fetch size for statement. * * @see PGProperty#DEFAULT_ROW_FETCH_SIZE */ protected int defaultFetchSize; // Default forcebinary option. protected boolean forcebinary = false; private int rsHoldability = ResultSet.CLOSE_CURSORS_AT_COMMIT; private int savepointId = 0; // Connection's autocommit state. private boolean autoCommit = true; // Connection's readonly state. private boolean readOnly = false; // Filter out database objects for which the current user has no privileges granted from the DatabaseMetaData private boolean hideUnprivilegedObjects ; // Whether to include error details in logging and exceptions private final boolean logServerErrorDetail; // Bind String to UNSPECIFIED or VARCHAR? private final boolean bindStringAsVarchar; // Current warnings; there might be more on queryExecutor too. private @Nullable SQLWarning firstWarning; // Timer for scheduling TimerTasks for this connection. // Only instantiated if a task is actually scheduled. private volatile @Nullable Timer cancelTimer; private @Nullable PreparedStatement checkConnectionQuery; /** * Replication protocol in current version postgresql(10devel) supports a limited number of * commands. */ private final boolean replicationConnection; private final LruCache<FieldMetadata.Key, FieldMetadata> fieldMetadataCache; private final @Nullable String xmlFactoryFactoryClass; private @Nullable PGXmlFactoryFactory xmlFactoryFactory; final CachedQuery borrowQuery(String sql) throws SQLException { return queryExecutor.borrowQuery(sql); } final CachedQuery borrowCallableQuery(String sql) throws SQLException { return queryExecutor.borrowCallableQuery(sql); } private CachedQuery borrowReturningQuery(String sql, String @Nullable [] columnNames) throws SQLException { return queryExecutor.borrowReturningQuery(sql, columnNames); } @Override public CachedQuery createQuery(String sql, boolean escapeProcessing, boolean isParameterized, String... columnNames) throws SQLException { return queryExecutor.createQuery(sql, escapeProcessing, isParameterized, columnNames); } void releaseQuery(CachedQuery cachedQuery) { queryExecutor.releaseQuery(cachedQuery); } @Override public void setFlushCacheOnDeallocate(boolean flushCacheOnDeallocate) { queryExecutor.setFlushCacheOnDeallocate(flushCacheOnDeallocate); LOGGER.log(Level.FINE, " setFlushCacheOnDeallocate = {0}", flushCacheOnDeallocate); } // // Ctor. // @SuppressWarnings({"method.invocation.invalid", "argument.type.incompatible"}) public PgConnection(HostSpec[] hostSpecs, String user, String database, Properties info, String url) throws SQLException { // Print out the driver version number LOGGER.log(Level.FINE, org.postgresql.util.DriverInfo.DRIVER_FULL_NAME); this.creatingURL = url; this.readOnlyBehavior = getReadOnlyBehavior(PGProperty.READ_ONLY_MODE.get(info)); setDefaultFetchSize(PGProperty.DEFAULT_ROW_FETCH_SIZE.getInt(info)); setPrepareThreshold(PGProperty.PREPARE_THRESHOLD.getInt(info)); if (prepareThreshold == -1) { setForceBinary(true); } // Now make the initial connection and set up local state this.queryExecutor = ConnectionFactory.openConnection(hostSpecs, user, database, info); // WARNING for unsupported servers (8.1 and lower are not supported) if (LOGGER.isLoggable(Level.WARNING) && !haveMinimumServerVersion(ServerVersion.v8_2)) { LOGGER.log(Level.WARNING, "Unsupported Server Version: {0}", queryExecutor.getServerVersion()); } setSessionReadOnly = createQuery("SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY", false, true); setSessionNotReadOnly = createQuery("SET SESSION CHARACTERISTICS AS TRANSACTION READ WRITE", false, true); // Set read-only early if requested if (PGProperty.READ_ONLY.getBoolean(info)) { setReadOnly(true); } this.hideUnprivilegedObjects = PGProperty.HIDE_UNPRIVILEGED_OBJECTS.getBoolean(info); Set<Integer> binaryOids = getBinaryOids(info); // split for receive and send for better control Set<Integer> useBinarySendForOids = new HashSet<Integer>(binaryOids); Set<Integer> useBinaryReceiveForOids = new HashSet<Integer>(binaryOids); /* * Does not pass unit tests because unit tests expect setDate to have millisecond accuracy * whereas the binary transfer only supports date accuracy. */ useBinarySendForOids.remove(Oid.DATE); queryExecutor.setBinaryReceiveOids(useBinaryReceiveForOids); queryExecutor.setBinarySendOids(useBinarySendForOids); if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, " types using binary send = {0}", oidsToString(useBinarySendForOids)); LOGGER.log(Level.FINEST, " types using binary receive = {0}", oidsToString(useBinaryReceiveForOids)); LOGGER.log(Level.FINEST, " integer date/time = {0}", queryExecutor.getIntegerDateTimes()); } // // String -> text or unknown? // String stringType = PGProperty.STRING_TYPE.get(info); if (stringType != null) { if (stringType.equalsIgnoreCase("unspecified")) { bindStringAsVarchar = false; } else if (stringType.equalsIgnoreCase("varchar")) { bindStringAsVarchar = true; } else { throw new PSQLException( GT.tr("Unsupported value for stringtype parameter: {0}", stringType), PSQLState.INVALID_PARAMETER_VALUE); } } else { bindStringAsVarchar = true; } // Initialize timestamp stuff timestampUtils = new TimestampUtils(!queryExecutor.getIntegerDateTimes(), new QueryExecutorTimeZoneProvider(queryExecutor)); // Initialize common queries. // isParameterized==true so full parse is performed and the engine knows the query // is not a compound query with ; inside, so it could use parse/bind/exec messages commitQuery = createQuery("COMMIT", false, true).query; rollbackQuery = createQuery("ROLLBACK", false, true).query; int unknownLength = PGProperty.UNKNOWN_LENGTH.getInt(info); // Initialize object handling typeCache = createTypeInfo(this, unknownLength); initObjectTypes(info); if (PGProperty.LOG_UNCLOSED_CONNECTIONS.getBoolean(info)) { openStackTrace = new Throwable("Connection was created at this point:"); } this.logServerErrorDetail = PGProperty.LOG_SERVER_ERROR_DETAIL.getBoolean(info); this.disableColumnSanitiser = PGProperty.DISABLE_COLUMN_SANITISER.getBoolean(info); if (haveMinimumServerVersion(ServerVersion.v8_3)) { typeCache.addCoreType("uuid", Oid.UUID, Types.OTHER, "java.util.UUID", Oid.UUID_ARRAY); typeCache.addCoreType("xml", Oid.XML, Types.SQLXML, "java.sql.SQLXML", Oid.XML_ARRAY); } this.clientInfo = new Properties(); if (haveMinimumServerVersion(ServerVersion.v9_0)) { String appName = PGProperty.APPLICATION_NAME.get(info); if (appName == null) { appName = ""; } this.clientInfo.put("ApplicationName", appName); } fieldMetadataCache = new LruCache<FieldMetadata.Key, FieldMetadata>( Math.max(0, PGProperty.DATABASE_METADATA_CACHE_FIELDS.getInt(info)), Math.max(0, PGProperty.DATABASE_METADATA_CACHE_FIELDS_MIB.getInt(info) * 1024L * 1024L), false); replicationConnection = PGProperty.REPLICATION.get(info) != null; xmlFactoryFactoryClass = PGProperty.XML_FACTORY_FACTORY.get(info); } private static ReadOnlyBehavior getReadOnlyBehavior(String property) { try { return ReadOnlyBehavior.valueOf(property); } catch (IllegalArgumentException e) { try { return ReadOnlyBehavior.valueOf(property.toLowerCase(Locale.US)); } catch (IllegalArgumentException e2) { return ReadOnlyBehavior.transaction; } } } private static Set<Integer> getSupportedBinaryOids() { return new HashSet<Integer>(Arrays.asList( Oid.BYTEA, Oid.INT2, Oid.INT4, Oid.INT8, Oid.FLOAT4, Oid.FLOAT8, Oid.NUMERIC, Oid.TIME, Oid.DATE, Oid.TIMETZ, Oid.TIMESTAMP, Oid.TIMESTAMPTZ, Oid.BYTEA_ARRAY, Oid.INT2_ARRAY, Oid.INT4_ARRAY, Oid.INT8_ARRAY, Oid.OID_ARRAY, Oid.FLOAT4_ARRAY, Oid.FLOAT8_ARRAY, Oid.VARCHAR_ARRAY, Oid.TEXT_ARRAY, Oid.POINT, Oid.BOX, Oid.UUID)); } private static Set<Integer> getBinaryOids(Properties info) throws PSQLException { boolean binaryTransfer = PGProperty.BINARY_TRANSFER.getBoolean(info); // Formats that currently have binary protocol support Set<Integer> binaryOids = new HashSet<Integer>(32); if (binaryTransfer) { binaryOids.addAll(SUPPORTED_BINARY_OIDS); } String oids = PGProperty.BINARY_TRANSFER_ENABLE.get(info); if (oids != null) { binaryOids.addAll(getOidSet(oids)); } oids = PGProperty.BINARY_TRANSFER_DISABLE.get(info); if (oids != null) { binaryOids.removeAll(getOidSet(oids)); } return binaryOids; } private static Set<Integer> getOidSet(String oidList) throws PSQLException { Set<Integer> oids = new HashSet<Integer>(); StringTokenizer tokenizer = new StringTokenizer(oidList, ","); while (tokenizer.hasMoreTokens()) { String oid = tokenizer.nextToken(); oids.add(Oid.valueOf(oid)); } return oids; } private String oidsToString(Set<Integer> oids) { StringBuilder sb = new StringBuilder(); for (Integer oid : oids) { sb.append(Oid.toString(oid)); sb.append(','); } if (sb.length() > 0) { sb.setLength(sb.length() - 1); } else { sb.append(" <none>"); } return sb.toString(); } private final TimestampUtils timestampUtils; public TimestampUtils getTimestampUtils() { return timestampUtils; } /** * The current type mappings. */ protected Map<String, Class<?>> typemap = new HashMap<String, Class<?>>(); @Override public Statement createStatement() throws SQLException { // We now follow the spec and default to TYPE_FORWARD_ONLY. return createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); } @Override public PreparedStatement prepareStatement(String sql) throws SQLException { return prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); } @Override public CallableStatement prepareCall(String sql) throws SQLException { return prepareCall(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); } @Override public Map<String, Class<?>> getTypeMap() throws SQLException { checkClosed(); return typemap; } public QueryExecutor getQueryExecutor() { return queryExecutor; } public ReplicationProtocol getReplicationProtocol() { return queryExecutor.getReplicationProtocol(); } /** * This adds a warning to the warning chain. * * @param warn warning to add */ public void addWarning(SQLWarning warn) { // Add the warning to the chain if (firstWarning != null) { firstWarning.setNextWarning(warn); } else { firstWarning = warn; } } @Override public ResultSet execSQLQuery(String s) throws SQLException { return execSQLQuery(s, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); } @Override public ResultSet execSQLQuery(String s, int resultSetType, int resultSetConcurrency) throws SQLException { BaseStatement stat = (BaseStatement) createStatement(resultSetType, resultSetConcurrency); boolean hasResultSet = stat.executeWithFlags(s, QueryExecutor.QUERY_SUPPRESS_BEGIN); while (!hasResultSet && stat.getUpdateCount() != -1) { hasResultSet = stat.getMoreResults(); } if (!hasResultSet) { throw new PSQLException(GT.tr("No results were returned by the query."), PSQLState.NO_DATA); } // Transfer warnings to the connection, since the user never // has a chance to see the statement itself. SQLWarning warnings = stat.getWarnings(); if (warnings != null) { addWarning(warnings); } return castNonNull(stat.getResultSet(), "hasResultSet==true, yet getResultSet()==null"); } @Override public void execSQLUpdate(String s) throws SQLException { BaseStatement stmt = (BaseStatement) createStatement(); if (stmt.executeWithFlags(s, QueryExecutor.QUERY_NO_METADATA | QueryExecutor.QUERY_NO_RESULTS | QueryExecutor.QUERY_SUPPRESS_BEGIN)) { throw new PSQLException(GT.tr("A result was returned when none was expected."), PSQLState.TOO_MANY_RESULTS); } // Transfer warnings to the connection, since the user never // has a chance to see the statement itself. SQLWarning warnings = stmt.getWarnings(); if (warnings != null) { addWarning(warnings); } stmt.close(); } void execSQLUpdate(CachedQuery query) throws SQLException { BaseStatement stmt = (BaseStatement) createStatement(); if (stmt.executeWithFlags(query, QueryExecutor.QUERY_NO_METADATA | QueryExecutor.QUERY_NO_RESULTS | QueryExecutor.QUERY_SUPPRESS_BEGIN)) { throw new PSQLException(GT.tr("A result was returned when none was expected."), PSQLState.TOO_MANY_RESULTS); } // Transfer warnings to the connection, since the user never // has a chance to see the statement itself. SQLWarning warnings = stmt.getWarnings(); if (warnings != null) { addWarning(warnings); } stmt.close(); } /** * <p>In SQL, a result table can be retrieved through a cursor that is named. The current row of a * result can be updated or deleted using a positioned update/delete statement that references the * cursor name.</p> * * <p>We do not support positioned update/delete, so this is a no-op.</p> * * @param cursor the cursor name * @throws SQLException if a database access error occurs */ public void setCursorName(String cursor) throws SQLException { checkClosed(); // No-op. } /** * getCursorName gets the cursor name. * * @return the current cursor name * @throws SQLException if a database access error occurs */ public @Nullable String getCursorName() throws SQLException { checkClosed(); return null; } /** * <p>We are required to bring back certain information by the DatabaseMetaData class. These * functions do that.</p> * * <p>Method getURL() brings back the URL (good job we saved it)</p> * * @return the url * @throws SQLException just in case... */ public String getURL() throws SQLException { return creatingURL; } /** * Method getUserName() brings back the User Name (again, we saved it). * * @return the user name * @throws SQLException just in case... */ public String getUserName() throws SQLException { return queryExecutor.getUser(); } public Fastpath getFastpathAPI() throws SQLException { checkClosed(); if (fastpath == null) { fastpath = new Fastpath(this); } return fastpath; } // This holds a reference to the Fastpath API if already open private @Nullable Fastpath fastpath; public LargeObjectManager getLargeObjectAPI() throws SQLException { checkClosed(); if (largeobject == null) { largeobject = new LargeObjectManager(this); } return largeobject; } // This holds a reference to the LargeObject API if already open private @Nullable LargeObjectManager largeobject; /* * This method is used internally to return an object based around org.postgresql's more unique * data types. * * <p>It uses an internal HashMap to get the handling class. If the type is not supported, then an * instance of org.postgresql.util.PGobject is returned. * * You can use the getValue() or setValue() methods to handle the returned object. Custom objects * can have their own methods. * * @return PGobject for this type, and set to value * * @exception SQLException if value is not correct for this type */ @Override public Object getObject(String type, @Nullable String value, byte @Nullable [] byteValue) throws SQLException { if (typemap != null) { Class<?> c = typemap.get(type); if (c != null) { // Handle the type (requires SQLInput & SQLOutput classes to be implemented) throw new PSQLException(GT.tr("Custom type maps are not supported."), PSQLState.NOT_IMPLEMENTED); } } PGobject obj = null; if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "Constructing object from type={0} value=<{1}>", new Object[]{type, value}); } try { Class<? extends PGobject> klass = typeCache.getPGobject(type); // If className is not null, then try to instantiate it, // It must be basetype PGobject // This is used to implement the org.postgresql unique types (like lseg, // point, etc). if (klass != null) { obj = klass.newInstance(); obj.setType(type); if (byteValue != null && obj instanceof PGBinaryObject) { PGBinaryObject binObj = (PGBinaryObject) obj; binObj.setByteValue(byteValue, 0); } else { obj.setValue(value); } } else { // If className is null, then the type is unknown. // so return a PGobject with the type set, and the value set obj = new PGobject(); obj.setType(type); obj.setValue(value); } return obj; } catch (SQLException sx) { // rethrow the exception. Done because we capture any others next throw sx; } catch (Exception ex) { throw new PSQLException(GT.tr("Failed to create object for: {0}.", type), PSQLState.CONNECTION_FAILURE, ex); } } protected TypeInfo createTypeInfo(BaseConnection conn, int unknownLength) { return new TypeInfoCache(conn, unknownLength); } public TypeInfo getTypeInfo() { return typeCache; } @Override public void addDataType(String type, String name) { try { addDataType(type, Class.forName(name).asSubclass(PGobject.class)); } catch (Exception e) { throw new RuntimeException("Cannot register new type: " + e); } } @Override public void addDataType(String type, Class<? extends PGobject> klass) throws SQLException { checkClosed(); typeCache.addDataType(type, klass); } // This initialises the objectTypes hash map private void initObjectTypes(Properties info) throws SQLException { // Add in the types that come packaged with the driver. // These can be overridden later if desired. addDataType("box", org.postgresql.geometric.PGbox.class); addDataType("circle", org.postgresql.geometric.PGcircle.class); addDataType("line", org.postgresql.geometric.PGline.class); addDataType("lseg", org.postgresql.geometric.PGlseg.class); addDataType("path", org.postgresql.geometric.PGpath.class); addDataType("point", org.postgresql.geometric.PGpoint.class); addDataType("polygon", org.postgresql.geometric.PGpolygon.class); addDataType("money", org.postgresql.util.PGmoney.class); addDataType("interval", org.postgresql.util.PGInterval.class); Enumeration<?> e = info.propertyNames(); while (e.hasMoreElements()) { String propertyName = (String) e.nextElement(); if (propertyName != null && propertyName.startsWith("datatype.")) { String typeName = propertyName.substring(9); String className = castNonNull(info.getProperty(propertyName)); Class<?> klass; try { klass = Class.forName(className); } catch (ClassNotFoundException cnfe) { throw new PSQLException( GT.tr("Unable to load the class {0} responsible for the datatype {1}", className, typeName), PSQLState.SYSTEM_ERROR, cnfe); } addDataType(typeName, klass.asSubclass(PGobject.class)); } } } /** * <B>Note:</B> even though {@code Statement} is automatically closed when it is garbage * collected, it is better to close it explicitly to lower resource consumption. * * {@inheritDoc} */ @Override public void close() throws SQLException { if (queryExecutor == null) { // This might happen in case constructor throws an exception (e.g. host being not available). // When that happens the connection is still registered in the finalizer queue, so it gets finalized return; } releaseTimer(); queryExecutor.close(); openStackTrace = null; } @Override public String nativeSQL(String sql) throws SQLException { checkClosed(); CachedQuery cachedQuery = queryExecutor.createQuery(sql, false, true); return cachedQuery.query.getNativeSql(); } @Override public synchronized @Nullable SQLWarning getWarnings() throws SQLException { checkClosed(); SQLWarning newWarnings = queryExecutor.getWarnings(); // NB: also clears them. if (firstWarning == null) { firstWarning = newWarnings; } else if (newWarnings != null) { firstWarning.setNextWarning(newWarnings); // Chain them on. } return firstWarning; } @Override public synchronized void clearWarnings() throws SQLException { checkClosed(); //noinspection ThrowableNotThrown queryExecutor.getWarnings(); // Clear and discard. firstWarning = null; } @Override public void setReadOnly(boolean readOnly) throws SQLException { checkClosed(); if (queryExecutor.getTransactionState() != TransactionState.IDLE) { throw new PSQLException( GT.tr("Cannot change transaction read-only property in the middle of a transaction."), PSQLState.ACTIVE_SQL_TRANSACTION); } if (readOnly != this.readOnly && autoCommit && this.readOnlyBehavior == ReadOnlyBehavior.always) { execSQLUpdate(readOnly ? setSessionReadOnly : setSessionNotReadOnly); } this.readOnly = readOnly; LOGGER.log(Level.FINE, " setReadOnly = {0}", readOnly); } @Override public boolean isReadOnly() throws SQLException { checkClosed(); return readOnly; } @Override public boolean hintReadOnly() { return readOnly && readOnlyBehavior != ReadOnlyBehavior.ignore; } @Override public void setAutoCommit(boolean autoCommit) throws SQLException { checkClosed(); if (this.autoCommit == autoCommit) { return; } if (!this.autoCommit) { commit(); } // if the connection is read only, we need to make sure session settings are // correct when autocommit status changed if (this.readOnly && readOnlyBehavior == ReadOnlyBehavior.always) { // if we are turning on autocommit, we need to set session // to read only if (autoCommit) { this.autoCommit = true; execSQLUpdate(setSessionReadOnly); } else { // if we are turning auto commit off, we need to // disable session execSQLUpdate(setSessionNotReadOnly); } } this.autoCommit = autoCommit; LOGGER.log(Level.FINE, " setAutoCommit = {0}", autoCommit); } @Override public boolean getAutoCommit() throws SQLException { checkClosed(); return this.autoCommit; } private void executeTransactionCommand(Query query) throws SQLException { int flags = QueryExecutor.QUERY_NO_METADATA | QueryExecutor.QUERY_NO_RESULTS | QueryExecutor.QUERY_SUPPRESS_BEGIN; if (prepareThreshold == 0) { flags |= QueryExecutor.QUERY_ONESHOT; } try { getQueryExecutor().execute(query, null, new TransactionCommandHandler(), 0, 0, flags); } catch (SQLException e) { // Don't retry composite queries as it might get partially executed if (query.getSubqueries() != null || !queryExecutor.willHealOnRetry(e)) { throw e; } query.close(); // retry getQueryExecutor().execute(query, null, new TransactionCommandHandler(), 0, 0, flags); } } @Override public void commit() throws SQLException { checkClosed(); if (autoCommit) { throw new PSQLException(GT.tr("Cannot commit when autoCommit is enabled."), PSQLState.NO_ACTIVE_SQL_TRANSACTION); } if (queryExecutor.getTransactionState() != TransactionState.IDLE) { executeTransactionCommand(commitQuery); } } protected void checkClosed() throws SQLException { if (isClosed()) { throw new PSQLException(GT.tr("This connection has been closed."), PSQLState.CONNECTION_DOES_NOT_EXIST); } } @Override public void rollback() throws SQLException { checkClosed(); if (autoCommit) { throw new PSQLException(GT.tr("Cannot rollback when autoCommit is enabled."), PSQLState.NO_ACTIVE_SQL_TRANSACTION); } if (queryExecutor.getTransactionState() != TransactionState.IDLE) { executeTransactionCommand(rollbackQuery); } else { // just log for debugging LOGGER.log(Level.FINE, "Rollback requested but no transaction in progress"); } } public TransactionState getTransactionState() { return queryExecutor.getTransactionState(); } public int getTransactionIsolation() throws SQLException { checkClosed(); String level = null; final ResultSet rs = execSQLQuery("SHOW TRANSACTION ISOLATION LEVEL"); // nb: no BEGIN triggered if (rs.next()) { level = rs.getString(1); } rs.close(); // TODO revisit: throw exception instead of silently eating the error in unknown cases? if (level == null) { return Connection.TRANSACTION_READ_COMMITTED; // Best guess. } level = level.toUpperCase(Locale.US); if (level.equals("READ COMMITTED")) { return Connection.TRANSACTION_READ_COMMITTED; } if (level.equals("READ UNCOMMITTED")) { return Connection.TRANSACTION_READ_UNCOMMITTED; } if (level.equals("REPEATABLE READ")) { return Connection.TRANSACTION_REPEATABLE_READ; } if (level.equals("SERIALIZABLE")) { return Connection.TRANSACTION_SERIALIZABLE; } return Connection.TRANSACTION_READ_COMMITTED; // Best guess. } public void setTransactionIsolation(int level) throws SQLException { checkClosed(); if (queryExecutor.getTransactionState() != TransactionState.IDLE) { throw new PSQLException( GT.tr("Cannot change transaction isolation level in the middle of a transaction."), PSQLState.ACTIVE_SQL_TRANSACTION); } String isolationLevelName = getIsolationLevelName(level); if (isolationLevelName == null) { throw new PSQLException(GT.tr("Transaction isolation level {0} not supported.", level), PSQLState.NOT_IMPLEMENTED); } String isolationLevelSQL = "SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL " + isolationLevelName; execSQLUpdate(isolationLevelSQL); // nb: no BEGIN triggered LOGGER.log(Level.FINE, " setTransactionIsolation = {0}", isolationLevelName); } protected @Nullable String getIsolationLevelName(int level) { switch (level) { case Connection.TRANSACTION_READ_COMMITTED: return "READ COMMITTED"; case Connection.TRANSACTION_SERIALIZABLE: return "SERIALIZABLE"; case Connection.TRANSACTION_READ_UNCOMMITTED: return "READ UNCOMMITTED"; case Connection.TRANSACTION_REPEATABLE_READ: return "REPEATABLE READ"; default: return null; } } public void setCatalog(String catalog) throws SQLException { checkClosed(); // no-op } public String getCatalog() throws SQLException { checkClosed(); return queryExecutor.getDatabase(); } public boolean getHideUnprivilegedObjects() { return hideUnprivilegedObjects; } /** * <p>Overrides finalize(). If called, it closes the connection.</p> * * <p>This was done at the request of <a href="mailto:[email protected]">Rachel * Greenham</a> who hit a problem where multiple clients didn't close the connection, and once a * fortnight enough clients were open to kill the postgres server.</p> */ protected void finalize() throws Throwable { try { if (openStackTrace != null) { LOGGER.log(Level.WARNING, GT.tr("Finalizing a Connection that was never closed:"), openStackTrace); } close(); } finally { super.finalize(); } } /** * Get server version number. * * @return server version number */ public String getDBVersionNumber() { return queryExecutor.getServerVersion(); } /** * Get server major version. * * @return server major version */ public int getServerMajorVersion() { try { StringTokenizer versionTokens = new StringTokenizer(queryExecutor.getServerVersion(), "."); // aaXbb.ccYdd return integerPart(versionTokens.nextToken()); // return X } catch (NoSuchElementException e) { return 0; } } /** * Get server minor version. * * @return server minor version */ public int getServerMinorVersion() { try { StringTokenizer versionTokens = new StringTokenizer(queryExecutor.getServerVersion(), "."); // aaXbb.ccYdd versionTokens.nextToken(); // Skip aaXbb return integerPart(versionTokens.nextToken()); // return Y } catch (NoSuchElementException e) { return 0; } } @Override public boolean haveMinimumServerVersion(int ver) { return queryExecutor.getServerVersionNum() >= ver; } @Override public boolean haveMinimumServerVersion(Version ver) { return haveMinimumServerVersion(ver.getVersionNum()); } @Pure @Override public Encoding getEncoding() { return queryExecutor.getEncoding(); } @Override public byte @PolyNull [] encodeString(@PolyNull String str) throws SQLException { try { return getEncoding().encode(str); } catch (IOException ioe) { throw new PSQLException(GT.tr("Unable to translate data into the desired encoding."), PSQLState.DATA_ERROR, ioe); } } @Override public String escapeString(String str) throws SQLException { return Utils.escapeLiteral(null, str, queryExecutor.getStandardConformingStrings()) .toString(); } @Override public boolean getStandardConformingStrings() { return queryExecutor.getStandardConformingStrings(); } // This is a cache of the DatabaseMetaData instance for this connection protected java.sql.@Nullable DatabaseMetaData metadata; @Override public boolean isClosed() throws SQLException { return queryExecutor.isClosed(); } @Override public void cancelQuery() throws SQLException { checkClosed(); queryExecutor.sendQueryCancel(); } @Override public PGNotification[] getNotifications() throws SQLException { return getNotifications(-1); } @Override public PGNotification[] getNotifications(int timeoutMillis) throws SQLException { checkClosed(); getQueryExecutor().processNotifies(timeoutMillis); // Backwards-compatibility hand-holding. PGNotification[] notifications = queryExecutor.getNotifications(); return notifications; } /** * Handler for transaction queries. */ private class TransactionCommandHandler extends ResultHandlerBase { public void handleCompletion() throws SQLException { SQLWarning warning = getWarning(); if (warning != null) { PgConnection.this.addWarning(warning); } super.handleCompletion(); } } public int getPrepareThreshold() { return prepareThreshold; } public void setDefaultFetchSize(int fetchSize) throws SQLException { if (fetchSize < 0) { throw new PSQLException(GT.tr("Fetch size must be a value greater to or equal to 0."), PSQLState.INVALID_PARAMETER_VALUE); } this.defaultFetchSize = fetchSize; LOGGER.log(Level.FINE, " setDefaultFetchSize = {0}", fetchSize); } public int getDefaultFetchSize() { return defaultFetchSize; } public void setPrepareThreshold(int newThreshold) { this.prepareThreshold = newThreshold; LOGGER.log(Level.FINE, " setPrepareThreshold = {0}", newThreshold); } public boolean getForceBinary() { return forcebinary; } public void setForceBinary(boolean newValue) { this.forcebinary = newValue; LOGGER.log(Level.FINE, " setForceBinary = {0}", newValue); } public void setTypeMapImpl(Map<String, Class<?>> map) throws SQLException { typemap = map; } public Logger getLogger() { return LOGGER; } public int getProtocolVersion() { return queryExecutor.getProtocolVersion(); } public boolean getStringVarcharFlag() { return bindStringAsVarchar; } private @Nullable CopyManager copyManager; public CopyManager getCopyAPI() throws SQLException { checkClosed(); if (copyManager == null) { copyManager = new CopyManager(this); } return copyManager; } public boolean binaryTransferSend(int oid) { return queryExecutor.useBinaryForSend(oid); } public int getBackendPID() { return queryExecutor.getBackendPID(); } public boolean isColumnSanitiserDisabled() { return this.disableColumnSanitiser; } public void setDisableColumnSanitiser(boolean disableColumnSanitiser) { this.disableColumnSanitiser = disableColumnSanitiser; LOGGER.log(Level.FINE, " setDisableColumnSanitiser = {0}", disableColumnSanitiser); } @Override public PreferQueryMode getPreferQueryMode() { return queryExecutor.getPreferQueryMode(); } @Override public AutoSave getAutosave() { return queryExecutor.getAutoSave(); } @Override public void setAutosave(AutoSave autoSave) { queryExecutor.setAutoSave(autoSave); LOGGER.log(Level.FINE, " setAutosave = {0}", autoSave.value()); } protected void abort() { queryExecutor.abort(); } private synchronized Timer getTimer() { if (cancelTimer == null) { cancelTimer = Driver.getSharedTimer().getTimer(); } return cancelTimer; } private synchronized void releaseTimer() { if (cancelTimer != null) { cancelTimer = null; Driver.getSharedTimer().releaseTimer(); } } @Override public void addTimerTask(TimerTask timerTask, long milliSeconds) { Timer timer = getTimer(); timer.schedule(timerTask, milliSeconds); } @Override public void purgeTimerTasks() { Timer timer = cancelTimer; if (timer != null) { timer.purge(); } } @Override public String escapeIdentifier(String identifier) throws SQLException { return Utils.escapeIdentifier(null, identifier).toString(); } @Override public String escapeLiteral(String literal) throws SQLException { return Utils.escapeLiteral(null, literal, queryExecutor.getStandardConformingStrings()) .toString(); } @Override public LruCache<FieldMetadata.Key, FieldMetadata> getFieldMetadataCache() { return fieldMetadataCache; } @Override public PGReplicationConnection getReplicationAPI() { return new PGReplicationConnectionImpl(this); } // Parse a "dirty" integer surrounded by non-numeric characters private static int integerPart(String dirtyString) { int start = 0; while (start < dirtyString.length() && !Character.isDigit(dirtyString.charAt(start))) { ++start; } int end = start; while (end < dirtyString.length() && Character.isDigit(dirtyString.charAt(end))) { ++end; } if (start == end) { return 0; } return Integer.parseInt(dirtyString.substring(start, end)); } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkClosed(); return new PgStatement(this, resultSetType, resultSetConcurrency, resultSetHoldability); } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkClosed(); return new PgPreparedStatement(this, sql, resultSetType, resultSetConcurrency, resultSetHoldability); } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkClosed(); return new PgCallableStatement(this, sql, resultSetType, resultSetConcurrency, resultSetHoldability); } @Override public DatabaseMetaData getMetaData() throws SQLException { checkClosed(); if (metadata == null) { metadata = new PgDatabaseMetaData(this); } return metadata; } @Override public void setTypeMap(Map<String, Class<?>> map) throws SQLException { setTypeMapImpl(map); LOGGER.log(Level.FINE, " setTypeMap = {0}", map); } protected Array makeArray(int oid, @Nullable String fieldString) throws SQLException { return new PgArray(this, oid, fieldString); } protected Blob makeBlob(long oid) throws SQLException { return new PgBlob(this, oid); } protected Clob makeClob(long oid) throws SQLException { return new PgClob(this, oid); } protected SQLXML makeSQLXML() throws SQLException { return new PgSQLXML(this); } @Override public Clob createClob() throws SQLException { checkClosed(); throw org.postgresql.Driver.notImplemented(this.getClass(), "createClob()"); } @Override public Blob createBlob() throws SQLException { checkClosed(); throw org.postgresql.Driver.notImplemented(this.getClass(), "createBlob()"); } @Override public NClob createNClob() throws SQLException { checkClosed(); throw org.postgresql.Driver.notImplemented(this.getClass(), "createNClob()"); } @Override public SQLXML createSQLXML() throws SQLException { checkClosed(); return makeSQLXML(); } @Override public Struct createStruct(String typeName, Object[] attributes) throws SQLException { checkClosed(); throw org.postgresql.Driver.notImplemented(this.getClass(), "createStruct(String, Object[])"); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public Array createArrayOf(String typeName, @Nullable Object elements) throws SQLException { checkClosed(); final TypeInfo typeInfo = getTypeInfo(); final int oid = typeInfo.getPGArrayType(typeName); final char delim = typeInfo.getArrayDelimiter(oid); if (oid == Oid.UNSPECIFIED) { throw new PSQLException(GT.tr("Unable to find server array type for provided name {0}.", typeName), PSQLState.INVALID_NAME); } if (elements == null) { return makeArray(oid, null); } final ArrayEncoding.ArrayEncoder arraySupport = ArrayEncoding.getArrayEncoder(elements); if (arraySupport.supportBinaryRepresentation(oid) && getPreferQueryMode() != PreferQueryMode.SIMPLE) { return new PgArray(this, oid, arraySupport.toBinaryRepresentation(this, elements, oid)); } final String arrayString = arraySupport.toArrayString(delim, elements); return makeArray(oid, arrayString); } @Override public Array createArrayOf(String typeName, @Nullable Object @Nullable [] elements) throws SQLException { return createArrayOf(typeName, (Object) elements); } @Override public boolean isValid(int timeout) throws SQLException { if (timeout < 0) { throw new PSQLException(GT.tr("Invalid timeout ({0}<0).", timeout), PSQLState.INVALID_PARAMETER_VALUE); } if (isClosed()) { return false; } boolean changedNetworkTimeout = false; try { int oldNetworkTimeout = getNetworkTimeout(); int newNetworkTimeout = (int) Math.min(timeout * 1000L, Integer.MAX_VALUE); try { // change network timeout only if the new value is less than the current // (zero means infinite timeout) if (newNetworkTimeout != 0 && (oldNetworkTimeout == 0 || newNetworkTimeout < oldNetworkTimeout)) { changedNetworkTimeout = true; setNetworkTimeout(null, newNetworkTimeout); } if (replicationConnection) { Statement statement = createStatement(); statement.execute("IDENTIFY_SYSTEM"); statement.close(); } else { if (checkConnectionQuery == null) { checkConnectionQuery = prepareStatement(""); } checkConnectionQuery.executeUpdate(); } return true; } finally { if (changedNetworkTimeout) { setNetworkTimeout(null, oldNetworkTimeout); } } } catch (SQLException e) { if (PSQLState.IN_FAILED_SQL_TRANSACTION.getState().equals(e.getSQLState())) { // "current transaction aborted", assume the connection is up and running return true; } LOGGER.log(Level.FINE, GT.tr("Validating connection."), e); } return false; } @Override public void setClientInfo(String name, @Nullable String value) throws SQLClientInfoException { try { checkClosed(); } catch (final SQLException cause) { Map<String, ClientInfoStatus> failures = new HashMap<String, ClientInfoStatus>(); failures.put(name, ClientInfoStatus.REASON_UNKNOWN); throw new SQLClientInfoException(GT.tr("This connection has been closed."), failures, cause); } if (haveMinimumServerVersion(ServerVersion.v9_0) && "ApplicationName".equals(name)) { if (value == null) { value = ""; } final String oldValue = queryExecutor.getApplicationName(); if (value.equals(oldValue)) { return; } try { StringBuilder sql = new StringBuilder("SET application_name = '"); Utils.escapeLiteral(sql, value, getStandardConformingStrings()); sql.append("'"); execSQLUpdate(sql.toString()); } catch (SQLException sqle) { Map<String, ClientInfoStatus> failures = new HashMap<String, ClientInfoStatus>(); failures.put(name, ClientInfoStatus.REASON_UNKNOWN); throw new SQLClientInfoException( GT.tr("Failed to set ClientInfo property: {0}", "ApplicationName"), sqle.getSQLState(), failures, sqle); } if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, " setClientInfo = {0} {1}", new Object[]{name, value}); } clientInfo.put(name, value); return; } addWarning(new SQLWarning(GT.tr("ClientInfo property not supported."), PSQLState.NOT_IMPLEMENTED.getState())); } @Override public void setClientInfo(Properties properties) throws SQLClientInfoException { try { checkClosed(); } catch (final SQLException cause) { Map<String, ClientInfoStatus> failures = new HashMap<String, ClientInfoStatus>(); for (Map.Entry<Object, Object> e : properties.entrySet()) { failures.put((String) e.getKey(), ClientInfoStatus.REASON_UNKNOWN); } throw new SQLClientInfoException(GT.tr("This connection has been closed."), failures, cause); } Map<String, ClientInfoStatus> failures = new HashMap<String, ClientInfoStatus>(); for (String name : new String[]{"ApplicationName"}) { try { setClientInfo(name, properties.getProperty(name, null)); } catch (SQLClientInfoException e) { failures.putAll(e.getFailedProperties()); } } if (!failures.isEmpty()) { throw new SQLClientInfoException(GT.tr("One or more ClientInfo failed."), PSQLState.NOT_IMPLEMENTED.getState(), failures); } } @Override public @Nullable String getClientInfo(String name) throws SQLException { checkClosed(); clientInfo.put("ApplicationName", queryExecutor.getApplicationName()); return clientInfo.getProperty(name); } @Override public Properties getClientInfo() throws SQLException { checkClosed(); clientInfo.put("ApplicationName", queryExecutor.getApplicationName()); return clientInfo; } public <T> T createQueryObject(Class<T> ifc) throws SQLException { checkClosed(); throw org.postgresql.Driver.notImplemented(this.getClass(), "createQueryObject(Class<T>)"); } public boolean getLogServerErrorDetail() { return logServerErrorDetail; } @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { checkClosed(); return iface.isAssignableFrom(getClass()); } @Override public <T> T unwrap(Class<T> iface) throws SQLException { checkClosed(); if (iface.isAssignableFrom(getClass())) { return iface.cast(this); } throw new SQLException("Cannot unwrap to " + iface.getName()); } public @Nullable String getSchema() throws SQLException { checkClosed(); Statement stmt = createStatement(); try { ResultSet rs = stmt.executeQuery("select current_schema()"); try { if (!rs.next()) { return null; // Is it ever possible? } return rs.getString(1); } finally { rs.close(); } } finally { stmt.close(); } } public void setSchema(@Nullable String schema) throws SQLException { checkClosed(); Statement stmt = createStatement(); try { if (schema == null) { stmt.executeUpdate("SET SESSION search_path TO DEFAULT"); } else { StringBuilder sb = new StringBuilder(); sb.append("SET SESSION search_path TO '"); Utils.escapeLiteral(sb, schema, getStandardConformingStrings()); sb.append("'"); stmt.executeUpdate(sb.toString()); LOGGER.log(Level.FINE, " setSchema = {0}", schema); } } finally { stmt.close(); } } public class AbortCommand implements Runnable { public void run() { abort(); } } public void abort(Executor executor) throws SQLException { if (executor == null) { throw new SQLException("executor is null"); } if (isClosed()) { return; } SQL_PERMISSION_ABORT.checkGuard(this); AbortCommand command = new AbortCommand(); executor.execute(command); } public void setNetworkTimeout(@Nullable Executor executor /*not used*/, int milliseconds) throws SQLException { checkClosed(); if (milliseconds < 0) { throw new PSQLException(GT.tr("Network timeout must be a value greater than or equal to 0."), PSQLState.INVALID_PARAMETER_VALUE); } SecurityManager securityManager = System.getSecurityManager(); if (securityManager != null) { securityManager.checkPermission(SQL_PERMISSION_NETWORK_TIMEOUT); } try { queryExecutor.setNetworkTimeout(milliseconds); } catch (IOException ioe) { throw new PSQLException(GT.tr("Unable to set network timeout."), PSQLState.COMMUNICATION_ERROR, ioe); } } public int getNetworkTimeout() throws SQLException { checkClosed(); try { return queryExecutor.getNetworkTimeout(); } catch (IOException ioe) { throw new PSQLException(GT.tr("Unable to get network timeout."), PSQLState.COMMUNICATION_ERROR, ioe); } } @Override public void setHoldability(int holdability) throws SQLException { checkClosed(); switch (holdability) { case ResultSet.CLOSE_CURSORS_AT_COMMIT: rsHoldability = holdability; break; case ResultSet.HOLD_CURSORS_OVER_COMMIT: rsHoldability = holdability; break; default: throw new PSQLException(GT.tr("Unknown ResultSet holdability setting: {0}.", holdability), PSQLState.INVALID_PARAMETER_VALUE); } LOGGER.log(Level.FINE, " setHoldability = {0}", holdability); } @Override public int getHoldability() throws SQLException { checkClosed(); return rsHoldability; } @Override public Savepoint setSavepoint() throws SQLException { checkClosed(); String pgName; if (getAutoCommit()) { throw new PSQLException(GT.tr("Cannot establish a savepoint in auto-commit mode."), PSQLState.NO_ACTIVE_SQL_TRANSACTION); } PSQLSavepoint savepoint = new PSQLSavepoint(savepointId++); pgName = savepoint.getPGName(); // Note we can't use execSQLUpdate because we don't want // to suppress BEGIN. Statement stmt = createStatement(); stmt.executeUpdate("SAVEPOINT " + pgName); stmt.close(); return savepoint; } @Override public Savepoint setSavepoint(String name) throws SQLException { checkClosed(); if (getAutoCommit()) { throw new PSQLException(GT.tr("Cannot establish a savepoint in auto-commit mode."), PSQLState.NO_ACTIVE_SQL_TRANSACTION); } PSQLSavepoint savepoint = new PSQLSavepoint(name); // Note we can't use execSQLUpdate because we don't want // to suppress BEGIN. Statement stmt = createStatement(); stmt.executeUpdate("SAVEPOINT " + savepoint.getPGName()); stmt.close(); return savepoint; } @Override public void rollback(Savepoint savepoint) throws SQLException { checkClosed(); PSQLSavepoint pgSavepoint = (PSQLSavepoint) savepoint; execSQLUpdate("ROLLBACK TO SAVEPOINT " + pgSavepoint.getPGName()); } @Override public void releaseSavepoint(Savepoint savepoint) throws SQLException { checkClosed(); PSQLSavepoint pgSavepoint = (PSQLSavepoint) savepoint; execSQLUpdate("RELEASE SAVEPOINT " + pgSavepoint.getPGName()); pgSavepoint.invalidate(); } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { checkClosed(); return createStatement(resultSetType, resultSetConcurrency, getHoldability()); } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { checkClosed(); return prepareStatement(sql, resultSetType, resultSetConcurrency, getHoldability()); } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { checkClosed(); return prepareCall(sql, resultSetType, resultSetConcurrency, getHoldability()); } @Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { if (autoGeneratedKeys != Statement.RETURN_GENERATED_KEYS) { return prepareStatement(sql); } return prepareStatement(sql, (String[]) null); } @Override public PreparedStatement prepareStatement(String sql, int @Nullable [] columnIndexes) throws SQLException { if (columnIndexes != null && columnIndexes.length == 0) { return prepareStatement(sql); } checkClosed(); throw new PSQLException(GT.tr("Returning autogenerated keys is not supported."), PSQLState.NOT_IMPLEMENTED); } @Override public PreparedStatement prepareStatement(String sql, String @Nullable[] columnNames) throws SQLException { if (columnNames != null && columnNames.length == 0) { return prepareStatement(sql); } CachedQuery cachedQuery = borrowReturningQuery(sql, columnNames); PgPreparedStatement ps = new PgPreparedStatement(this, cachedQuery, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, getHoldability()); Query query = cachedQuery.query; SqlCommand sqlCommand = query.getSqlCommand(); if (sqlCommand != null) { ps.wantsGeneratedKeysAlways = sqlCommand.isReturningKeywordPresent(); } else { // If composite query is given, just ignore "generated keys" arguments } return ps; } @Override public final Map<String,String> getParameterStatuses() { return queryExecutor.getParameterStatuses(); } @Override public final @Nullable String getParameterStatus(String parameterName) { return queryExecutor.getParameterStatus(parameterName); } @Override public boolean getAdaptiveFetch() { return queryExecutor.getAdaptiveFetch(); } @Override public void setAdaptiveFetch(boolean adaptiveFetch) { queryExecutor.setAdaptiveFetch(adaptiveFetch); } @Override public PGXmlFactoryFactory getXmlFactoryFactory() throws SQLException { PGXmlFactoryFactory xmlFactoryFactory = this.xmlFactoryFactory; if (xmlFactoryFactory != null) { return xmlFactoryFactory; } if (xmlFactoryFactoryClass == null || xmlFactoryFactoryClass.equals("")) { xmlFactoryFactory = DefaultPGXmlFactoryFactory.INSTANCE; } else if (xmlFactoryFactoryClass.equals("LEGACY_INSECURE")) { xmlFactoryFactory = LegacyInsecurePGXmlFactoryFactory.INSTANCE; } else { Class<?> clazz; try { clazz = Class.forName(xmlFactoryFactoryClass); } catch (ClassNotFoundException ex) { throw new PSQLException( GT.tr("Could not instantiate xmlFactoryFactory: {0}", xmlFactoryFactoryClass), PSQLState.INVALID_PARAMETER_VALUE, ex); } if (!clazz.isAssignableFrom(PGXmlFactoryFactory.class)) { throw new PSQLException( GT.tr("Connection property xmlFactoryFactory must implement PGXmlFactoryFactory: {0}", xmlFactoryFactoryClass), PSQLState.INVALID_PARAMETER_VALUE); } try { xmlFactoryFactory = (PGXmlFactoryFactory) clazz.newInstance(); } catch (Exception ex) { throw new PSQLException( GT.tr("Could not instantiate xmlFactoryFactory: {0}", xmlFactoryFactoryClass), PSQLState.INVALID_PARAMETER_VALUE, ex); } } this.xmlFactoryFactory = xmlFactoryFactory; return xmlFactoryFactory; } }
fix Issue #2300. The spec says that calling close() on a closed connection is a noop. (#2345) * fix Issue #2300. The spec says that calling close() on a closed connection is a noop.
pgjdbc/src/main/java/org/postgresql/jdbc/PgConnection.java
fix Issue #2300. The spec says that calling close() on a closed connection is a noop. (#2345)
Java
mit
23db875128b6b1010549b616020ba3fb1b31c778
0
albertoruibal/gwt_android_emu,albertoruibal/gwt_android_emu,albertoruibal/gwt_android_emu
package android.utils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; public class GenerateResources { private static String FILE_HEADER = "/** FILE GENERATED AUTOMATICALLY BY GWT_ANDROID_EMU'S GenerateResources: DO NOT EDIT MANUALLY */\n"; private Pattern idsPattern = Pattern.compile(".*@" + Pattern.quote("+") + "id/([a-zA-Z0-9_]+).*"); private Pattern langPattern = Pattern.compile(".*/values-([a-zA-Z]{2})/.*"); private Pattern layoutPattern = Pattern.compile(".*public [a-zA-Z0-9_]+ ([a-zA-Z0-9_]+)" + Pattern.quote("(") + Pattern.quote(")") + ".*"); String packageName; ArrayList<String> idsInClass = new ArrayList<String>(); StringBuffer menuClassSB = new StringBuffer(); ArrayList<String> menuIdsInClass = new ArrayList<String>(); HashMap<String, StringBuffer> stringPropertiesSBMap = new HashMap<String, StringBuffer>(); ArrayList<String> stringIdsInClass = new ArrayList<String>(); StringBuffer stringClassSB = new StringBuffer(); HashMap<String, StringBuffer> arrayPropertiesSBMap = new HashMap<String, StringBuffer>(); ArrayList<String> arrayIdsInClass = new ArrayList<String>(); StringBuffer arrayClassSB = new StringBuffer(); ArrayList<String> layouts = new ArrayList<String>(); public GenerateResources(String packageName) { this.packageName = packageName; menuClassSB.append(FILE_HEADER + "package " + packageName + ";\n\nimport android.view.Menu;\nimport android.view.MenuItem;\n\npublic class Menus {\n"); stringClassSB.append(FILE_HEADER + "package " + packageName + ";\n\nimport com.google.gwt.i18n.client.Constants;\n\npublic interface Strings extends Constants {\n"); arrayClassSB.append(FILE_HEADER + "package " + packageName + ";\n\nimport com.google.gwt.i18n.client.Constants;\n\npublic interface Arrays extends Constants {\n"); } public void getIdsFromFile(String fileName) { System.out.println("Getting Ids from file " + fileName + "..."); try { File file = new File(fileName); BufferedReader br = new BufferedReader(new FileReader(file)); String line; while ((line = br.readLine()) != null) { Matcher matcher = idsPattern.matcher(line); String id; while (matcher.find()) { id = matcher.group(1); boolean found = false; for (String s : idsInClass) { if (s.equals(id)) { found = true; break; } } if (!found) { System.out.println("Adding id " + id); idsInClass.add(id); } } } br.close(); } catch (Exception e) { e.printStackTrace(); } } public void processLangFile(String fileName) { Matcher matcher = langPattern.matcher(fileName); String lang = null; if (matcher.find()) { lang = matcher.group(1); } System.out.println("Processing file " + fileName + "(lang " + lang + ")..."); if (!stringPropertiesSBMap.containsKey(lang)) { stringPropertiesSBMap.put(lang, new StringBuffer()); } StringBuffer stringPropertiesSB = stringPropertiesSBMap.get(lang); if (!arrayPropertiesSBMap.containsKey(lang)) { arrayPropertiesSBMap.put(lang, new StringBuffer()); } StringBuffer arrayPropertiesSB = arrayPropertiesSBMap.get(lang); try { File xmlFile = new File(fileName); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(xmlFile); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("string"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; String key = eElement.getAttribute("name"); String value = eElement.getTextContent(); stringPropertiesSB.append(key).append(" = ").append(value).append("\n"); // Avoids duplicated class methods in multi-language if (!stringIdsInClass.contains(key)) { stringClassSB.append("\tString ").append(key).append("();\n"); stringIdsInClass.add(key); } } } NodeList stringArrays = doc.getElementsByTagName("string-array"); for (int i = 0; i < stringArrays.getLength(); i++) { if (stringArrays.item(i).getNodeType() == Node.ELEMENT_NODE) { String key = ((Element) stringArrays.item(i)).getAttribute("name"); StringBuffer valueSb = new StringBuffer(); NodeList stringArraysItems = stringArrays.item(i).getChildNodes(); for (int j = 0; j < stringArraysItems.getLength(); j++) { if (stringArraysItems.item(j).getNodeType() == Node.ELEMENT_NODE) { if (valueSb.length() != 0) { valueSb.append(", "); } valueSb.append(stringArraysItems.item(j).getTextContent().replace(",", "\\\\,")); } } arrayPropertiesSB.append(key).append(" = ").append(valueSb.toString()).append("\n"); // Avoids duplicated class methods in multi-language if (!arrayIdsInClass.contains(key)) { arrayClassSB.append("\tString[] ").append(key).append("();\n"); arrayIdsInClass.add(key); } } } } catch (Exception e) { e.printStackTrace(); } } public void processMenuFile(String fileName) { try { File xmlFile = new File(fileName); System.out.println("Processing MENU file " + fileName + "..."); System.out.println("File name: " + xmlFile.getName()); String menuName = xmlFile.getName().replace(".xml", ""); menuIdsInClass.add(menuName); menuClassSB.append("\tpublic static Menu " + menuName + "() {\n"); menuClassSB.append("\t\tMenu menu = new Menu();\n"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(xmlFile); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("item"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; int groupId = 0; String itemId = "0"; int order = 0; String title = "0"; if (eElement.hasAttribute("android:id")) { itemId = "R.id." + eElement.getAttribute("android:id").replace("@id/", "").replace("@+id/", ""); } if (eElement.hasAttribute("android:title")) { title = "R.string." + eElement.getAttribute("android:title").replace("@string/", ""); } menuClassSB.append("\t\tMenuItem item" + temp + " = menu.add(" + groupId + ", " + itemId + ", " + order + ", " + title + ");\n"); } } } catch (Exception e) { e.printStackTrace(); } menuClassSB.append("\t\treturn menu;\n"); menuClassSB.append("\t}\n"); } public void getLayoutsFromJavaFile(String fileName) { System.out.println("Getting Layouts from file " + fileName + "..."); try { File javaFile = new File(fileName); BufferedReader br = new BufferedReader(new FileReader(javaFile)); String line; while ((line = br.readLine()) != null) { Matcher matcher = layoutPattern.matcher(line); if (matcher.find()) { layouts.add(matcher.group(1)); } } br.close(); } catch (Exception e) { e.printStackTrace(); } } private void writeFile(String fileName, StringBuffer sb) { File file = new File(fileName); if (file.exists()) { file.delete(); } try { file.createNewFile(); FileWriter fos = new FileWriter(file); fos.append(sb.toString()); fos.close(); } catch (IOException e) { e.printStackTrace(); } } public void output() { StringBuffer idsSB = new StringBuffer(); StringBuffer menuIdsSB = new StringBuffer(); StringBuffer stringIdsSB = new StringBuffer(); StringBuffer arrayIdsSB = new StringBuffer(); StringBuffer layoutIdsSB = new StringBuffer(); StringBuffer idResolverSB = new StringBuffer(); StringBuffer menuIdResolverSB = new StringBuffer(); StringBuffer stringIdResolverSB = new StringBuffer(); StringBuffer arrayIdResolverSB = new StringBuffer(); StringBuffer layoutIdResolverSB = new StringBuffer(); int counter; // IDS counter = 1; for (String str : idsInClass) { idResolverSB.append("\t\t\tcase R.id." + str + ":\n\t\t\t\t\treturn \"" + str + "\";\n"); idsSB.append("\t\tpublic final static int " + str + " = " + counter++ + ";\n"); } // MENUS for (String str : menuIdsInClass) { menuIdResolverSB.append("\t\t\tcase R.menu." + str + ":\n\t\t\t\t\treturn Menus." + str + "();\n"); menuIdsSB.append("\t\tpublic final static int " + str + " = " + counter++ + ";\n"); } menuClassSB.append("}\n"); writeFile("Menus.java", menuClassSB); // STRING IDS counter = 1; for (String str : stringIdsInClass) { stringIdResolverSB.append("\t\t\tcase R.string." + str + ":\n\t\t\t\treturn strings." + str + "();\n"); stringIdsSB.append("\t\tpublic final static int " + str + " = " + counter++ + ";\n"); } // ARRAY IDS counter = 1; for (String str : arrayIdsInClass) { arrayIdResolverSB.append("\t\t\tcase R.array." + str + ":\n\t\t\t\treturn arrays." + str + "();\n"); arrayIdsSB.append("\t\tpublic final static int " + str + " = " + counter++ + ";\n"); } // STRINGS & ARRAYS stringClassSB.append("}\n"); arrayClassSB.append("}\n"); writeFile("Strings.java", stringClassSB); writeFile("Arrays.java", arrayClassSB); for (String lang : stringPropertiesSBMap.keySet()) { if (lang == null) { writeFile("Strings.properties", stringPropertiesSBMap.get(lang)); writeFile("Arrays.properties", arrayPropertiesSBMap.get(lang)); } else { writeFile("Strings_" + lang + ".properties", stringPropertiesSBMap.get(lang)); writeFile("Arrays_" + lang + ".properties", arrayPropertiesSBMap.get(lang)); } } // LAYOUT IDS counter = 1; for (String str : layouts) { layoutIdResolverSB.append("\t\t\tcase R.layout." + str + ":\n\t\t\t\treturn layouts." + str + "();\n"); layoutIdsSB.append("\t\tpublic final static int " + str + " = " + counter++ + ";\n"); } // Finally write the "R" class StringBuffer RSB = new StringBuffer(); RSB.append(FILE_HEADER); RSB.append("package " + packageName + ";\n\n"); RSB.append("import android.content.res.Resources;\n"); RSB.append("\n"); RSB.append("public class R {\n"); RSB.append("\tpublic static final class id {\n"); RSB.append(idsSB); RSB.append("\t}\n"); RSB.append("\tpublic static final class string {\n"); RSB.append(stringIdsSB); RSB.append("\t}\n"); RSB.append("\tpublic static final class array {\n"); RSB.append(arrayIdsSB); RSB.append("\t}\n"); RSB.append("\tpublic static final class menu {\n"); RSB.append(menuIdsSB); RSB.append("\t}\n"); RSB.append("\tpublic static final class layout {\n"); RSB.append(layoutIdsSB); RSB.append("\t}\n"); RSB.append("}\n"); writeFile("R.java", RSB); StringBuffer contentResolverSB = new StringBuffer(); contentResolverSB.append(FILE_HEADER); contentResolverSB.append("package " + packageName + ";\n\n"); contentResolverSB.append("import android.content.res.BaseResourceResolver;\n"); contentResolverSB.append("import android.view.Menu;\n"); contentResolverSB.append("import com.google.gwt.core.client.GWT;\n"); contentResolverSB.append("import com.google.gwt.user.client.ui.Widget;\n\n"); contentResolverSB.append("public class ResourceResolver extends BaseResourceResolver {\n\n"); contentResolverSB.append("\tpublic static final Strings strings = GWT.create(Strings.class);\n"); contentResolverSB.append("\tpublic static final Arrays arrays = GWT.create(Arrays.class);\n"); contentResolverSB.append("\tpublic static final Layouts layouts = new Layouts();\n"); // Layout and Raw must be created by user... contentResolverSB.append("\tpublic static final Raw raw = GWT.create(Raw.class);\n"); contentResolverSB.append("\n"); contentResolverSB.append("\tpublic String getIdAsString(int id) {\n"); contentResolverSB.append("\t\tswitch(id) {\n"); contentResolverSB.append(idResolverSB); contentResolverSB.append("\t\t}\n"); contentResolverSB.append("\t\treturn null;\n"); contentResolverSB.append("\t}\n"); contentResolverSB.append("\tpublic String getString(int id) {\n"); contentResolverSB.append("\t\tswitch(id) {\n"); contentResolverSB.append(stringIdResolverSB); contentResolverSB.append("\t\t}\n"); contentResolverSB.append("\t\treturn null;\n"); contentResolverSB.append("\t}\n"); contentResolverSB.append("\tpublic String[] getStringArray(int id) {\n"); contentResolverSB.append("\t\tswitch(id) {\n"); contentResolverSB.append(arrayIdResolverSB); contentResolverSB.append("\t\t}\n"); contentResolverSB.append("\t\treturn null;\n"); contentResolverSB.append("\t}\n"); contentResolverSB.append("\tpublic Menu getMenu(int id) {\n"); contentResolverSB.append("\t\tswitch(id) {\n"); contentResolverSB.append(menuIdResolverSB); contentResolverSB.append("\t\t}\n"); contentResolverSB.append("\t\treturn null;\n"); contentResolverSB.append("\t}\n"); contentResolverSB.append("\tpublic Widget getLayout(int id) {\n"); contentResolverSB.append("\t\tswitch(id) {\n"); contentResolverSB.append(layoutIdResolverSB); contentResolverSB.append("\t\t}\n"); contentResolverSB.append("\t\treturn null;\n"); contentResolverSB.append("\t}\n"); contentResolverSB.append("}\n"); writeFile("ResourceResolver.java", contentResolverSB); } public void crawl(String fileName) { File file = new File(fileName); if (file.isDirectory()) { for (String f : file.list()) { crawl(fileName + "/" + f); } } else { if (fileName.endsWith(".xml")) { if (fileName.contains("/menu/")) { processMenuFile(fileName); } else { processLangFile(fileName); } getIdsFromFile(fileName); } } } public static void main(String args[]) { if (args.length < 2) { System.out.println("GWT Resource generation crawling Android resource directories."); System.out.println("Converts resources from and Android project to a GWT format used by the GWT_android_emu library."); System.out.println("Generates:"); System.out.println(" - R.java: with resource IDs"); System.out.println(" - ContentResolverImpl.java: maps IDs to resources"); System.out.println(" - Strings.java and Strings.properties with language variants"); System.out.println(" - Arrays.java and Arrays.properties"); System.out.println(" - Menus.java"); System.out.println(""); System.out.println("Usage: GenerateResources package_name resource_dir_1 [resource_dir_2] [resource_dir_3] ..."); return; } GenerateResources cs = new GenerateResources(args[0]); for (int i = 1; i < args.length; i++) { cs.crawl(args[i]); } // Get layouts from Layouts.java cs.getLayoutsFromJavaFile("Layouts.java"); cs.output(); } }
androidemu/src/main/java/android/utils/GenerateResources.java
package android.utils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; public class GenerateResources { private static String FILE_HEADER = "/** FILE GENERATED AUTOMATICALLY BY GWT_ANDROID_EMU'S GenerateResources: DO NOT EDIT MANUALLY */\n"; private Pattern idsPattern = Pattern.compile(".*@" + Pattern.quote("+") + "id/([a-zA-Z0-9_]+).*"); private Pattern langPattern = Pattern.compile(".*/values-([a-zA-Z]{2})/.*"); private Pattern layoutPattern = Pattern.compile(".*public [a-zA-Z0-9_]+ ([a-zA-Z0-9_]+)" + Pattern.quote("(") + Pattern.quote(")") + ".*"); String packageName; ArrayList<String> idsInClass = new ArrayList<String>(); StringBuffer menuClassSB = new StringBuffer(); ArrayList<String> menuIdsInClass = new ArrayList<String>(); HashMap<String, StringBuffer> stringPropertiesSBMap = new HashMap<String, StringBuffer>(); ArrayList<String> stringIdsInClass = new ArrayList<String>(); StringBuffer stringClassSB = new StringBuffer(); HashMap<String, StringBuffer> arrayPropertiesSBMap = new HashMap<String, StringBuffer>(); ArrayList<String> arrayIdsInClass = new ArrayList<String>(); StringBuffer arrayClassSB = new StringBuffer(); ArrayList<String> layouts = new ArrayList<String>(); public GenerateResources(String packageName) { this.packageName = packageName; menuClassSB.append(FILE_HEADER + "package " + packageName + ";\n\nimport android.view.Menu;\nimport android.view.MenuItem;\n\npublic class Menus {\n"); stringClassSB.append(FILE_HEADER + "package " + packageName + ";\n\nimport com.google.gwt.i18n.client.Constants;\n\npublic interface Strings extends Constants {\n"); arrayClassSB.append(FILE_HEADER + "package " + packageName + ";\n\nimport com.google.gwt.i18n.client.Constants;\n\npublic interface Arrays extends Constants {\n"); } public void getIdsFromFile(String fileName) { System.out.println("Getting Ids from file " + fileName + ")..."); try { File file = new File(fileName); BufferedReader br = new BufferedReader(new FileReader(file)); String line; while ((line = br.readLine()) != null) { Matcher matcher = idsPattern.matcher(line); String id; while (matcher.find()) { id = matcher.group(1); boolean found = false; for (String s : idsInClass) { if (s.equals(id)) { found = true; break; } } if (!found) { System.out.println("Adding id " + id); idsInClass.add(id); } } } br.close(); } catch (Exception e) { e.printStackTrace(); } } public void processLangFile(String fileName) { Matcher matcher = langPattern.matcher(fileName); String lang = null; if (matcher.find()) { lang = matcher.group(1); } System.out.println("Processing file " + fileName + "(lang " + lang + ")..."); if (!stringPropertiesSBMap.containsKey(lang)) { stringPropertiesSBMap.put(lang, new StringBuffer()); } StringBuffer stringPropertiesSB = stringPropertiesSBMap.get(lang); if (!arrayPropertiesSBMap.containsKey(lang)) { arrayPropertiesSBMap.put(lang, new StringBuffer()); } StringBuffer arrayPropertiesSB = arrayPropertiesSBMap.get(lang); try { File xmlFile = new File(fileName); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(xmlFile); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("string"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; String key = eElement.getAttribute("name"); String value = eElement.getTextContent(); stringPropertiesSB.append(key).append(" = ").append(value).append("\n"); // Avoids duplicated class methods in multi-language if (!stringIdsInClass.contains(key)) { stringClassSB.append("\tString ").append(key).append("();\n"); stringIdsInClass.add(key); } } } NodeList stringArrays = doc.getElementsByTagName("string-array"); for (int i = 0; i < stringArrays.getLength(); i++) { if (stringArrays.item(i).getNodeType() == Node.ELEMENT_NODE) { String key = ((Element) stringArrays.item(i)).getAttribute("name"); StringBuffer valueSb = new StringBuffer(); NodeList stringArraysItems = stringArrays.item(i).getChildNodes(); for (int j = 0; j < stringArraysItems.getLength(); j++) { if (stringArraysItems.item(j).getNodeType() == Node.ELEMENT_NODE) { if (valueSb.length() != 0) { valueSb.append(", "); } valueSb.append(stringArraysItems.item(j).getTextContent().replace(",", "\\\\,")); } } arrayPropertiesSB.append(key).append(" = ").append(valueSb.toString()).append("\n"); // Avoids duplicated class methods in multi-language if (!arrayIdsInClass.contains(key)) { arrayClassSB.append("\tString[] ").append(key).append("();\n"); arrayIdsInClass.add(key); } } } } catch (Exception e) { e.printStackTrace(); } } public void processMenuFile(String fileName) { try { File xmlFile = new File(fileName); System.out.println("Processing MENU file " + fileName + "..."); System.out.println("File name: " + xmlFile.getName()); String menuName = xmlFile.getName().replace(".xml", ""); menuIdsInClass.add(menuName); menuClassSB.append("\tpublic static Menu " + menuName + "() {\n"); menuClassSB.append("\t\tMenu menu = new Menu();\n"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(xmlFile); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("item"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; int groupId = 0; String itemId = "0"; int order = 0; String title = "0"; if (eElement.hasAttribute("android:id")) { itemId = "R.id." + eElement.getAttribute("android:id").replace("@id/", "").replace("@+id/", ""); } if (eElement.hasAttribute("android:title")) { title = "R.string." + eElement.getAttribute("android:title").replace("@string/", ""); } menuClassSB.append("\t\tMenuItem item" + temp + " = menu.add(" + groupId + ", " + itemId + ", " + order + ", " + title + ");\n"); } } } catch (Exception e) { e.printStackTrace(); } menuClassSB.append("\t\treturn menu;\n"); menuClassSB.append("\t}\n"); } public void getLayoutsFromJavaFile(String fileName) { System.out.println("Getting Ids from file " + fileName + ")..."); try { File javaFile = new File(fileName); BufferedReader br = new BufferedReader(new FileReader(javaFile)); String line; while ((line = br.readLine()) != null) { Matcher matcher = layoutPattern.matcher(line); if (matcher.find()) { layouts.add(matcher.group(1)); } } br.close(); } catch (Exception e) { e.printStackTrace(); } } private void writeFile(String fileName, StringBuffer sb) { File file = new File(fileName); if (file.exists()) { file.delete(); } try { file.createNewFile(); FileWriter fos = new FileWriter(file); fos.append(sb.toString()); fos.close(); } catch (IOException e) { e.printStackTrace(); } } public void output() { StringBuffer idsSB = new StringBuffer(); StringBuffer menuIdsSB = new StringBuffer(); StringBuffer stringIdsSB = new StringBuffer(); StringBuffer arrayIdsSB = new StringBuffer(); StringBuffer layoutIdsSB = new StringBuffer(); StringBuffer idResolverSB = new StringBuffer(); StringBuffer menuIdResolverSB = new StringBuffer(); StringBuffer stringIdResolverSB = new StringBuffer(); StringBuffer arrayIdResolverSB = new StringBuffer(); StringBuffer layoutIdResolverSB = new StringBuffer(); int counter; // IDS counter = 1; for (String str : idsInClass) { idResolverSB.append("\t\t\tcase R.id." + str + ":\n\t\t\t\t\treturn \"" + str + "\";\n"); idsSB.append("\t\tpublic final static int " + str + " = " + counter++ + ";\n"); } // MENUS for (String str : menuIdsInClass) { menuIdResolverSB.append("\t\t\tcase R.menu." + str + ":\n\t\t\t\t\treturn Menus." + str + "();\n"); menuIdsSB.append("\t\tpublic final static int " + str + " = " + counter++ + ";\n"); } menuClassSB.append("}\n"); writeFile("Menus.java", menuClassSB); // STRING IDS counter = 1; for (String str : stringIdsInClass) { stringIdResolverSB.append("\t\t\tcase R.string." + str + ":\n\t\t\t\treturn strings." + str + "();\n"); stringIdsSB.append("\t\tpublic final static int " + str + " = " + counter++ + ";\n"); } // ARRAY IDS counter = 1; for (String str : arrayIdsInClass) { arrayIdResolverSB.append("\t\t\tcase R.array." + str + ":\n\t\t\t\treturn arrays." + str + "();\n"); arrayIdsSB.append("\t\tpublic final static int " + str + " = " + counter++ + ";\n"); } // STRINGS & ARRAYS stringClassSB.append("}\n"); arrayClassSB.append("}\n"); writeFile("Strings.java", stringClassSB); writeFile("Arrays.java", arrayClassSB); for (String lang : stringPropertiesSBMap.keySet()) { if (lang == null) { writeFile("Strings.properties", stringPropertiesSBMap.get(lang)); writeFile("Arrays.properties", arrayPropertiesSBMap.get(lang)); } else { writeFile("Strings_" + lang + ".properties", stringPropertiesSBMap.get(lang)); writeFile("Arrays_" + lang + ".properties", arrayPropertiesSBMap.get(lang)); } } // LAYOUT IDS counter = 1; for (String str : layouts) { layoutIdResolverSB.append("\t\t\tcase R.layout." + str + ":\n\t\t\t\treturn layouts." + str + "();\n"); layoutIdsSB.append("\t\tpublic final static int " + str + " = " + counter++ + ";\n"); } // Finally write the "R" class StringBuffer RSB = new StringBuffer(); RSB.append(FILE_HEADER); RSB.append("package " + packageName + ";\n\n"); RSB.append("import android.content.res.Resources;\n"); RSB.append("\n"); RSB.append("public class R {\n"); RSB.append("\tpublic static final class id {\n"); RSB.append(idsSB); RSB.append("\t}\n"); RSB.append("\tpublic static final class string {\n"); RSB.append(stringIdsSB); RSB.append("\t}\n"); RSB.append("\tpublic static final class array {\n"); RSB.append(arrayIdsSB); RSB.append("\t}\n"); RSB.append("\tpublic static final class menu {\n"); RSB.append(menuIdsSB); RSB.append("\t}\n"); RSB.append("\tpublic static final class layout {\n"); RSB.append(layoutIdsSB); RSB.append("\t}\n"); RSB.append("}\n"); writeFile("R.java", RSB); StringBuffer contentResolverSB = new StringBuffer(); contentResolverSB.append(FILE_HEADER); contentResolverSB.append("package " + packageName + ";\n\n"); contentResolverSB.append("import android.content.res.BaseResourceResolver;\n"); contentResolverSB.append("import android.view.Menu;\n"); contentResolverSB.append("import com.google.gwt.core.client.GWT;\n"); contentResolverSB.append("import com.google.gwt.user.client.ui.Widget;\n\n"); contentResolverSB.append("public class ResourceResolver extends BaseResourceResolver {\n\n"); contentResolverSB.append("\tpublic static final Strings strings = GWT.create(Strings.class);\n"); contentResolverSB.append("\tpublic static final Arrays arrays = GWT.create(Arrays.class);\n"); contentResolverSB.append("\tpublic static final Layouts layouts = new Layouts();\n"); // Layout and Raw must be created by user... contentResolverSB.append("\tpublic static final Raw raw = GWT.create(Raw.class);\n"); contentResolverSB.append("\n"); contentResolverSB.append("\tpublic String getIdAsString(int id) {\n"); contentResolverSB.append("\t\tswitch(id) {\n"); contentResolverSB.append(idResolverSB); contentResolverSB.append("\t\t}\n"); contentResolverSB.append("\t\treturn null;\n"); contentResolverSB.append("\t}\n"); contentResolverSB.append("\tpublic String getString(int id) {\n"); contentResolverSB.append("\t\tswitch(id) {\n"); contentResolverSB.append(stringIdResolverSB); contentResolverSB.append("\t\t}\n"); contentResolverSB.append("\t\treturn null;\n"); contentResolverSB.append("\t}\n"); contentResolverSB.append("\tpublic String[] getStringArray(int id) {\n"); contentResolverSB.append("\t\tswitch(id) {\n"); contentResolverSB.append(arrayIdResolverSB); contentResolverSB.append("\t\t}\n"); contentResolverSB.append("\t\treturn null;\n"); contentResolverSB.append("\t}\n"); contentResolverSB.append("\tpublic Menu getMenu(int id) {\n"); contentResolverSB.append("\t\tswitch(id) {\n"); contentResolverSB.append(menuIdResolverSB); contentResolverSB.append("\t\t}\n"); contentResolverSB.append("\t\treturn null;\n"); contentResolverSB.append("\t}\n"); contentResolverSB.append("\tpublic Widget getLayout(int id) {\n"); contentResolverSB.append("\t\tswitch(id) {\n"); contentResolverSB.append(layoutIdResolverSB); contentResolverSB.append("\t\t}\n"); contentResolverSB.append("\t\treturn null;\n"); contentResolverSB.append("\t}\n"); contentResolverSB.append("}\n"); writeFile("ResourceResolver.java", contentResolverSB); } public void crawl(String fileName) { File file = new File(fileName); if (file.isDirectory()) { for (String f : file.list()) { crawl(fileName + "/" + f); } } else { if (fileName.endsWith(".xml")) { if (fileName.contains("/menu/")) { processMenuFile(fileName); } else { processLangFile(fileName); } getIdsFromFile(fileName); } } } public static void main(String args[]) { if (args.length < 2) { System.out.println("GWT Resource generation crawling Android resource directories."); System.out.println("Converts resources from and Android project to a GWT format used by the GWT_android_emu library."); System.out.println("Generates:"); System.out.println(" - R.java: with resource IDs"); System.out.println(" - ContentResolverImpl.java: maps IDs to resources"); System.out.println(" - Strings.java and Strings.properties with language variants"); System.out.println(" - Arrays.java and Arrays.properties"); System.out.println(" - Menus.java"); System.out.println(""); System.out.println("Usage: GenerateResources package_name resource_dir_1 [resource_dir_2] [resource_dir_3] ..."); return; } GenerateResources cs = new GenerateResources(args[0]); for (int i = 1; i < args.length; i++) { cs.crawl(args[i]); } // Get layouts from Layouts.java cs.getLayoutsFromJavaFile("Layouts.java"); cs.output(); } }
Changed some log messages
androidemu/src/main/java/android/utils/GenerateResources.java
Changed some log messages
Java
mit
136bb78b94b302548098e3ee1809c810b3e9e76b
0
ljshj/actor-platform,ljshj/actor-platform,ljshj/actor-platform,ljshj/actor-platform,ljshj/actor-platform,ljshj/actor-platform,ljshj/actor-platform
/* * Copyright (C) 2015 Actor LLC. <https://actor.im> */ package im.actor.core.modules.internal; import java.io.IOException; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.List; import im.actor.core.api.ApiMessageSearchItem; import im.actor.core.api.ApiMessageSearchResult; import im.actor.core.api.ApiPeerSearchResult; import im.actor.core.api.ApiSearchAndCondition; import im.actor.core.api.ApiSearchCondition; import im.actor.core.api.ApiSearchContentType; import im.actor.core.api.ApiSearchPeerCondition; import im.actor.core.api.ApiSearchPeerContentType; import im.actor.core.api.ApiSearchPeerType; import im.actor.core.api.ApiSearchPeerTypeCondition; import im.actor.core.api.ApiSearchPieceText; import im.actor.core.api.rpc.RequestMessageSearch; import im.actor.core.api.rpc.RequestPeerSearch; import im.actor.core.api.rpc.ResponseMessageSearch; import im.actor.core.api.rpc.ResponsePeerSearch; import im.actor.core.entity.Dialog; import im.actor.core.entity.MessageSearchEntity; import im.actor.core.entity.Peer; import im.actor.core.entity.PeerSearchEntity; import im.actor.core.entity.PeerSearchType; import im.actor.core.entity.SearchEntity; import im.actor.core.entity.content.AbsContent; import im.actor.core.modules.AbsModule; import im.actor.core.modules.Modules; import im.actor.core.modules.internal.search.SearchActor; import im.actor.core.network.RpcCallback; import im.actor.core.network.RpcException; import im.actor.core.viewmodel.Command; import im.actor.core.viewmodel.CommandCallback; import im.actor.runtime.Log; import im.actor.runtime.Storage; import im.actor.runtime.actors.ActorCreator; import im.actor.runtime.actors.ActorRef; import im.actor.runtime.actors.Props; import im.actor.runtime.storage.ListEngine; import static im.actor.core.modules.internal.messages.entity.EntityConverter.convert; import static im.actor.runtime.actors.ActorSystem.system; public class SearchModule extends AbsModule { private ListEngine<SearchEntity> searchList; private ActorRef actorRef; public SearchModule(Modules modules) { super(modules); searchList = Storage.createList(STORAGE_SEARCH, SearchEntity.CREATOR); } public void run() { actorRef = system().actorOf(Props.create(SearchActor.class, new ActorCreator<SearchActor>() { @Override public SearchActor create() { return new SearchActor(context()); } }), "actor/search"); } public ListEngine<SearchEntity> getSearchList() { return searchList; } public void onDialogsChanged(List<Dialog> dialogs) { actorRef.send(new SearchActor.OnDialogsUpdated(dialogs)); } public void onContactsChanged(Integer[] contacts) { int[] res = new int[contacts.length]; for (int i = 0; i < res.length; i++) { res[i] = contacts[i]; } actorRef.send(new SearchActor.OnContactsUpdated(res)); } public Command<List<MessageSearchEntity>> findTextMessages(Peer peer, String query) { ArrayList<ApiSearchCondition> conditions = new ArrayList<ApiSearchCondition>(); conditions.add(new ApiSearchPeerCondition(buildApiOutPeer(peer))); conditions.add(new ApiSearchPieceText(query)); return findMessages(new ApiSearchAndCondition(conditions)); } public Command<List<MessageSearchEntity>> findAllDocs(Peer peer) { return findAllContent(peer, ApiSearchContentType.DOCUMENTS); } public Command<List<MessageSearchEntity>> findAllLinks(Peer peer) { return findAllContent(peer, ApiSearchContentType.LINKS); } public Command<List<MessageSearchEntity>> findAllPhotos(Peer peer) { return findAllContent(peer, ApiSearchContentType.PHOTOS); } private Command<List<MessageSearchEntity>> findAllContent(Peer peer, ApiSearchContentType contentType) { ArrayList<ApiSearchCondition> conditions = new ArrayList<>(); conditions.add(new ApiSearchPeerCondition(buildApiOutPeer(peer))); conditions.add(new ApiSearchPeerContentType(contentType)); return findMessages(new ApiSearchAndCondition(conditions)); } private Command<List<MessageSearchEntity>> findMessages(final ApiSearchCondition condition) { return new Command<List<MessageSearchEntity>>() { @Override public void start(final CommandCallback<List<MessageSearchEntity>> callback) { request(new RequestMessageSearch(condition), new RpcCallback<ResponseMessageSearch>() { @Override public void onResult(final ResponseMessageSearch response) { updates().executeRelatedResponse(response.getUsers(), response.getGroups(), new Runnable() { @Override public void run() { final ArrayList<MessageSearchEntity> res = new ArrayList<MessageSearchEntity>(); for (ApiMessageSearchItem r : response.getSearchResults()) { ApiMessageSearchResult itm = r.getResult(); try { res.add(new MessageSearchEntity( convert(itm.getPeer()), itm.getRid(), itm.getDate(), itm.getSenderId(), AbsContent.fromMessage(itm.getContent()))); } catch (IOException e) { e.printStackTrace(); } } runOnUiThread(new Runnable() { @Override public void run() { callback.onResult(res); } }); } }); } @Override public void onError(final RpcException e) { runOnUiThread(new Runnable() { @Override public void run() { callback.onError(e); } }); } }); } }; } public Command<List<PeerSearchEntity>> findPeers(final PeerSearchType type) { final ApiSearchPeerType apiType; if (type == PeerSearchType.GROUPS) { apiType = ApiSearchPeerType.GROUPS; } else if (type == PeerSearchType.PUBLIC) { apiType = ApiSearchPeerType.PUBLIC; } else { apiType = ApiSearchPeerType.CONTACTS; } return new Command<List<PeerSearchEntity>>() { @Override public void start(final CommandCallback<List<PeerSearchEntity>> callback) { ArrayList<ApiSearchCondition> conditions = new ArrayList<ApiSearchCondition>(); conditions.add(new ApiSearchPeerTypeCondition(apiType)); request(new RequestPeerSearch(conditions), new RpcCallback<ResponsePeerSearch>() { @Override public void onResult(final ResponsePeerSearch response) { updates().executeRelatedResponse(response.getUsers(), response.getGroups(), new Runnable() { @Override public void run() { final ArrayList<PeerSearchEntity> res = new ArrayList<PeerSearchEntity>(); for (ApiPeerSearchResult r : response.getSearchResults()) { res.add(new PeerSearchEntity(convert(r.getPeer()), r.getTitle(), r.getDescription(), r.getMembersCount(), r.getDateCreated(), r.getCreator(), r.isPublic(), r.isJoined())); } runOnUiThread(new Runnable() { @Override public void run() { callback.onResult(res); } }); } }); } @Override public void onError(final RpcException e) { runOnUiThread(new Runnable() { @Override public void run() { callback.onError(e); } }); } }); } }; } public void resetModule() { actorRef.send(new SearchActor.Clear()); } }
actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/modules/internal/SearchModule.java
/* * Copyright (C) 2015 Actor LLC. <https://actor.im> */ package im.actor.core.modules.internal; import java.io.IOException; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.List; import im.actor.core.api.ApiMessageSearchItem; import im.actor.core.api.ApiMessageSearchResult; import im.actor.core.api.ApiPeerSearchResult; import im.actor.core.api.ApiSearchAndCondition; import im.actor.core.api.ApiSearchCondition; import im.actor.core.api.ApiSearchContentType; import im.actor.core.api.ApiSearchPeerCondition; import im.actor.core.api.ApiSearchPeerContentType; import im.actor.core.api.ApiSearchPeerType; import im.actor.core.api.ApiSearchPeerTypeCondition; import im.actor.core.api.ApiSearchPieceText; import im.actor.core.api.rpc.RequestMessageSearch; import im.actor.core.api.rpc.RequestPeerSearch; import im.actor.core.api.rpc.ResponseMessageSearch; import im.actor.core.api.rpc.ResponsePeerSearch; import im.actor.core.entity.Dialog; import im.actor.core.entity.MessageSearchEntity; import im.actor.core.entity.Peer; import im.actor.core.entity.PeerSearchEntity; import im.actor.core.entity.PeerSearchType; import im.actor.core.entity.SearchEntity; import im.actor.core.entity.content.AbsContent; import im.actor.core.modules.AbsModule; import im.actor.core.modules.Modules; import im.actor.core.modules.internal.search.SearchActor; import im.actor.core.network.RpcCallback; import im.actor.core.network.RpcException; import im.actor.core.viewmodel.Command; import im.actor.core.viewmodel.CommandCallback; import im.actor.runtime.Log; import im.actor.runtime.Storage; import im.actor.runtime.actors.ActorCreator; import im.actor.runtime.actors.ActorRef; import im.actor.runtime.actors.Props; import im.actor.runtime.storage.ListEngine; import static im.actor.core.modules.internal.messages.entity.EntityConverter.convert; import static im.actor.runtime.actors.ActorSystem.system; public class SearchModule extends AbsModule { private ListEngine<SearchEntity> searchList; private ActorRef actorRef; public SearchModule(Modules modules) { super(modules); searchList = Storage.createList(STORAGE_SEARCH, SearchEntity.CREATOR); } public void run() { actorRef = system().actorOf(Props.create(SearchActor.class, new ActorCreator<SearchActor>() { @Override public SearchActor create() { return new SearchActor(context()); } }), "actor/search"); } public ListEngine<SearchEntity> getSearchList() { return searchList; } public void onDialogsChanged(List<Dialog> dialogs) { actorRef.send(new SearchActor.OnDialogsUpdated(dialogs)); } public void onContactsChanged(Integer[] contacts) { int[] res = new int[contacts.length]; for (int i = 0; i < res.length; i++) { res[i] = contacts[i]; } actorRef.send(new SearchActor.OnContactsUpdated(res)); } public Command<List<MessageSearchEntity>> findTextMessages(Peer peer, String query) { ArrayList<ApiSearchCondition> conditions = new ArrayList<>(); conditions.add(new ApiSearchPeerCondition(buildApiOutPeer(peer))); conditions.add(new ApiSearchPieceText(query)); return findMessages(new ApiSearchAndCondition(conditions)); } public Command<List<MessageSearchEntity>> findAllDocs(Peer peer) { return findAllContent(peer, ApiSearchContentType.DOCUMENTS); } public Command<List<MessageSearchEntity>> findAllLinks(Peer peer) { return findAllContent(peer, ApiSearchContentType.LINKS); } public Command<List<MessageSearchEntity>> findAllPhotos(Peer peer) { return findAllContent(peer, ApiSearchContentType.PHOTOS); } private Command<List<MessageSearchEntity>> findAllContent(Peer peer, ApiSearchContentType contentType) { ArrayList<ApiSearchCondition> conditions = new ArrayList<>(); conditions.add(new ApiSearchPeerCondition(buildApiOutPeer(peer))); conditions.add(new ApiSearchPeerContentType(contentType)); return findMessages(new ApiSearchAndCondition(conditions)); } private Command<List<MessageSearchEntity>> findMessages(final ApiSearchCondition condition) { return new Command<List<MessageSearchEntity>>() { @Override public void start(final CommandCallback<List<MessageSearchEntity>> callback) { request(new RequestMessageSearch(condition), new RpcCallback<ResponseMessageSearch>() { @Override public void onResult(final ResponseMessageSearch response) { updates().executeRelatedResponse(response.getUsers(), response.getGroups(), new Runnable() { @Override public void run() { final ArrayList<MessageSearchEntity> res = new ArrayList<MessageSearchEntity>(); for (ApiMessageSearchItem r : response.getSearchResults()) { ApiMessageSearchResult itm = r.getResult(); try { res.add(new MessageSearchEntity( convert(itm.getPeer()), itm.getRid(), itm.getDate(), itm.getSenderId(), AbsContent.fromMessage(itm.getContent()))); } catch (IOException e) { e.printStackTrace(); } } runOnUiThread(new Runnable() { @Override public void run() { callback.onResult(res); } }); } }); } @Override public void onError(final RpcException e) { runOnUiThread(new Runnable() { @Override public void run() { callback.onError(e); } }); } }); } }; } public Command<List<PeerSearchEntity>> findPeers(final PeerSearchType type) { final ApiSearchPeerType apiType; if (type == PeerSearchType.GROUPS) { apiType = ApiSearchPeerType.GROUPS; } else if (type == PeerSearchType.PUBLIC) { apiType = ApiSearchPeerType.PUBLIC; } else { apiType = ApiSearchPeerType.CONTACTS; } return new Command<List<PeerSearchEntity>>() { @Override public void start(final CommandCallback<List<PeerSearchEntity>> callback) { ArrayList<ApiSearchCondition> conditions = new ArrayList<ApiSearchCondition>(); conditions.add(new ApiSearchPeerTypeCondition(apiType)); request(new RequestPeerSearch(conditions), new RpcCallback<ResponsePeerSearch>() { @Override public void onResult(final ResponsePeerSearch response) { updates().executeRelatedResponse(response.getUsers(), response.getGroups(), new Runnable() { @Override public void run() { final ArrayList<PeerSearchEntity> res = new ArrayList<PeerSearchEntity>(); for (ApiPeerSearchResult r : response.getSearchResults()) { res.add(new PeerSearchEntity(convert(r.getPeer()), r.getTitle(), r.getDescription(), r.getMembersCount(), r.getDateCreated(), r.getCreator(), r.isPublic(), r.isJoined())); } runOnUiThread(new Runnable() { @Override public void run() { callback.onResult(res); } }); } }); } @Override public void onError(final RpcException e) { runOnUiThread(new Runnable() { @Override public void run() { callback.onError(e); } }); } }); } }; } public void resetModule() { actorRef.send(new SearchActor.Clear()); } }
fix(core): Fixing cli build
actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/modules/internal/SearchModule.java
fix(core): Fixing cli build
Java
mit
b274fa90d23612e4f32c01abf6eb4fc499bc39e4
0
emeryduh/TeamJones_Project,emeryduh/TeamJones_Project,emeryduh/TeamJones_Project
package mainpackage; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; public class PlayerInput implements KeyListener { private int gameScreen; public PlayerInput() { } public void menuOrGame(int gameScreen) { this.gameScreen = gameScreen; } @Override public void keyPressed(KeyEvent e) { int keyPressed = e.getKeyCode(); if (gameScreen == 0) { switch (keyPressed) { case KeyEvent.VK_LEFT: break; case KeyEvent.VK_RIGHT: break; case KeyEvent.VK_ENTER: break; } } else { switch (keyPressed) { case KeyEvent.VK_LEFT: break; case KeyEvent.VK_RIGHT: break; case KeyEvent.VK_UP: break; case KeyEvent.VK_DOWN: break; case KeyEvent.VK_M: break; case KeyEvent.VK_N: break; case KeyEvent.VK_B: break; case KeyEvent.VK_SPACE: break; } } } @Override public void keyReleased(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { } }
TeamJones_Project/src/mainpackage/PlayerInput.java
package mainpackage; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; public class PlayerInput implements KeyListener { private int gameScreen; public PlayerInput() { } public void menuOrGame(int gameScreen) { this.gameScreen = gameScreen; } @Override public void keyPressed(KeyEvent e) { int keyPressed = e.getKeyCode(); if (gameScreen == 0) { switch (keyPressed) { case KeyEvent.VK_LEFT: break; case KeyEvent.VK_RIGHT: break; case KeyEvent.VK_ENTER: break; } } else { switch (keyPressed) { case KeyEvent.VK_LEFT: break; case KeyEvent.VK_RIGHT: break; case KeyEvent.VK_M: break; case KeyEvent.VK_N: break; case KeyEvent.VK_B: break; case KeyEvent.VK_SPACE: break; } } } @Override public void keyReleased(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { } }
minor fix to PlayerInput
TeamJones_Project/src/mainpackage/PlayerInput.java
minor fix to PlayerInput
Java
mit
80bda37512838877721e632a7d4a299263ed6d4b
0
lemmy/tlaplus,lemmy/tlaplus,tlaplus/tlaplus,lemmy/tlaplus,tlaplus/tlaplus,lemmy/tlaplus,tlaplus/tlaplus,tlaplus/tlaplus
package org.lamport.tla.toolbox.tool.tlc.ui.editor.page; import java.util.Arrays; import java.util.Hashtable; import java.util.List; import java.util.Vector; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.forms.IManagedForm; import org.eclipse.ui.forms.IMessageManager; import org.eclipse.ui.forms.editor.FormEditor; import org.eclipse.ui.forms.widgets.FormText; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.Section; import org.eclipse.ui.forms.widgets.TableWrapData; import org.lamport.tla.toolbox.tool.ToolboxHandle; import org.lamport.tla.toolbox.tool.tlc.launch.IConfigurationConstants; import org.lamport.tla.toolbox.tool.tlc.launch.IConfigurationDefaults; import org.lamport.tla.toolbox.tool.tlc.model.Assignment; import org.lamport.tla.toolbox.tool.tlc.model.TypedSet; import org.lamport.tla.toolbox.tool.tlc.ui.editor.DataBindingManager; import org.lamport.tla.toolbox.tool.tlc.ui.editor.ModelEditor; import org.lamport.tla.toolbox.tool.tlc.ui.editor.part.ValidateableOverridesSectionPart; import org.lamport.tla.toolbox.tool.tlc.ui.editor.part.ValidateableSectionPart; import org.lamport.tla.toolbox.tool.tlc.ui.util.DirtyMarkingListener; import org.lamport.tla.toolbox.tool.tlc.ui.util.FormHelper; import org.lamport.tla.toolbox.tool.tlc.ui.util.SemanticHelper; import org.lamport.tla.toolbox.util.IHelpConstants; import org.lamport.tla.toolbox.util.UIHelper; import tla2sany.modanalyzer.SpecObj; import tla2sany.semantic.OpDefNode; /** * Represent all advanced model elements * * @author Simon Zambrovski * @version $Id$ */ public class AdvancedModelPage extends BasicFormPage implements IConfigurationConstants, IConfigurationDefaults { public static final String ID = "advancedModelPage"; private SourceViewer constraintSource; private SourceViewer actionConstraintSource; private SourceViewer newDefinitionsSource; private SourceViewer viewSource; private SourceViewer modelValuesSource; private Button dfidOption; private Button mcOption; private Button simulationOption; private Text dfidDepthText; private Text simuDepthText; private Text simuSeedText; private Text simuArilText; private TableViewer definitionsTable; /** * Constructs the page * * @param editor */ public AdvancedModelPage(FormEditor editor) { super(editor, AdvancedModelPage.ID, "Advanced Options"); this.helpId = IHelpConstants.ADVANCED_MODEL_PAGE; this.imagePath = "icons/full/choice_sc_obj.gif"; } /** * Loads data from the model */ protected void loadData() throws CoreException { // definition overrides List definitions = getConfig().getAttribute(MODEL_PARAMETER_DEFINITIONS, new Vector()); FormHelper.setSerializedInput(definitionsTable, definitions); // new definitions String newDefinitions = getConfig().getAttribute(MODEL_PARAMETER_NEW_DEFINITIONS, EMPTY_STRING); newDefinitionsSource.setDocument(new Document(newDefinitions)); // advanced model values String modelValues = getConfig().getAttribute(MODEL_PARAMETER_MODEL_VALUES, EMPTY_STRING); modelValuesSource.setDocument(new Document(modelValues)); // constraint String constraint = getConfig().getAttribute(MODEL_PARAMETER_CONSTRAINT, EMPTY_STRING); constraintSource.setDocument(new Document(constraint)); // view String view = getConfig().getAttribute(LAUNCH_VIEW, EMPTY_STRING); viewSource.setDocument(new Document(view)); // action constraint String actionConstraint = getConfig().getAttribute(MODEL_PARAMETER_ACTION_CONSTRAINT, EMPTY_STRING); actionConstraintSource.setDocument(new Document(actionConstraint)); // run mode mode boolean isMCMode = getConfig().getAttribute(LAUNCH_MC_MODE, LAUNCH_MC_MODE_DEFAULT); mcOption.setSelection(isMCMode); simulationOption.setSelection(!isMCMode); // DFID mode boolean isDFIDMode = getConfig().getAttribute(LAUNCH_DFID_MODE, LAUNCH_DFID_MODE_DEFAULT); dfidOption.setSelection(isDFIDMode); // DFID depth int dfidDepth = getConfig().getAttribute(LAUNCH_DFID_DEPTH, LAUNCH_DFID_DEPTH_DEFAULT); dfidDepthText.setText("" + dfidDepth); // simulation depth int simuDepth = getConfig().getAttribute(LAUNCH_SIMU_DEPTH, LAUNCH_SIMU_DEPTH_DEFAULT); simuDepthText.setText("" + simuDepth); // simulation aril int simuAril = getConfig().getAttribute(LAUNCH_SIMU_SEED, LAUNCH_SIMU_ARIL_DEFAULT); if (LAUNCH_SIMU_ARIL_DEFAULT != simuAril) { simuArilText.setText("" + simuAril); } else { simuArilText.setText(""); } // simulation seed int simuSeed = getConfig().getAttribute(LAUNCH_SIMU_ARIL, LAUNCH_SIMU_SEED_DEFAULT); if (LAUNCH_SIMU_SEED_DEFAULT != simuSeed) { simuSeedText.setText("" + simuSeed); } else { simuSeedText.setText(""); } } /** * Save data back to config */ public void commit(boolean onSave) { // TLCUIActivator.logDebug("Advanced page commit"); boolean isMCMode = mcOption.getSelection(); getConfig().setAttribute(LAUNCH_MC_MODE, isMCMode); // DFID mode boolean isDFIDMode = dfidOption.getSelection(); getConfig().setAttribute(LAUNCH_DFID_MODE, isDFIDMode); int dfidDepth = Integer.parseInt(dfidDepthText.getText()); int simuDepth = Integer.parseInt(simuDepthText.getText()); int simuAril = LAUNCH_SIMU_ARIL_DEFAULT; int simuSeed = LAUNCH_SIMU_SEED_DEFAULT; if (!"".equals(simuArilText.getText())) { simuAril = Integer.parseInt(simuArilText.getText()); } if (!"".equals(simuSeedText.getText())) { simuSeed = Integer.parseInt(simuSeedText.getText()); } // DFID depth getConfig().setAttribute(LAUNCH_DFID_DEPTH, dfidDepth); // simulation depth getConfig().setAttribute(LAUNCH_SIMU_DEPTH, simuDepth); // simulation aril getConfig().setAttribute(LAUNCH_SIMU_SEED, simuSeed); // simulation seed getConfig().setAttribute(LAUNCH_SIMU_ARIL, simuAril); // definitions List definitions = FormHelper.getSerializedInput(definitionsTable); getConfig().setAttribute(MODEL_PARAMETER_DEFINITIONS, definitions); // new definitions String newDefinitions = FormHelper.trimTrailingSpaces(newDefinitionsSource.getDocument().get()); getConfig().setAttribute(MODEL_PARAMETER_NEW_DEFINITIONS, newDefinitions); // model values String modelValues = FormHelper.trimTrailingSpaces(modelValuesSource.getDocument().get()); TypedSet modelValuesSet = TypedSet.parseSet(modelValues); getConfig().setAttribute(MODEL_PARAMETER_MODEL_VALUES, modelValuesSet.toString()); // constraint formula String constraintFormula = FormHelper.trimTrailingSpaces(constraintSource.getDocument().get()); getConfig().setAttribute(MODEL_PARAMETER_CONSTRAINT, constraintFormula); // view String viewFormula = FormHelper.trimTrailingSpaces(viewSource.getDocument().get()); getConfig().setAttribute(LAUNCH_VIEW, viewFormula); // action constraint formula String actionConstraintFormula = FormHelper.trimTrailingSpaces(actionConstraintSource.getDocument().get()); getConfig().setAttribute(MODEL_PARAMETER_ACTION_CONSTRAINT, actionConstraintFormula); super.commit(onSave); } /** * */ public void validatePage(boolean switchToErrorPage) { if (getManagedForm() == null) { return; } IMessageManager mm = getManagedForm().getMessageManager(); mm.setAutoUpdate(false); ModelEditor modelEditor = (ModelEditor) getEditor(); // clean old messages // this is now done in validateRunnable of // ModelEditor // mm.removeAllMessages(); // make the run possible setComplete(true); // setup the names from the current page getLookupHelper().resetModelNames(this); try { int dfidDepth = Integer.parseInt(dfidDepthText.getText()); if (dfidDepth <= 0) { modelEditor.addErrorMessage("dfid1", "Depth of DFID launch must be a positive integer", this.getId(), IMessageProvider.ERROR, dfidDepthText); setComplete(false); expandSection(SEC_LAUNCHING_SETUP); } } catch (NumberFormatException e) { modelEditor.addErrorMessage("dfid2", "Depth of DFID launch must be a positive integer", this.getId(), IMessageProvider.ERROR, dfidDepthText); setComplete(false); expandSection(SEC_LAUNCHING_SETUP); } try { int simuDepth = Integer.parseInt(simuDepthText.getText()); if (simuDepth <= 0) { modelEditor.addErrorMessage("simuDepth1", "Length of the simulation tracemust be a positive integer", this.getId(), IMessageProvider.ERROR, simuDepthText); setComplete(false); expandSection(SEC_LAUNCHING_SETUP); } } catch (NumberFormatException e) { modelEditor.addErrorMessage("simuDepth2", "Length of the simulation trace must be a positive integer", this .getId(), IMessageProvider.ERROR, simuDepthText); setComplete(false); expandSection(SEC_LAUNCHING_SETUP); } if (!EMPTY_STRING.equals(simuArilText.getText())) { try { long simuAril = Long.parseLong(simuArilText.getText()); if (simuAril <= 0) { modelEditor.addErrorMessage("simuAril1", "The simulation aril must be a positive integer", this .getId(), IMessageProvider.ERROR, simuArilText); setComplete(false); } } catch (NumberFormatException e) { modelEditor.addErrorMessage("simuAril2", "The simulation aril must be a positive integer", this.getId(), IMessageProvider.ERROR, simuArilText); setComplete(false); expandSection(SEC_LAUNCHING_SETUP); } } if (!EMPTY_STRING.equals(simuSeedText.getText())) { try { // long simuSeed = Long.parseLong(simuSeedText.getText()); } catch (NumberFormatException e) { modelEditor.addErrorMessage("simuSeed1", "The simulation aril must be a positive integer", this.getId(), IMessageProvider.ERROR, simuSeedText); expandSection(SEC_LAUNCHING_SETUP); setComplete(false); } } // get data binding manager DataBindingManager dm = getDataBindingManager(); // check the model values TypedSet modelValuesSet = TypedSet.parseSet(FormHelper .trimTrailingSpaces(modelValuesSource.getDocument().get())); if (modelValuesSet.getValueCount() > 0) { // there were values defined // check if those are numbers? /* * if (modelValuesSet.hasANumberOnlyValue()) { * mm.addMessage("modelValues1", * "A model value can not be an number", modelValuesSet, * IMessageProvider.ERROR, modelValuesSource.getControl()); * setComplete(false); } */ List values = modelValuesSet.getValuesAsList(); // check list of model values if these are already used validateUsage(MODEL_PARAMETER_MODEL_VALUES, values, "modelValues2_", "A model value", "Advanced Model Values", true); // check whether the model values are valid ids validateId(MODEL_PARAMETER_MODEL_VALUES, values, "modelValues2_", "A model value"); // get widget for model values Control widget = UIHelper.getWidget(dm.getAttributeControl(MODEL_PARAMETER_MODEL_VALUES)); // check if model values are config file keywords for (int j = 0; j < values.size(); j++) { String value = (String) values.get(j); if (SemanticHelper.isConfigFileKeyword(value)) { modelEditor.addErrorMessage(value, "The toolbox cannot handle the model value " + value + ".", this .getId(), IMessageProvider.ERROR, widget); setComplete(false); } } } // opDefNodes necessary for determining if a definition in definition // overrides is still in the specification SpecObj specObj = ToolboxHandle.getCurrentSpec().getValidRootModule(); OpDefNode[] opDefNodes = null; if (specObj != null) { opDefNodes = specObj.getExternalModuleTable().getRootModule().getOpDefs(); } Hashtable nodeTable = new Hashtable(); if (opDefNodes != null) { for (int j = 0; j < opDefNodes.length; j++) { String key = opDefNodes[j].getName().toString(); nodeTable.put(key, opDefNodes[j]); } } // get widget for definition overrides Control widget = UIHelper.getWidget(dm.getAttributeControl(MODEL_PARAMETER_DEFINITIONS)); // check the definition overrides List definitions = (List) definitionsTable.getInput(); for (int i = 0; i < definitions.size(); i++) { Assignment definition = (Assignment) definitions.get(i); List values = Arrays.asList(definition.getParams()); // check list of parameters validateUsage(MODEL_PARAMETER_DEFINITIONS, values, "param1_", "A parameter name", "Definition Overrides", false); // check whether the parameters are valid ids validateId(MODEL_PARAMETER_DEFINITIONS, values, "param1_", "A parameter name"); // The following if test was added by LL on 11 Nov 2009 to prevent an unparsed // file from producing bogus error messages saying that overridden definitions // have been removed from the spec. if (opDefNodes != null) { // check if definition still appears in root module if (!nodeTable.containsKey(definition.getLabel())) { // the following would remove // the definition override from the table // right now, an error message appears instead // definitions.remove(i); // definitionsTable.setInput(definitions); // dm.getSection(DEF_OVERRIDES_PART).markDirty(); modelEditor.addErrorMessage(definition.getLabel(), "The defined symbol " + definition.getLabel().substring(definition.getLabel().lastIndexOf("!") + 1) + " has been removed from the specification." + " It must be removed from the list of definition overrides.", this.getId(), IMessageProvider.ERROR, widget); setComplete(false); } else { // add error message if the number of parameters has changed OpDefNode opDefNode = (OpDefNode) nodeTable.get(definition.getLabel()); if (opDefNode.getSource().getNumberOfArgs() != definition.getParams().length) { modelEditor.addErrorMessage(definition.getLabel(), "Edit the definition override for " + opDefNode.getSource().getName() + " to match the correct number of arguments.", this .getId(), IMessageProvider.ERROR, widget); setComplete(false); } } } } for (int j = 0; j < definitions.size(); j++) { Assignment definition = (Assignment) definitions.get(j); String label = definition.getLabel(); if (SemanticHelper.isConfigFileKeyword(label)) { modelEditor.addErrorMessage(label, "The toolbox cannot override the definition of " + label + " because it is a configuration file keyword.", this.getId(), IMessageProvider.ERROR, widget); setComplete(false); } } // check if the view field contains a cfg file keyword Control viewWidget = UIHelper.getWidget(dm.getAttributeControl(MODEL_PARAMETER_VIEW)); String viewString = FormHelper.trimTrailingSpaces(viewSource.getDocument().get()); if (SemanticHelper.containsConfigFileKeyword(viewString)) { modelEditor.addErrorMessage(viewString, "The toolbox cannot handle the string " + viewString + " because it contains a configuration file keyword.", this.getId(), IMessageProvider.ERROR, viewWidget); setComplete(false); } mm.setAutoUpdate(true); super.validatePage(switchToErrorPage); } /** * Creates the UI * * Its helpful to know what the standard SWT widgets look like. * Pictures can be found at http://www.eclipse.org/swt/widgets/ * * Layouts are used throughout this method. * A good explanation of layouts is given in the article * http://www.eclipse.org/articles/article.php?file=Article-Understanding-Layouts/index.html */ protected void createBodyContent(IManagedForm managedForm) { DataBindingManager dm = getDataBindingManager(); int sectionFlags = Section.TITLE_BAR | Section.DESCRIPTION | Section.TREE_NODE; FormToolkit toolkit = managedForm.getToolkit(); Composite body = managedForm.getForm().getBody(); GridData gd; TableWrapData twd; // left Composite left = toolkit.createComposite(body); twd = new TableWrapData(TableWrapData.FILL_GRAB); twd.grabHorizontal = true; left.setLayout(new GridLayout(1, false)); left.setLayoutData(twd); // right Composite right = toolkit.createComposite(body); twd = new TableWrapData(TableWrapData.FILL_GRAB); twd.grabHorizontal = true; right.setLayoutData(twd); right.setLayout(new GridLayout(1, false)); Section section; // --------------------------------------------------------------- // new definitions section = FormHelper .createSectionComposite( left, "Additional Definitions", "Definitions required for the model checking, in addition to the definitions in the specification modules.", toolkit, sectionFlags, getExpansionListener()); ValidateableSectionPart newDefinitionsPart = new ValidateableSectionPart(section, this, SEC_NEW_DEFINITION); managedForm.addPart(newDefinitionsPart); DirtyMarkingListener newDefinitionsListener = new DirtyMarkingListener(newDefinitionsPart, true); gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 3; section.setLayoutData(gd); Composite newDefinitionsArea = (Composite) section.getClient(); newDefinitionsSource = FormHelper.createFormsSourceViewer(toolkit, newDefinitionsArea, SWT.V_SCROLL); // layout of the source viewer twd = new TableWrapData(TableWrapData.FILL); twd.heightHint = 60; twd.grabHorizontal = true; newDefinitionsSource.getTextWidget().setLayoutData(twd); newDefinitionsSource.addTextListener(newDefinitionsListener); dm.bindAttribute(MODEL_PARAMETER_NEW_DEFINITIONS, newDefinitionsSource, newDefinitionsPart); // --------------------------------------------------------------- // definition overwrite ValidateableOverridesSectionPart definitionsPart = new ValidateableOverridesSectionPart(right, "Definition Override", "Directs TLC to use alternate definitions for operators.", toolkit, sectionFlags, this); managedForm.addPart(definitionsPart); // layout gd = new GridData(GridData.FILL_HORIZONTAL); definitionsPart.getSection().setLayoutData(gd); gd = new GridData(GridData.FILL_BOTH); gd.widthHint = 100; gd.verticalSpan = 3; definitionsPart.getTableViewer().getTable().setLayoutData(gd); definitionsTable = definitionsPart.getTableViewer(); dm.bindAttribute(MODEL_PARAMETER_DEFINITIONS, definitionsTable, definitionsPart); // --------------------------------------------------------------- // constraint section = FormHelper.createSectionComposite(left, "State Constraint", "A state constraint is a formula restricting the possible states by a state predicate.", toolkit, sectionFlags, getExpansionListener()); ValidateableSectionPart constraintPart = new ValidateableSectionPart(section, this, SEC_STATE_CONSTRAINT); managedForm.addPart(constraintPart); DirtyMarkingListener constraintListener = new DirtyMarkingListener(constraintPart, true); gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 3; section.setLayoutData(gd); Composite constraintArea = (Composite) section.getClient(); constraintSource = FormHelper.createFormsSourceViewer(toolkit, constraintArea, SWT.V_SCROLL); // layout of the source viewer twd = new TableWrapData(TableWrapData.FILL); twd.heightHint = 60; twd.grabHorizontal = true; constraintSource.getTextWidget().setLayoutData(twd); constraintSource.addTextListener(constraintListener); dm.bindAttribute(MODEL_PARAMETER_CONSTRAINT, constraintSource, constraintPart); // --------------------------------------------------------------- // action constraint section = FormHelper.createSectionComposite(right, "Action Constraint", "An action constraint is a formula restricting the possible transitions.", toolkit, sectionFlags, getExpansionListener()); ValidateableSectionPart actionConstraintPart = new ValidateableSectionPart(section, this, SEC_ACTION_CONSTRAINT); managedForm.addPart(actionConstraintPart); DirtyMarkingListener actionConstraintListener = new DirtyMarkingListener(actionConstraintPart, true); gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 3; section.setLayoutData(gd); Composite actionConstraintArea = (Composite) section.getClient(); actionConstraintSource = FormHelper.createFormsSourceViewer(toolkit, actionConstraintArea, SWT.V_SCROLL); // layout of the source viewer twd = new TableWrapData(TableWrapData.FILL); twd.heightHint = 60; twd.grabHorizontal = true; actionConstraintSource.getTextWidget().setLayoutData(twd); actionConstraintSource.addTextListener(actionConstraintListener); dm.bindAttribute(MODEL_PARAMETER_ACTION_CONSTRAINT, actionConstraintSource, actionConstraintPart); // --------------------------------------------------------------- // modelValues section = FormHelper.createSectionComposite(left, "Model Values", "An additional set of model values.", toolkit, sectionFlags, getExpansionListener()); ValidateableSectionPart modelValuesPart = new ValidateableSectionPart(section, this, SEC_MODEL_VALUES); managedForm.addPart(modelValuesPart); DirtyMarkingListener modelValuesListener = new DirtyMarkingListener(modelValuesPart, true); gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 3; section.setLayoutData(gd); Composite modelValueArea = (Composite) section.getClient(); modelValuesSource = FormHelper.createFormsSourceViewer(toolkit, modelValueArea, SWT.V_SCROLL); // layout of the source viewer twd = new TableWrapData(TableWrapData.FILL); twd.heightHint = 60; twd.grabHorizontal = true; modelValuesSource.getTextWidget().setLayoutData(twd); modelValuesSource.addTextListener(modelValuesListener); dm.bindAttribute(MODEL_PARAMETER_MODEL_VALUES, modelValuesSource, modelValuesPart); // --------------------------------------------------------------- // launch section = createAdvancedLaunchSection(toolkit, right, sectionFlags); ValidateableSectionPart launchPart = new ValidateableSectionPart(section, this, SEC_LAUNCHING_SETUP); managedForm.addPart(launchPart); DirtyMarkingListener launchListener = new DirtyMarkingListener(launchPart, true); dm.bindAttribute(MODEL_PARAMETER_VIEW, viewSource, launchPart); // dirty listeners simuArilText.addModifyListener(launchListener); simuSeedText.addModifyListener(launchListener); simuDepthText.addModifyListener(launchListener); dfidDepthText.addModifyListener(launchListener); simulationOption.addSelectionListener(launchListener); dfidOption.addSelectionListener(launchListener); mcOption.addSelectionListener(launchListener); viewSource.addTextListener(launchListener); // add section ignoring listeners dirtyPartListeners.add(newDefinitionsListener); dirtyPartListeners.add(actionConstraintListener); dirtyPartListeners.add(modelValuesListener); dirtyPartListeners.add(constraintListener); dirtyPartListeners.add(launchListener); } /** * @param toolkit * @param parent * @param flags */ private Section createAdvancedLaunchSection(FormToolkit toolkit, Composite parent, int sectionFlags) { GridData gd; // advanced section Section advancedSection = FormHelper.createSectionComposite(parent, "TLC Options", "Advanced settings of the TLC model checker", toolkit, sectionFlags, getExpansionListener()); gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 2; gd.grabExcessHorizontalSpace = true; advancedSection.setLayoutData(gd); Composite area = (Composite) advancedSection.getClient(); area.setLayout(new GridLayout(2, false)); mcOption = toolkit.createButton(area, "Model-checking mode", SWT.RADIO); gd = new GridData(); gd.horizontalSpan = 2; mcOption.setLayoutData(gd); // label view FormText viewLabel = toolkit.createFormText(area, true); viewLabel.setText("View:", false, false); gd = new GridData(); gd.verticalAlignment = SWT.BEGINNING; gd.horizontalIndent = 10; viewLabel.setLayoutData(gd); // field view viewSource = FormHelper.createFormsSourceViewer(toolkit, area, SWT.V_SCROLL); // layout of the source viewer gd = new GridData(GridData.FILL_HORIZONTAL); gd.grabExcessHorizontalSpace = true; gd.heightHint = 60; gd.widthHint = 200; viewSource.getTextWidget().setLayoutData(gd); dfidOption = toolkit.createButton(area, "Depth-first", SWT.CHECK); gd = new GridData(); gd.horizontalSpan = 2; gd.horizontalIndent = 10; dfidOption.setLayoutData(gd); // label depth FormText dfidDepthLabel = toolkit.createFormText(area, true); dfidDepthLabel.setText("Depth:", false, false); gd = new GridData(); gd.horizontalIndent = 10; dfidDepthLabel.setLayoutData(gd); // field depth dfidDepthText = toolkit.createText(area, "100"); gd = new GridData(); gd.widthHint = 100; dfidDepthText.setLayoutData(gd); simulationOption = toolkit.createButton(area, "Simulation mode", SWT.RADIO); gd = new GridData(); gd.horizontalSpan = 2; simulationOption.setLayoutData(gd); // label depth FormText depthLabel = toolkit.createFormText(area, true); depthLabel.setText("Maximum length of the trace:", false, false); gd = new GridData(); gd.horizontalIndent = 10; depthLabel.setLayoutData(gd); // field depth simuDepthText = toolkit.createText(area, "100"); gd = new GridData(); gd.widthHint = 100; simuDepthText.setLayoutData(gd); // label seed FormText seedLabel = toolkit.createFormText(area, true); seedLabel.setText("Seed:", false, false); gd = new GridData(); gd.horizontalIndent = 10; seedLabel.setLayoutData(gd); // field seed simuSeedText = toolkit.createText(area, ""); gd = new GridData(); gd.widthHint = 200; simuSeedText.setLayoutData(gd); // label seed FormText arilLabel = toolkit.createFormText(area, true); arilLabel.setText("Aril:", false, false); gd = new GridData(); gd.horizontalIndent = 10; arilLabel.setLayoutData(gd); // field seed simuArilText = toolkit.createText(area, ""); gd = new GridData(); gd.widthHint = 200; simuArilText.setLayoutData(gd); return advancedSection; } }
org.lamport.tla.toolbox.tool.tlc.ui/src/org/lamport/tla/toolbox/tool/tlc/ui/editor/page/AdvancedModelPage.java
package org.lamport.tla.toolbox.tool.tlc.ui.editor.page; import java.util.Arrays; import java.util.Hashtable; import java.util.List; import java.util.Vector; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.forms.IManagedForm; import org.eclipse.ui.forms.IMessageManager; import org.eclipse.ui.forms.editor.FormEditor; import org.eclipse.ui.forms.widgets.FormText; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.Section; import org.eclipse.ui.forms.widgets.TableWrapData; import org.lamport.tla.toolbox.tool.ToolboxHandle; import org.lamport.tla.toolbox.tool.tlc.launch.IConfigurationConstants; import org.lamport.tla.toolbox.tool.tlc.launch.IConfigurationDefaults; import org.lamport.tla.toolbox.tool.tlc.model.Assignment; import org.lamport.tla.toolbox.tool.tlc.model.TypedSet; import org.lamport.tla.toolbox.tool.tlc.ui.editor.DataBindingManager; import org.lamport.tla.toolbox.tool.tlc.ui.editor.ModelEditor; import org.lamport.tla.toolbox.tool.tlc.ui.editor.part.ValidateableOverridesSectionPart; import org.lamport.tla.toolbox.tool.tlc.ui.editor.part.ValidateableSectionPart; import org.lamport.tla.toolbox.tool.tlc.ui.util.DirtyMarkingListener; import org.lamport.tla.toolbox.tool.tlc.ui.util.FormHelper; import org.lamport.tla.toolbox.tool.tlc.ui.util.SemanticHelper; import org.lamport.tla.toolbox.util.IHelpConstants; import org.lamport.tla.toolbox.util.UIHelper; import tla2sany.modanalyzer.SpecObj; import tla2sany.semantic.OpDefNode; /** * Represent all advanced model elements * * @author Simon Zambrovski * @version $Id$ */ public class AdvancedModelPage extends BasicFormPage implements IConfigurationConstants, IConfigurationDefaults { public static final String ID = "advancedModelPage"; private SourceViewer constraintSource; private SourceViewer actionConstraintSource; private SourceViewer newDefinitionsSource; private SourceViewer viewSource; private SourceViewer modelValuesSource; private Button dfidOption; private Button mcOption; private Button simulationOption; private Text dfidDepthText; private Text simuDepthText; private Text simuSeedText; private Text simuArilText; private TableViewer definitionsTable; /** * Constructs the page * * @param editor */ public AdvancedModelPage(FormEditor editor) { super(editor, AdvancedModelPage.ID, "Advanced Options"); this.helpId = IHelpConstants.ADVANCED_MODEL_PAGE; this.imagePath = "icons/full/choice_sc_obj.gif"; } /** * Loads data from the model */ protected void loadData() throws CoreException { // definition overrides List definitions = getConfig().getAttribute(MODEL_PARAMETER_DEFINITIONS, new Vector()); FormHelper.setSerializedInput(definitionsTable, definitions); // new definitions String newDefinitions = getConfig().getAttribute(MODEL_PARAMETER_NEW_DEFINITIONS, EMPTY_STRING); newDefinitionsSource.setDocument(new Document(newDefinitions)); // advanced model values String modelValues = getConfig().getAttribute(MODEL_PARAMETER_MODEL_VALUES, EMPTY_STRING); modelValuesSource.setDocument(new Document(modelValues)); // constraint String constraint = getConfig().getAttribute(MODEL_PARAMETER_CONSTRAINT, EMPTY_STRING); constraintSource.setDocument(new Document(constraint)); // view String view = getConfig().getAttribute(LAUNCH_VIEW, EMPTY_STRING); viewSource.setDocument(new Document(view)); // action constraint String actionConstraint = getConfig().getAttribute(MODEL_PARAMETER_ACTION_CONSTRAINT, EMPTY_STRING); actionConstraintSource.setDocument(new Document(actionConstraint)); // run mode mode boolean isMCMode = getConfig().getAttribute(LAUNCH_MC_MODE, LAUNCH_MC_MODE_DEFAULT); mcOption.setSelection(isMCMode); simulationOption.setSelection(!isMCMode); // DFID mode boolean isDFIDMode = getConfig().getAttribute(LAUNCH_DFID_MODE, LAUNCH_DFID_MODE_DEFAULT); dfidOption.setSelection(isDFIDMode); // DFID depth int dfidDepth = getConfig().getAttribute(LAUNCH_DFID_DEPTH, LAUNCH_DFID_DEPTH_DEFAULT); dfidDepthText.setText("" + dfidDepth); // simulation depth int simuDepth = getConfig().getAttribute(LAUNCH_SIMU_DEPTH, LAUNCH_SIMU_DEPTH_DEFAULT); simuDepthText.setText("" + simuDepth); // simulation aril int simuAril = getConfig().getAttribute(LAUNCH_SIMU_SEED, LAUNCH_SIMU_ARIL_DEFAULT); if (LAUNCH_SIMU_ARIL_DEFAULT != simuAril) { simuArilText.setText("" + simuAril); } else { simuArilText.setText(""); } // simulation seed int simuSeed = getConfig().getAttribute(LAUNCH_SIMU_ARIL, LAUNCH_SIMU_SEED_DEFAULT); if (LAUNCH_SIMU_SEED_DEFAULT != simuSeed) { simuSeedText.setText("" + simuSeed); } else { simuSeedText.setText(""); } } /** * Save data back to config */ public void commit(boolean onSave) { // TLCUIActivator.logDebug("Advanced page commit"); boolean isMCMode = mcOption.getSelection(); getConfig().setAttribute(LAUNCH_MC_MODE, isMCMode); // DFID mode boolean isDFIDMode = dfidOption.getSelection(); getConfig().setAttribute(LAUNCH_DFID_MODE, isDFIDMode); int dfidDepth = Integer.parseInt(dfidDepthText.getText()); int simuDepth = Integer.parseInt(simuDepthText.getText()); int simuAril = LAUNCH_SIMU_ARIL_DEFAULT; int simuSeed = LAUNCH_SIMU_SEED_DEFAULT; if (!"".equals(simuArilText.getText())) { simuAril = Integer.parseInt(simuArilText.getText()); } if (!"".equals(simuSeedText.getText())) { simuSeed = Integer.parseInt(simuSeedText.getText()); } // DFID depth getConfig().setAttribute(LAUNCH_DFID_DEPTH, dfidDepth); // simulation depth getConfig().setAttribute(LAUNCH_SIMU_DEPTH, simuDepth); // simulation aril getConfig().setAttribute(LAUNCH_SIMU_SEED, simuSeed); // simulation seed getConfig().setAttribute(LAUNCH_SIMU_ARIL, simuAril); // definitions List definitions = FormHelper.getSerializedInput(definitionsTable); getConfig().setAttribute(MODEL_PARAMETER_DEFINITIONS, definitions); // new definitions String newDefinitions = FormHelper.trimTrailingSpaces(newDefinitionsSource.getDocument().get()); getConfig().setAttribute(MODEL_PARAMETER_NEW_DEFINITIONS, newDefinitions); // model values String modelValues = FormHelper.trimTrailingSpaces(modelValuesSource.getDocument().get()); TypedSet modelValuesSet = TypedSet.parseSet(modelValues); getConfig().setAttribute(MODEL_PARAMETER_MODEL_VALUES, modelValuesSet.toString()); // constraint formula String constraintFormula = FormHelper.trimTrailingSpaces(constraintSource.getDocument().get()); getConfig().setAttribute(MODEL_PARAMETER_CONSTRAINT, constraintFormula); // view String viewFormula = FormHelper.trimTrailingSpaces(viewSource.getDocument().get()); getConfig().setAttribute(LAUNCH_VIEW, viewFormula); // action constraint formula String actionConstraintFormula = FormHelper.trimTrailingSpaces(actionConstraintSource.getDocument().get()); getConfig().setAttribute(MODEL_PARAMETER_ACTION_CONSTRAINT, actionConstraintFormula); super.commit(onSave); } /** * */ public void validatePage(boolean switchToErrorPage) { if (getManagedForm() == null) { return; } IMessageManager mm = getManagedForm().getMessageManager(); mm.setAutoUpdate(false); ModelEditor modelEditor = (ModelEditor) getEditor(); // clean old messages // this is now done in validateRunnable of // ModelEditor // mm.removeAllMessages(); // make the run possible setComplete(true); // setup the names from the current page getLookupHelper().resetModelNames(this); try { int dfidDepth = Integer.parseInt(dfidDepthText.getText()); if (dfidDepth <= 0) { modelEditor.addErrorMessage("dfid1", "Depth of DFID launch must be a positive integer", this.getId(), IMessageProvider.ERROR, dfidDepthText); setComplete(false); expandSection(SEC_LAUNCHING_SETUP); } } catch (NumberFormatException e) { modelEditor.addErrorMessage("dfid2", "Depth of DFID launch must be a positive integer", this.getId(), IMessageProvider.ERROR, dfidDepthText); setComplete(false); expandSection(SEC_LAUNCHING_SETUP); } try { int simuDepth = Integer.parseInt(simuDepthText.getText()); if (simuDepth <= 0) { modelEditor.addErrorMessage("simuDepth1", "Length of the simulation tracemust be a positive integer", this.getId(), IMessageProvider.ERROR, simuDepthText); setComplete(false); expandSection(SEC_LAUNCHING_SETUP); } } catch (NumberFormatException e) { modelEditor.addErrorMessage("simuDepth2", "Length of the simulation trace must be a positive integer", this .getId(), IMessageProvider.ERROR, simuDepthText); setComplete(false); expandSection(SEC_LAUNCHING_SETUP); } if (!EMPTY_STRING.equals(simuArilText.getText())) { try { long simuAril = Long.parseLong(simuArilText.getText()); if (simuAril <= 0) { modelEditor.addErrorMessage("simuAril1", "The simulation aril must be a positive integer", this .getId(), IMessageProvider.ERROR, simuArilText); setComplete(false); } } catch (NumberFormatException e) { modelEditor.addErrorMessage("simuAril2", "The simulation aril must be a positive integer", this.getId(), IMessageProvider.ERROR, simuArilText); setComplete(false); expandSection(SEC_LAUNCHING_SETUP); } } if (!EMPTY_STRING.equals(simuSeedText.getText())) { try { // long simuSeed = Long.parseLong(simuSeedText.getText()); } catch (NumberFormatException e) { modelEditor.addErrorMessage("simuSeed1", "The simulation aril must be a positive integer", this.getId(), IMessageProvider.ERROR, simuSeedText); expandSection(SEC_LAUNCHING_SETUP); setComplete(false); } } // get data binding manager DataBindingManager dm = getDataBindingManager(); // check the model values TypedSet modelValuesSet = TypedSet.parseSet(FormHelper .trimTrailingSpaces(modelValuesSource.getDocument().get())); if (modelValuesSet.getValueCount() > 0) { // there were values defined // check if those are numbers? /* * if (modelValuesSet.hasANumberOnlyValue()) { * mm.addMessage("modelValues1", * "A model value can not be an number", modelValuesSet, * IMessageProvider.ERROR, modelValuesSource.getControl()); * setComplete(false); } */ List values = modelValuesSet.getValuesAsList(); // check list of model values if these are already used validateUsage(MODEL_PARAMETER_MODEL_VALUES, values, "modelValues2_", "A model value", "Advanced Model Values", true); // check whether the model values are valid ids validateId(MODEL_PARAMETER_MODEL_VALUES, values, "modelValues2_", "A model value"); // get widget for model values Control widget = UIHelper.getWidget(dm.getAttributeControl(MODEL_PARAMETER_MODEL_VALUES)); // check if model values are config file keywords for (int j = 0; j < values.size(); j++) { String value = (String) values.get(j); if (SemanticHelper.isConfigFileKeyword(value)) { modelEditor.addErrorMessage(value, "The toolbox cannot handle the model value " + value + ".", this .getId(), IMessageProvider.ERROR, widget); setComplete(false); } } } // opDefNodes necessary for determining if a definition in definition // overrides is still in the specification SpecObj specObj = ToolboxHandle.getCurrentSpec().getValidRootModule(); OpDefNode[] opDefNodes = null; if (specObj != null) { opDefNodes = specObj.getExternalModuleTable().getRootModule().getOpDefs(); } Hashtable nodeTable = new Hashtable(); if (opDefNodes != null) { for (int j = 0; j < opDefNodes.length; j++) { String key = opDefNodes[j].getName().toString(); nodeTable.put(key, opDefNodes[j]); } } // get widget for definition overrides Control widget = UIHelper.getWidget(dm.getAttributeControl(MODEL_PARAMETER_DEFINITIONS)); // check the definition overrides List definitions = (List) definitionsTable.getInput(); for (int i = 0; i < definitions.size(); i++) { Assignment definition = (Assignment) definitions.get(i); List values = Arrays.asList(definition.getParams()); // check list of parameters validateUsage(MODEL_PARAMETER_DEFINITIONS, values, "param1_", "A parameter name", "Definition Overrides", false); // check whether the parameters are valid ids validateId(MODEL_PARAMETER_DEFINITIONS, values, "param1_", "A parameter name"); // The following if test was added by LL on 11 Nov 2009 to prevent an unparsed // file from producing bogus error messages saying that overridden definitions // have been removed from the spec. if (opDefNodes != null) { // check if definition still appears in root module if (!nodeTable.containsKey(definition.getLabel())) { // the following would remove // the definition override from the table // right now, an error message appears instead // definitions.remove(i); // definitionsTable.setInput(definitions); // dm.getSection(DEF_OVERRIDES_PART).markDirty(); modelEditor.addErrorMessage(definition.getLabel(), "The defined symbol " + definition.getLabel().substring(definition.getLabel().lastIndexOf("!") + 1) + " has been removed from the specification." + " It must be removed from the list of definition overrides.", this.getId(), IMessageProvider.ERROR, widget); setComplete(false); } else { // add error message if the number of parameters has changed OpDefNode opDefNode = (OpDefNode) nodeTable.get(definition.getLabel()); if (opDefNode.getSource().getNumberOfArgs() != definition.getParams().length) { modelEditor.addErrorMessage(definition.getLabel(), "Edit the definition override for " + opDefNode.getSource().getName() + " to match the correct number of arguments.", this .getId(), IMessageProvider.ERROR, widget); setComplete(false); } } } } for (int j = 0; j < definitions.size(); j++) { Assignment definition = (Assignment) definitions.get(j); String label = definition.getLabel(); if (SemanticHelper.isConfigFileKeyword(label)) { modelEditor.addErrorMessage(label, "The toolbox cannot override the definition of " + label + " because it is a configuration file keyword.", this.getId(), IMessageProvider.ERROR, widget); setComplete(false); } } // check if the view field contains a cfg file keyword Control viewWidget = UIHelper.getWidget(dm.getAttributeControl(MODEL_PARAMETER_VIEW)); String viewString = FormHelper.trimTrailingSpaces(viewSource.getDocument().get()); if (SemanticHelper.containsConfigFileKeyword(viewString)) { modelEditor.addErrorMessage(viewString, "The toolbox cannot handle the string " + viewString + " because it contains a configuration file keyword.", this.getId(), IMessageProvider.ERROR, viewWidget); setComplete(false); } mm.setAutoUpdate(true); super.validatePage(switchToErrorPage); } /** * Creates the UI */ protected void createBodyContent(IManagedForm managedForm) { DataBindingManager dm = getDataBindingManager(); int sectionFlags = Section.TITLE_BAR | Section.DESCRIPTION | Section.TREE_NODE; FormToolkit toolkit = managedForm.getToolkit(); Composite body = managedForm.getForm().getBody(); GridData gd; TableWrapData twd; // left Composite left = toolkit.createComposite(body); twd = new TableWrapData(TableWrapData.FILL_GRAB); twd.grabHorizontal = true; left.setLayout(new GridLayout(1, false)); left.setLayoutData(twd); // right Composite right = toolkit.createComposite(body); twd = new TableWrapData(TableWrapData.FILL_GRAB); twd.grabHorizontal = true; right.setLayoutData(twd); right.setLayout(new GridLayout(1, false)); Section section; // --------------------------------------------------------------- // new definitions section = FormHelper .createSectionComposite( left, "Additional Definitions", "Definitions required for the model checking, in addition to the definitions in the specification modules.", toolkit, sectionFlags, getExpansionListener()); ValidateableSectionPart newDefinitionsPart = new ValidateableSectionPart(section, this, SEC_NEW_DEFINITION); managedForm.addPart(newDefinitionsPart); DirtyMarkingListener newDefinitionsListener = new DirtyMarkingListener(newDefinitionsPart, true); gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 3; section.setLayoutData(gd); Composite newDefinitionsArea = (Composite) section.getClient(); newDefinitionsSource = FormHelper.createFormsSourceViewer(toolkit, newDefinitionsArea, SWT.V_SCROLL); // layout of the source viewer twd = new TableWrapData(TableWrapData.FILL); twd.heightHint = 60; twd.grabHorizontal = true; newDefinitionsSource.getTextWidget().setLayoutData(twd); newDefinitionsSource.addTextListener(newDefinitionsListener); dm.bindAttribute(MODEL_PARAMETER_NEW_DEFINITIONS, newDefinitionsSource, newDefinitionsPart); // --------------------------------------------------------------- // definition overwrite ValidateableOverridesSectionPart definitionsPart = new ValidateableOverridesSectionPart(right, "Definition Override", "Directs TLC to use alternate definitions for operators.", toolkit, sectionFlags, this); managedForm.addPart(definitionsPart); // layout gd = new GridData(GridData.FILL_HORIZONTAL); definitionsPart.getSection().setLayoutData(gd); gd = new GridData(GridData.FILL_BOTH); gd.widthHint = 100; gd.verticalSpan = 3; definitionsPart.getTableViewer().getTable().setLayoutData(gd); definitionsTable = definitionsPart.getTableViewer(); dm.bindAttribute(MODEL_PARAMETER_DEFINITIONS, definitionsTable, definitionsPart); // --------------------------------------------------------------- // constraint section = FormHelper.createSectionComposite(left, "State Constraint", "A state constraint is a formula restricting the possible states by a state predicate.", toolkit, sectionFlags, getExpansionListener()); ValidateableSectionPart constraintPart = new ValidateableSectionPart(section, this, SEC_STATE_CONSTRAINT); managedForm.addPart(constraintPart); DirtyMarkingListener constraintListener = new DirtyMarkingListener(constraintPart, true); gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 3; section.setLayoutData(gd); Composite constraintArea = (Composite) section.getClient(); constraintSource = FormHelper.createFormsSourceViewer(toolkit, constraintArea, SWT.V_SCROLL); // layout of the source viewer twd = new TableWrapData(TableWrapData.FILL); twd.heightHint = 60; twd.grabHorizontal = true; constraintSource.getTextWidget().setLayoutData(twd); constraintSource.addTextListener(constraintListener); dm.bindAttribute(MODEL_PARAMETER_CONSTRAINT, constraintSource, constraintPart); // --------------------------------------------------------------- // action constraint section = FormHelper.createSectionComposite(right, "Action Constraint", "An action constraint is a formula restricting the possible transitions.", toolkit, sectionFlags, getExpansionListener()); ValidateableSectionPart actionConstraintPart = new ValidateableSectionPart(section, this, SEC_ACTION_CONSTRAINT); managedForm.addPart(actionConstraintPart); DirtyMarkingListener actionConstraintListener = new DirtyMarkingListener(actionConstraintPart, true); gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 3; section.setLayoutData(gd); Composite actionConstraintArea = (Composite) section.getClient(); actionConstraintSource = FormHelper.createFormsSourceViewer(toolkit, actionConstraintArea, SWT.V_SCROLL); // layout of the source viewer twd = new TableWrapData(TableWrapData.FILL); twd.heightHint = 60; twd.grabHorizontal = true; actionConstraintSource.getTextWidget().setLayoutData(twd); actionConstraintSource.addTextListener(actionConstraintListener); dm.bindAttribute(MODEL_PARAMETER_ACTION_CONSTRAINT, actionConstraintSource, actionConstraintPart); // --------------------------------------------------------------- // modelValues section = FormHelper.createSectionComposite(left, "Model Values", "An additional set of model values.", toolkit, sectionFlags, getExpansionListener()); ValidateableSectionPart modelValuesPart = new ValidateableSectionPart(section, this, SEC_MODEL_VALUES); managedForm.addPart(modelValuesPart); DirtyMarkingListener modelValuesListener = new DirtyMarkingListener(modelValuesPart, true); gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 3; section.setLayoutData(gd); Composite modelValueArea = (Composite) section.getClient(); modelValuesSource = FormHelper.createFormsSourceViewer(toolkit, modelValueArea, SWT.V_SCROLL); // layout of the source viewer twd = new TableWrapData(TableWrapData.FILL); twd.heightHint = 60; twd.grabHorizontal = true; modelValuesSource.getTextWidget().setLayoutData(twd); modelValuesSource.addTextListener(modelValuesListener); dm.bindAttribute(MODEL_PARAMETER_MODEL_VALUES, modelValuesSource, modelValuesPart); // --------------------------------------------------------------- // launch section = createAdvancedLaunchSection(toolkit, right, sectionFlags); ValidateableSectionPart launchPart = new ValidateableSectionPart(section, this, SEC_LAUNCHING_SETUP); managedForm.addPart(launchPart); DirtyMarkingListener launchListener = new DirtyMarkingListener(launchPart, true); dm.bindAttribute(MODEL_PARAMETER_VIEW, viewSource, launchPart); // dirty listeners simuArilText.addModifyListener(launchListener); simuSeedText.addModifyListener(launchListener); simuDepthText.addModifyListener(launchListener); dfidDepthText.addModifyListener(launchListener); simulationOption.addSelectionListener(launchListener); dfidOption.addSelectionListener(launchListener); mcOption.addSelectionListener(launchListener); viewSource.addTextListener(launchListener); // add section ignoring listeners dirtyPartListeners.add(newDefinitionsListener); dirtyPartListeners.add(actionConstraintListener); dirtyPartListeners.add(modelValuesListener); dirtyPartListeners.add(constraintListener); dirtyPartListeners.add(launchListener); } /** * @param toolkit * @param parent * @param flags */ private Section createAdvancedLaunchSection(FormToolkit toolkit, Composite parent, int sectionFlags) { GridData gd; // advanced section Section advancedSection = FormHelper.createSectionComposite(parent, "TLC Options", "Advanced settings of the TLC model checker", toolkit, sectionFlags, getExpansionListener()); gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 2; gd.grabExcessHorizontalSpace = true; advancedSection.setLayoutData(gd); Composite area = (Composite) advancedSection.getClient(); area.setLayout(new GridLayout(2, false)); mcOption = toolkit.createButton(area, "Model-checking mode", SWT.RADIO); gd = new GridData(); gd.horizontalSpan = 2; mcOption.setLayoutData(gd); // label view FormText viewLabel = toolkit.createFormText(area, true); viewLabel.setText("View:", false, false); gd = new GridData(); gd.verticalAlignment = SWT.BEGINNING; gd.horizontalIndent = 10; viewLabel.setLayoutData(gd); // field view viewSource = FormHelper.createFormsSourceViewer(toolkit, area, SWT.V_SCROLL); // layout of the source viewer gd = new GridData(GridData.FILL_HORIZONTAL); gd.grabExcessHorizontalSpace = true; gd.heightHint = 60; gd.widthHint = 200; viewSource.getTextWidget().setLayoutData(gd); dfidOption = toolkit.createButton(area, "Depth-first", SWT.CHECK); gd = new GridData(); gd.horizontalSpan = 2; gd.horizontalIndent = 10; dfidOption.setLayoutData(gd); // label depth FormText dfidDepthLabel = toolkit.createFormText(area, true); dfidDepthLabel.setText("Depth:", false, false); gd = new GridData(); gd.horizontalIndent = 10; dfidDepthLabel.setLayoutData(gd); // field depth dfidDepthText = toolkit.createText(area, "100"); gd = new GridData(); gd.widthHint = 100; dfidDepthText.setLayoutData(gd); simulationOption = toolkit.createButton(area, "Simulation mode", SWT.RADIO); gd = new GridData(); gd.horizontalSpan = 2; simulationOption.setLayoutData(gd); // label depth FormText depthLabel = toolkit.createFormText(area, true); depthLabel.setText("Maximum length of the trace:", false, false); gd = new GridData(); gd.horizontalIndent = 10; depthLabel.setLayoutData(gd); // field depth simuDepthText = toolkit.createText(area, "100"); gd = new GridData(); gd.widthHint = 100; simuDepthText.setLayoutData(gd); // label seed FormText seedLabel = toolkit.createFormText(area, true); seedLabel.setText("Seed:", false, false); gd = new GridData(); gd.horizontalIndent = 10; seedLabel.setLayoutData(gd); // field seed simuSeedText = toolkit.createText(area, ""); gd = new GridData(); gd.widthHint = 200; simuSeedText.setLayoutData(gd); // label seed FormText arilLabel = toolkit.createFormText(area, true); arilLabel.setText("Aril:", false, false); gd = new GridData(); gd.horizontalIndent = 10; arilLabel.setLayoutData(gd); // field seed simuArilText = toolkit.createText(area, ""); gd = new GridData(); gd.widthHint = 200; simuArilText.setLayoutData(gd); return advancedSection; } }
Comments. git-svn-id: 7acc490bd371dbc82047a939b87dc892fdc31f59@15147 76a6fc44-f60b-0410-a9a8-e67b0e8fc65c
org.lamport.tla.toolbox.tool.tlc.ui/src/org/lamport/tla/toolbox/tool/tlc/ui/editor/page/AdvancedModelPage.java
Comments.
Java
agpl-3.0
9764ffc85145c1d414ddf181bd6263e263aebe04
0
ngaut/sql-layer,jaytaylor/sql-layer,jaytaylor/sql-layer,relateiq/sql-layer,shunwang/sql-layer-1,jaytaylor/sql-layer,relateiq/sql-layer,wfxiang08/sql-layer-1,relateiq/sql-layer,jaytaylor/sql-layer,qiuyesuifeng/sql-layer,wfxiang08/sql-layer-1,ngaut/sql-layer,relateiq/sql-layer,ngaut/sql-layer,wfxiang08/sql-layer-1,qiuyesuifeng/sql-layer,ngaut/sql-layer,qiuyesuifeng/sql-layer,shunwang/sql-layer-1,shunwang/sql-layer-1,shunwang/sql-layer-1,qiuyesuifeng/sql-layer,wfxiang08/sql-layer-1
/** * END USER LICENSE AGREEMENT (“EULA”) * * READ THIS AGREEMENT CAREFULLY (date: 9/13/2011): * http://www.akiban.com/licensing/20110913 * * BY INSTALLING OR USING ALL OR ANY PORTION OF THE SOFTWARE, YOU ARE ACCEPTING * ALL OF THE TERMS AND CONDITIONS OF THIS AGREEMENT. YOU AGREE THAT THIS * AGREEMENT IS ENFORCEABLE LIKE ANY WRITTEN AGREEMENT SIGNED BY YOU. * * IF YOU HAVE PAID A LICENSE FEE FOR USE OF THE SOFTWARE AND DO NOT AGREE TO * THESE TERMS, YOU MAY RETURN THE SOFTWARE FOR A FULL REFUND PROVIDED YOU (A) DO * NOT USE THE SOFTWARE AND (B) RETURN THE SOFTWARE WITHIN THIRTY (30) DAYS OF * YOUR INITIAL PURCHASE. * * IF YOU WISH TO USE THE SOFTWARE AS AN EMPLOYEE, CONTRACTOR, OR AGENT OF A * CORPORATION, PARTNERSHIP OR SIMILAR ENTITY, THEN YOU MUST BE AUTHORIZED TO SIGN * FOR AND BIND THE ENTITY IN ORDER TO ACCEPT THE TERMS OF THIS AGREEMENT. THE * LICENSES GRANTED UNDER THIS AGREEMENT ARE EXPRESSLY CONDITIONED UPON ACCEPTANCE * BY SUCH AUTHORIZED PERSONNEL. * * IF YOU HAVE ENTERED INTO A SEPARATE WRITTEN LICENSE AGREEMENT WITH AKIBAN FOR * USE OF THE SOFTWARE, THE TERMS AND CONDITIONS OF SUCH OTHER AGREEMENT SHALL * PREVAIL OVER ANY CONFLICTING TERMS OR CONDITIONS IN THIS AGREEMENT. */ package com.akiban.sql.aisddl; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; import com.akiban.ais.AISCloner; import com.akiban.ais.model.Columnar; import com.akiban.ais.protobuf.ProtobufWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.akiban.server.api.DDLFunctions; import com.akiban.server.error.IndexTableNotInGroupException; import com.akiban.server.error.IndistinguishableIndexException; import com.akiban.server.error.MissingGroupIndexJoinTypeException; import com.akiban.server.error.NoSuchColumnException; import com.akiban.server.error.NoSuchGroupException; import com.akiban.server.error.NoSuchIndexException; import com.akiban.server.error.NoSuchTableException; import com.akiban.server.error.TableIndexJoinTypeException; import com.akiban.server.error.UnsupportedGroupIndexJoinTypeException; import com.akiban.server.error.UnsupportedSQLException; import com.akiban.server.error.UnsupportedUniqueGroupIndexException; import com.akiban.server.service.session.Session; import com.akiban.sql.parser.CreateIndexNode; import com.akiban.sql.parser.DropIndexNode; import com.akiban.sql.parser.IndexColumn; import com.akiban.sql.parser.RenameNode; import com.akiban.sql.parser.SpecialIndexFuncNode; import com.akiban.ais.model.AISBuilder; import com.akiban.ais.model.AkibanInformationSchema; import com.akiban.ais.model.Column; import com.akiban.ais.model.Group; import com.akiban.ais.model.Index; import com.akiban.ais.model.IndexName; import com.akiban.ais.model.TableIndex; import com.akiban.ais.model.TableName; import com.akiban.ais.model.UserTable; import com.akiban.server.error.InvalidOperationException; import com.akiban.sql.parser.ExistenceCheck; import com.akiban.sql.pg.PostgresQueryContext; /** DDL operations on Indices */ public class IndexDDL { private static final Logger logger = LoggerFactory.getLogger(IndexDDL.class); private IndexDDL() { } private static boolean returnHere(ExistenceCheck condition, InvalidOperationException error, PostgresQueryContext context) { switch(condition) { case IF_EXISTS: // doesn't exist, does nothing context.warnClient(error); return true; case NO_CONDITION: throw error; default: throw new IllegalStateException("Unexpected condition in DROP INDEX: " + condition); } } public static void dropIndex (DDLFunctions ddlFunctions, Session session, String defaultSchemaName, DropIndexNode dropIndex, PostgresQueryContext context) { String groupName = null; TableName tableName = null; ExistenceCheck condition = dropIndex.getExistenceCheck(); final String indexSchemaName = dropIndex.getObjectName() != null && dropIndex.getObjectName().getSchemaName() != null ? dropIndex.getObjectName().getSchemaName() : null; final String indexTableName = dropIndex.getObjectName() != null && dropIndex.getObjectName().getTableName() != null ? dropIndex.getObjectName().getTableName() : null; final String indexName = dropIndex.getIndexName(); List<String> indexesToDrop = Collections.singletonList(indexName); // if the user supplies the table for the index, look only there if (indexTableName != null) { tableName = TableName.create(indexSchemaName == null ? defaultSchemaName : indexSchemaName, indexTableName); UserTable table = ddlFunctions.getAIS(session).getUserTable(tableName); if (table == null) { if(returnHere(condition, new NoSuchTableException(tableName), context)) return; } // if we can't find the index, set tableName to null // to flag not a user table index. if (table.getIndex(indexName) == null) { tableName = null; } // Check the group associated to the table for the // same index name. Group group = table.getGroup(); if (group.getIndex(indexName) != null) { // Table and it's group share an index name, we're confused. if (tableName != null) { throw new IndistinguishableIndexException(indexName); } // else flag group index for dropping groupName = group.getName(); } } // the user has not supplied a table name for the index to drop, // scan all groups/tables for the index name else { for (UserTable table : ddlFunctions.getAIS(session).getUserTables().values()) { if (indexSchemaName != null && !table.getName().getSchemaName().equalsIgnoreCase(indexSchemaName)) { continue; } if (table.getIndex(indexName) != null) { if (tableName == null) { tableName = table.getName(); } else { throw new IndistinguishableIndexException(indexName); } } } for (Group table : ddlFunctions.getAIS(session).getGroups().values()) { if (table.getIndex(indexName) != null) { if (tableName == null && groupName == null) { groupName = table.getName(); } else { throw new IndistinguishableIndexException(indexName); } } } } if (groupName != null) { ddlFunctions.dropGroupIndexes(session, groupName, indexesToDrop); } else if (tableName != null) { ddlFunctions.dropTableIndexes(session, tableName, indexesToDrop); } else { if(returnHere(condition, new NoSuchIndexException (indexName), context)) return; } } public static void renameIndex (DDLFunctions ddlFunctions, Session session, String defaultSchemaName, RenameNode renameIndex) { throw new UnsupportedSQLException (renameIndex.statementToString(), renameIndex); } public static void createIndex(DDLFunctions ddlFunctions, Session session, String defaultSchemaName, CreateIndexNode createIndex) { AkibanInformationSchema ais = ddlFunctions.getAIS(session); Collection<Index> indexesToAdd = new LinkedList<Index>(); indexesToAdd.add(buildIndex(ais, defaultSchemaName, createIndex)); ddlFunctions.createIndexes(session, indexesToAdd); // TODO: This is not real but just enough to make isSpatial() return true. if (createIndex.getColumnList() instanceof SpecialIndexFuncNode) { ais = ddlFunctions.getAIS(session); IndexName indexName = indexesToAdd.iterator().next().getIndexName(); TableIndex index = ais.getTable(indexName.getSchemaName(), indexName.getTableName()) .getIndex(indexName.getName()); switch (((SpecialIndexFuncNode)createIndex.getColumnList()).getFunctionType()) { case Z_ORDER_LAT_LON: index.spatialIndexDimensions(new long[] { 0, 0 }, new long[] { 100, 100 }); assert index.isSpatial() : index; break; } } } private static Index buildIndex (AkibanInformationSchema ais, String defaultSchemaName, CreateIndexNode index) { final String schemaName = index.getObjectName().getSchemaName() != null ? index.getObjectName().getSchemaName() : defaultSchemaName; final TableName tableName = TableName.create(schemaName, index.getIndexTableName().getTableName()); if (checkIndexType (index, tableName) == Index.IndexType.TABLE) { logger.info ("Building Table index on table {}", tableName); return buildTableIndex (ais, tableName, index); } else { logger.info ("Building Group index on table {}", tableName); return buildGroupIndex (ais, tableName, index); } } /** * Check if the index specification is for a table index or a group index. We distinguish between * them by checking the columns specified in the index, if they all belong to the table * in the "ON" clause, this is a table index, else it is a group index. * @param index AST for index to check * @param tableName ON clause table name * @return IndexType (GROUP or TABLE). */ private static Index.IndexType checkIndexType(CreateIndexNode index, TableName tableName) { for (IndexColumn col : index.getColumnList()) { // if the column has no table name (e.g. "col1") OR // there is a table name (e.g. "schema1.table1.col1" or "table1.col1") // if the table name has a schema it matches, else assume it's the same as the table // and the table name match the index table. if (col.getTableName() == null || ((col.getTableName().hasSchema() && col.getTableName().getSchemaName().equalsIgnoreCase(tableName.getSchemaName()) || !col.getTableName().hasSchema()) && col.getTableName().getTableName().equalsIgnoreCase(tableName.getTableName()))){ ; // Column is in the base table, check the next } else { return Index.IndexType.GROUP; } } return Index.IndexType.TABLE; } private static Index buildTableIndex (AkibanInformationSchema ais, TableName tableName, CreateIndexNode index) { final String indexName = index.getObjectName().getTableName(); UserTable table = ais.getUserTable(tableName); if (table == null) { throw new NoSuchTableException (tableName); } if (index.getJoinType() != null) { throw new TableIndexJoinTypeException(); } AISBuilder builder = new AISBuilder(); addGroup (builder, ais, table.getGroup().getName()); builder.index(tableName.getSchemaName(), tableName.getTableName(), indexName, index.getUniqueness(), index.getUniqueness() ? Index.UNIQUE_KEY_CONSTRAINT : Index.KEY_CONSTRAINT); int i = 0; for (IndexColumn col : index.getColumnList()) { Column tableCol = ais.getTable(tableName).getColumn(col.getColumnName()); if (tableCol == null) { throw new NoSuchColumnException (col.getColumnName()); } builder.indexColumn(tableName.getSchemaName(), tableName.getTableName(), indexName, tableCol.getName(), i, col.isAscending(), null); i++; } builder.basicSchemaIsComplete(); return builder.akibanInformationSchema().getTable(tableName).getIndex(indexName); } private static Index buildGroupIndex (AkibanInformationSchema ais, TableName tableName, CreateIndexNode index) { final String indexName = index.getObjectName().getTableName(); if (ais.getUserTable(tableName) == null) { throw new NoSuchTableException (tableName); } final String groupName = ais.getUserTable(tableName).getGroup().getName(); if (ais.getGroup(groupName) == null) { throw new NoSuchGroupException(groupName); } // TODO: Remove this check when the PSSM index creation does AIS.validate() // which is the correct approach. if (index.getUniqueness()) { throw new UnsupportedUniqueGroupIndexException (indexName); } Index.JoinType joinType = null; if (index.getJoinType() == null) { throw new MissingGroupIndexJoinTypeException(); } else { switch (index.getJoinType()) { case LEFT_OUTER: joinType = Index.JoinType.LEFT; break; case RIGHT_OUTER: joinType = Index.JoinType.RIGHT; break; case INNER: if (false) { // TODO: Not yet supported; falls through to error. // joinType = Index.JoinType.INNER; break; } default: throw new UnsupportedGroupIndexJoinTypeException(index.getJoinType().toString()); } } AISBuilder builder = new AISBuilder(); addGroup(builder, ais, groupName); builder.groupIndex(groupName, indexName, index.getUniqueness(), joinType); int i = 0; String schemaName; TableName columnTable; for (IndexColumn col : index.getColumnList()) { if (col.getTableName() != null) { schemaName = col.getTableName().hasSchema() ? col.getTableName().getSchemaName() : tableName.getSchemaName(); columnTable = TableName.create(schemaName, col.getTableName().getTableName()); } else { columnTable = tableName; schemaName = tableName.getSchemaName(); } final String columnName = col.getColumnName(); if (ais.getUserTable(columnTable) == null) { throw new NoSuchTableException(columnTable); } if (ais.getUserTable(columnTable).getGroup().getName() != groupName) throw new IndexTableNotInGroupException(indexName, columnName, columnTable.getTableName()); Column tableCol = ais.getUserTable(columnTable).getColumn(columnName); if (tableCol == null) { throw new NoSuchColumnException (col.getColumnName()); } builder.groupIndexColumn(groupName, indexName, schemaName, columnTable.getTableName(), columnName, i); i++; } builder.basicSchemaIsComplete(); return builder.akibanInformationSchema().getGroup(groupName).getIndex(indexName); } private static void addGroup (AISBuilder builder, AkibanInformationSchema ais, final String groupName) { AISCloner.clone( builder.akibanInformationSchema(), ais, new ProtobufWriter.TableSelector() { @Override public boolean isSelected(Columnar columnar) { if(!columnar.isTable()) { return false; } UserTable table = (UserTable)columnar; return table.getGroup().getName().equalsIgnoreCase(groupName); } } ); } }
src/main/java/com/akiban/sql/aisddl/IndexDDL.java
/** * END USER LICENSE AGREEMENT (“EULA”) * * READ THIS AGREEMENT CAREFULLY (date: 9/13/2011): * http://www.akiban.com/licensing/20110913 * * BY INSTALLING OR USING ALL OR ANY PORTION OF THE SOFTWARE, YOU ARE ACCEPTING * ALL OF THE TERMS AND CONDITIONS OF THIS AGREEMENT. YOU AGREE THAT THIS * AGREEMENT IS ENFORCEABLE LIKE ANY WRITTEN AGREEMENT SIGNED BY YOU. * * IF YOU HAVE PAID A LICENSE FEE FOR USE OF THE SOFTWARE AND DO NOT AGREE TO * THESE TERMS, YOU MAY RETURN THE SOFTWARE FOR A FULL REFUND PROVIDED YOU (A) DO * NOT USE THE SOFTWARE AND (B) RETURN THE SOFTWARE WITHIN THIRTY (30) DAYS OF * YOUR INITIAL PURCHASE. * * IF YOU WISH TO USE THE SOFTWARE AS AN EMPLOYEE, CONTRACTOR, OR AGENT OF A * CORPORATION, PARTNERSHIP OR SIMILAR ENTITY, THEN YOU MUST BE AUTHORIZED TO SIGN * FOR AND BIND THE ENTITY IN ORDER TO ACCEPT THE TERMS OF THIS AGREEMENT. THE * LICENSES GRANTED UNDER THIS AGREEMENT ARE EXPRESSLY CONDITIONED UPON ACCEPTANCE * BY SUCH AUTHORIZED PERSONNEL. * * IF YOU HAVE ENTERED INTO A SEPARATE WRITTEN LICENSE AGREEMENT WITH AKIBAN FOR * USE OF THE SOFTWARE, THE TERMS AND CONDITIONS OF SUCH OTHER AGREEMENT SHALL * PREVAIL OVER ANY CONFLICTING TERMS OR CONDITIONS IN THIS AGREEMENT. */ package com.akiban.sql.aisddl; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; import com.akiban.ais.AISCloner; import com.akiban.ais.model.Columnar; import com.akiban.ais.protobuf.ProtobufWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.akiban.server.api.DDLFunctions; import com.akiban.server.error.IndexTableNotInGroupException; import com.akiban.server.error.IndistinguishableIndexException; import com.akiban.server.error.MissingGroupIndexJoinTypeException; import com.akiban.server.error.NoSuchColumnException; import com.akiban.server.error.NoSuchGroupException; import com.akiban.server.error.NoSuchIndexException; import com.akiban.server.error.NoSuchTableException; import com.akiban.server.error.TableIndexJoinTypeException; import com.akiban.server.error.UnsupportedGroupIndexJoinTypeException; import com.akiban.server.error.UnsupportedSQLException; import com.akiban.server.error.UnsupportedUniqueGroupIndexException; import com.akiban.server.service.session.Session; import com.akiban.sql.parser.CreateIndexNode; import com.akiban.sql.parser.DropIndexNode; import com.akiban.sql.parser.IndexColumn; import com.akiban.sql.parser.RenameNode; import com.akiban.ais.model.AISBuilder; import com.akiban.ais.model.AkibanInformationSchema; import com.akiban.ais.model.Column; import com.akiban.ais.model.Group; import com.akiban.ais.model.Index; import com.akiban.ais.model.TableName; import com.akiban.ais.model.UserTable; import com.akiban.server.error.InvalidOperationException; import com.akiban.sql.parser.ExistenceCheck; import com.akiban.sql.pg.PostgresQueryContext; /** DDL operations on Indices */ public class IndexDDL { private static final Logger logger = LoggerFactory.getLogger(IndexDDL.class); private IndexDDL() { } private static boolean returnHere(ExistenceCheck condition, InvalidOperationException error, PostgresQueryContext context) { switch(condition) { case IF_EXISTS: // doesn't exist, does nothing context.warnClient(error); return true; case NO_CONDITION: throw error; default: throw new IllegalStateException("Unexpected condition in DROP INDEX: " + condition); } } public static void dropIndex (DDLFunctions ddlFunctions, Session session, String defaultSchemaName, DropIndexNode dropIndex, PostgresQueryContext context) { String groupName = null; TableName tableName = null; ExistenceCheck condition = dropIndex.getExistenceCheck(); final String indexSchemaName = dropIndex.getObjectName() != null && dropIndex.getObjectName().getSchemaName() != null ? dropIndex.getObjectName().getSchemaName() : null; final String indexTableName = dropIndex.getObjectName() != null && dropIndex.getObjectName().getTableName() != null ? dropIndex.getObjectName().getTableName() : null; final String indexName = dropIndex.getIndexName(); List<String> indexesToDrop = Collections.singletonList(indexName); // if the user supplies the table for the index, look only there if (indexTableName != null) { tableName = TableName.create(indexSchemaName == null ? defaultSchemaName : indexSchemaName, indexTableName); UserTable table = ddlFunctions.getAIS(session).getUserTable(tableName); if (table == null) { if(returnHere(condition, new NoSuchTableException(tableName), context)) return; } // if we can't find the index, set tableName to null // to flag not a user table index. if (table.getIndex(indexName) == null) { tableName = null; } // Check the group associated to the table for the // same index name. Group group = table.getGroup(); if (group.getIndex(indexName) != null) { // Table and it's group share an index name, we're confused. if (tableName != null) { throw new IndistinguishableIndexException(indexName); } // else flag group index for dropping groupName = group.getName(); } } // the user has not supplied a table name for the index to drop, // scan all groups/tables for the index name else { for (UserTable table : ddlFunctions.getAIS(session).getUserTables().values()) { if (indexSchemaName != null && !table.getName().getSchemaName().equalsIgnoreCase(indexSchemaName)) { continue; } if (table.getIndex(indexName) != null) { if (tableName == null) { tableName = table.getName(); } else { throw new IndistinguishableIndexException(indexName); } } } for (Group table : ddlFunctions.getAIS(session).getGroups().values()) { if (table.getIndex(indexName) != null) { if (tableName == null && groupName == null) { groupName = table.getName(); } else { throw new IndistinguishableIndexException(indexName); } } } } if (groupName != null) { ddlFunctions.dropGroupIndexes(session, groupName, indexesToDrop); } else if (tableName != null) { ddlFunctions.dropTableIndexes(session, tableName, indexesToDrop); } else { if(returnHere(condition, new NoSuchIndexException (indexName), context)) return; } } public static void renameIndex (DDLFunctions ddlFunctions, Session session, String defaultSchemaName, RenameNode renameIndex) { throw new UnsupportedSQLException (renameIndex.statementToString(), renameIndex); } public static void createIndex(DDLFunctions ddlFunctions, Session session, String defaultSchemaName, CreateIndexNode createIndex) { AkibanInformationSchema ais = ddlFunctions.getAIS(session); Collection<Index> indexesToAdd = new LinkedList<Index>(); indexesToAdd.add(buildIndex(ais, defaultSchemaName, createIndex)); ddlFunctions.createIndexes(session, indexesToAdd); } private static Index buildIndex (AkibanInformationSchema ais, String defaultSchemaName, CreateIndexNode index) { final String schemaName = index.getObjectName().getSchemaName() != null ? index.getObjectName().getSchemaName() : defaultSchemaName; final TableName tableName = TableName.create(schemaName, index.getIndexTableName().getTableName()); if (checkIndexType (index, tableName) == Index.IndexType.TABLE) { logger.info ("Building Table index on table {}", tableName); return buildTableIndex (ais, tableName, index); } else { logger.info ("Building Group index on table {}", tableName); return buildGroupIndex (ais, tableName, index); } } /** * Check if the index specification is for a table index or a group index. We distinguish between * them by checking the columns specified in the index, if they all belong to the table * in the "ON" clause, this is a table index, else it is a group index. * @param index AST for index to check * @param tableName ON clause table name * @return IndexType (GROUP or TABLE). */ private static Index.IndexType checkIndexType(CreateIndexNode index, TableName tableName) { for (IndexColumn col : index.getColumnList()) { // if the column has no table name (e.g. "col1") OR // there is a table name (e.g. "schema1.table1.col1" or "table1.col1") // if the table name has a schema it matches, else assume it's the same as the table // and the table name match the index table. if (col.getTableName() == null || ((col.getTableName().hasSchema() && col.getTableName().getSchemaName().equalsIgnoreCase(tableName.getSchemaName()) || !col.getTableName().hasSchema()) && col.getTableName().getTableName().equalsIgnoreCase(tableName.getTableName()))){ ; // Column is in the base table, check the next } else { return Index.IndexType.GROUP; } } return Index.IndexType.TABLE; } private static Index buildTableIndex (AkibanInformationSchema ais, TableName tableName, CreateIndexNode index) { final String indexName = index.getObjectName().getTableName(); UserTable table = ais.getUserTable(tableName); if (table == null) { throw new NoSuchTableException (tableName); } if (index.getJoinType() != null) { throw new TableIndexJoinTypeException(); } AISBuilder builder = new AISBuilder(); addGroup (builder, ais, table.getGroup().getName()); builder.index(tableName.getSchemaName(), tableName.getTableName(), indexName, index.getUniqueness(), index.getUniqueness() ? Index.UNIQUE_KEY_CONSTRAINT : Index.KEY_CONSTRAINT); int i = 0; for (IndexColumn col : index.getColumnList()) { Column tableCol = ais.getTable(tableName).getColumn(col.getColumnName()); if (tableCol == null) { throw new NoSuchColumnException (col.getColumnName()); } builder.indexColumn(tableName.getSchemaName(), tableName.getTableName(), indexName, tableCol.getName(), i, col.isAscending(), null); i++; } builder.basicSchemaIsComplete(); return builder.akibanInformationSchema().getTable(tableName).getIndex(indexName); } private static Index buildGroupIndex (AkibanInformationSchema ais, TableName tableName, CreateIndexNode index) { final String indexName = index.getObjectName().getTableName(); if (ais.getUserTable(tableName) == null) { throw new NoSuchTableException (tableName); } final String groupName = ais.getUserTable(tableName).getGroup().getName(); if (ais.getGroup(groupName) == null) { throw new NoSuchGroupException(groupName); } // TODO: Remove this check when the PSSM index creation does AIS.validate() // which is the correct approach. if (index.getUniqueness()) { throw new UnsupportedUniqueGroupIndexException (indexName); } Index.JoinType joinType = null; if (index.getJoinType() == null) { throw new MissingGroupIndexJoinTypeException(); } else { switch (index.getJoinType()) { case LEFT_OUTER: joinType = Index.JoinType.LEFT; break; case RIGHT_OUTER: joinType = Index.JoinType.RIGHT; break; case INNER: if (false) { // TODO: Not yet supported; falls through to error. // joinType = Index.JoinType.INNER; break; } default: throw new UnsupportedGroupIndexJoinTypeException(index.getJoinType().toString()); } } AISBuilder builder = new AISBuilder(); addGroup(builder, ais, groupName); builder.groupIndex(groupName, indexName, index.getUniqueness(), joinType); int i = 0; String schemaName; TableName columnTable; for (IndexColumn col : index.getColumnList()) { if (col.getTableName() != null) { schemaName = col.getTableName().hasSchema() ? col.getTableName().getSchemaName() : tableName.getSchemaName(); columnTable = TableName.create(schemaName, col.getTableName().getTableName()); } else { columnTable = tableName; schemaName = tableName.getSchemaName(); } final String columnName = col.getColumnName(); if (ais.getUserTable(columnTable) == null) { throw new NoSuchTableException(columnTable); } if (ais.getUserTable(columnTable).getGroup().getName() != groupName) throw new IndexTableNotInGroupException(indexName, columnName, columnTable.getTableName()); Column tableCol = ais.getUserTable(columnTable).getColumn(columnName); if (tableCol == null) { throw new NoSuchColumnException (col.getColumnName()); } builder.groupIndexColumn(groupName, indexName, schemaName, columnTable.getTableName(), columnName, i); i++; } builder.basicSchemaIsComplete(); return builder.akibanInformationSchema().getGroup(groupName).getIndex(indexName); } private static void addGroup (AISBuilder builder, AkibanInformationSchema ais, final String groupName) { AISCloner.clone( builder.akibanInformationSchema(), ais, new ProtobufWriter.TableSelector() { @Override public boolean isSelected(Columnar columnar) { if(!columnar.isTable()) { return false; } UserTable table = (UserTable)columnar; return table.getGroup().getName().equalsIgnoreCase(groupName); } } ); } }
Hack to make a spatial index. Space isn't right, isn't persisted in AIS, etc.
src/main/java/com/akiban/sql/aisddl/IndexDDL.java
Hack to make a spatial index. Space isn't right, isn't persisted in AIS, etc.
Java
agpl-3.0
5e3599821fc3218b56d2748c65bcee4045af3076
0
bihealth/cbioportal,onursumer/cbioportal,adamabeshouse/cbioportal,jjgao/cbioportal,d3b-center/pedcbioportal,angelicaochoa/cbioportal,jjgao/cbioportal,pughlab/cbioportal,zhx828/cbioportal,onursumer/cbioportal,yichaoS/cbioportal,gsun83/cbioportal,adamabeshouse/cbioportal,sheridancbio/cbioportal,angelicaochoa/cbioportal,gsun83/cbioportal,d3b-center/pedcbioportal,gsun83/cbioportal,adamabeshouse/cbioportal,cBioPortal/cbioportal,sheridancbio/cbioportal,n1zea144/cbioportal,zhx828/cbioportal,inodb/cbioportal,d3b-center/pedcbioportal,inodb/cbioportal,angelicaochoa/cbioportal,cBioPortal/cbioportal,n1zea144/cbioportal,onursumer/cbioportal,yichaoS/cbioportal,n1zea144/cbioportal,zhx828/cbioportal,d3b-center/pedcbioportal,jjgao/cbioportal,adamabeshouse/cbioportal,sheridancbio/cbioportal,pughlab/cbioportal,jjgao/cbioportal,angelicaochoa/cbioportal,bihealth/cbioportal,pughlab/cbioportal,angelicaochoa/cbioportal,bihealth/cbioportal,d3b-center/pedcbioportal,d3b-center/pedcbioportal,pughlab/cbioportal,n1zea144/cbioportal,inodb/cbioportal,inodb/cbioportal,inodb/cbioportal,adamabeshouse/cbioportal,yichaoS/cbioportal,bihealth/cbioportal,cBioPortal/cbioportal,onursumer/cbioportal,sheridancbio/cbioportal,cBioPortal/cbioportal,onursumer/cbioportal,zhx828/cbioportal,n1zea144/cbioportal,jjgao/cbioportal,yichaoS/cbioportal,zhx828/cbioportal,yichaoS/cbioportal,pughlab/cbioportal,yichaoS/cbioportal,pughlab/cbioportal,d3b-center/pedcbioportal,angelicaochoa/cbioportal,zhx828/cbioportal,cBioPortal/cbioportal,jjgao/cbioportal,zhx828/cbioportal,sheridancbio/cbioportal,bihealth/cbioportal,inodb/cbioportal,jjgao/cbioportal,cBioPortal/cbioportal,adamabeshouse/cbioportal,gsun83/cbioportal,sheridancbio/cbioportal,n1zea144/cbioportal,mandawilson/cbioportal,mandawilson/cbioportal,yichaoS/cbioportal,gsun83/cbioportal,mandawilson/cbioportal,n1zea144/cbioportal,mandawilson/cbioportal,gsun83/cbioportal,adamabeshouse/cbioportal,gsun83/cbioportal,bihealth/cbioportal,bihealth/cbioportal,mandawilson/cbioportal,mandawilson/cbioportal,onursumer/cbioportal,mandawilson/cbioportal,pughlab/cbioportal,angelicaochoa/cbioportal,inodb/cbioportal
/* * Copyright (c) 2015 Memorial Sloan-Kettering Cancer Center. * * This library 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. The software and documentation provided hereunder * is on an "as is" basis, and Memorial Sloan-Kettering Cancer Center has no * obligations to provide maintenance, support, updates, enhancements or * modifications. In no event shall Memorial Sloan-Kettering Cancer Center be * liable to any party for direct, indirect, special, incidental or * consequential damages, including lost profits, arising out of the use of this * software and its documentation, even if Memorial Sloan-Kettering Cancer * Center has been advised of the possibility of such damage. */ /* * This file is part of cBioPortal. * * cBioPortal is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.mskcc.cbio.portal.scripts; import org.mskcc.cbio.portal.dao.*; import org.mskcc.cbio.portal.model.*; import org.mskcc.cbio.portal.util.*; import org.apache.commons.lang.ArrayUtils; import org.apache.log4j.Logger; import java.io.*; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Code to Import Copy Number Alteration, MRNA Expression Data, Methylation, or protein RPPA data * * @author Ethan Cerami */ public class ImportTabDelimData { private HashSet<Long> importedGeneSet = new HashSet<Long>(); private File mutationFile; private String targetLine; private int geneticProfileId; private GeneticProfile geneticProfile; private int entriesSkipped = 0; private int nrExtraRecords = 0; private Set<String> arrayIdSet = new HashSet<String>(); /** * Constructor. * * @param dataFile Data File containing Copy Number Alteration, MRNA Expression Data, or protein RPPA data * @param targetLine The line we want to import. * If null, all lines are imported. * @param geneticProfileId GeneticProfile ID. * * @deprecated : TODO shall we deprecate this feature (i.e. the targetLine)? */ public ImportTabDelimData(File dataFile, String targetLine, int geneticProfileId) { this.mutationFile = dataFile; this.targetLine = targetLine; this.geneticProfileId = geneticProfileId; } /** * Constructor. * * @param dataFile Data File containing Copy Number Alteration, MRNA Expression Data, or protein RPPA data * @param geneticProfileId GeneticProfile ID. */ public ImportTabDelimData(File dataFile, int geneticProfileId) { this.mutationFile = dataFile; this.geneticProfileId = geneticProfileId; } /** * Import the Copy Number Alteration, MRNA Expression Data, or protein RPPA data * * @throws IOException IO Error. * @throws DaoException Database Error. */ public void importData(int numLines) throws IOException, DaoException { geneticProfile = DaoGeneticProfile.getGeneticProfileById(geneticProfileId); FileReader reader = new FileReader(mutationFile); BufferedReader buf = new BufferedReader(reader); String headerLine = buf.readLine(); String parts[] = headerLine.split("\t"); //Whether data regards CNA or RPPA: boolean discritizedCnaProfile = geneticProfile!=null && geneticProfile.getGeneticAlterationType() == GeneticAlterationType.COPY_NUMBER_ALTERATION && geneticProfile.showProfileInAnalysisTab(); boolean rppaProfile = geneticProfile!=null && geneticProfile.getGeneticAlterationType() == GeneticAlterationType.PROTEIN_LEVEL && "Composite.Element.Ref".equalsIgnoreCase(parts[0]); int numRecordsToAdd = 0; int samplesSkipped = 0; try { int hugoSymbolIndex = getHugoSymbolIndex(parts); int entrezGeneIdIndex = getEntrezGeneIdIndex(parts); int rppaGeneRefIndex = getRppaGeneRefIndex(parts); int sampleStartIndex = getStartIndex(parts, hugoSymbolIndex, entrezGeneIdIndex, rppaGeneRefIndex); if (rppaProfile) { if (rppaGeneRefIndex == -1) throw new RuntimeException("Error: the following column should be present for RPPA data: Composite.Element.Ref"); } else if (hugoSymbolIndex == -1 && entrezGeneIdIndex == -1) throw new RuntimeException("Error: at least one of the following columns should be present: Hugo_Symbol or Entrez_Gene_Id"); String sampleIds[]; sampleIds = new String[parts.length - sampleStartIndex]; System.arraycopy(parts, sampleStartIndex, sampleIds, 0, parts.length - sampleStartIndex); int nrUnknownSamplesAdded = 0; ProgressMonitor.setCurrentMessage(" --> total number of samples: " + sampleIds.length); // link Samples to the genetic profile ArrayList <Integer> orderedSampleList = new ArrayList<Integer>(); ArrayList <Integer> filteredSampleIndices = new ArrayList<Integer>(); for (int i = 0; i < sampleIds.length; i++) { // backwards compatible part (i.e. in the new process, the sample should already be there. TODO - replace this workaround later with an exception: Sample sample = DaoSample.getSampleByCancerStudyAndSampleId(geneticProfile.getCancerStudyId(), StableIdUtil.getSampleId(sampleIds[i])); if (sample == null ) { //TODO - as stated above, this part should be removed. Agreed with JJ to remove this as soon as MSK moves to new validation //procedure. In this new procedure, Patients and Samples should only be added //via the corresponding ImportClinicalData process. Furthermore, the code below is wrong as it assumes one //sample per patient, which is not always the case. ImportDataUtil.addPatients(new String[] { sampleIds[i] }, geneticProfileId); // add the sample (except if it is a 'normal' sample): nrUnknownSamplesAdded += ImportDataUtil.addSamples(new String[] { sampleIds[i] }, geneticProfileId); } // check again (repeated because of workaround above): sample = DaoSample.getSampleByCancerStudyAndSampleId(geneticProfile.getCancerStudyId(), StableIdUtil.getSampleId(sampleIds[i])); // can be null in case of 'normal' sample: if (sample == null) { assert StableIdUtil.isNormal(sampleIds[i]); filteredSampleIndices.add(i); samplesSkipped++; continue; } if (!DaoSampleProfile.sampleExistsInGeneticProfile(sample.getInternalId(), geneticProfileId)) { DaoSampleProfile.addSampleProfile(sample.getInternalId(), geneticProfileId); } orderedSampleList.add(sample.getInternalId()); } if (nrUnknownSamplesAdded > 0) { ProgressMonitor.logWarning("WARNING: Number of samples added on the fly because they were missing in clinical data: " + nrUnknownSamplesAdded); } if (samplesSkipped > 0) { ProgressMonitor.setCurrentMessage(" --> total number of samples skipped (normal samples): " + samplesSkipped); } ProgressMonitor.setCurrentMessage(" --> total number of data lines: " + (numLines-1)); DaoGeneticProfileSamples.addGeneticProfileSamples(geneticProfileId, orderedSampleList); //Gene cache: DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance(); //Object to insert records in the generic 'genetic_alteration' table: DaoGeneticAlteration daoGeneticAlteration = DaoGeneticAlteration.getInstance(); //cache for data found in cna_event' table: Map<CnaEvent.Event, CnaEvent.Event> existingCnaEvents = null; if (discritizedCnaProfile) { existingCnaEvents = new HashMap<CnaEvent.Event, CnaEvent.Event>(); for (CnaEvent.Event event : DaoCnaEvent.getAllCnaEvents()) { existingCnaEvents.put(event, event); } MySQLbulkLoader.bulkLoadOn(); } int lenParts = parts.length; String line = buf.readLine(); while (line != null) { ProgressMonitor.incrementCurValue(); ConsoleUtil.showProgress(); if (parseLine(line, lenParts, sampleStartIndex, hugoSymbolIndex, entrezGeneIdIndex, rppaGeneRefIndex, rppaProfile, discritizedCnaProfile, daoGene, filteredSampleIndices, orderedSampleList, existingCnaEvents, daoGeneticAlteration)) { numRecordsToAdd++; } else { entriesSkipped++; } line = buf.readLine(); } if (MySQLbulkLoader.isBulkLoad()) { MySQLbulkLoader.flushAll(); } if (rppaProfile) { ProgressMonitor.setCurrentMessage(" --> total number of extra records added because of multiple genes in one line: " + nrExtraRecords); } if (entriesSkipped > 0) { ProgressMonitor.setCurrentMessage(" --> total number of data entries skipped (see table below): " + entriesSkipped); } if (numRecordsToAdd == 0) { throw new DaoException ("Something has gone wrong! I did not save any records" + " to the database!"); } } finally { buf.close(); } } private boolean parseLine(String line, int nrColumns, int sampleStartIndex, int hugoSymbolIndex, int entrezGeneIdIndex, int rppaGeneRefIndex, boolean rppaProfile, boolean discritizedCnaProfile, DaoGeneOptimized daoGene, List <Integer> filteredSampleIndices, List <Integer> orderedSampleList, Map<CnaEvent.Event, CnaEvent.Event> existingCnaEvents, DaoGeneticAlteration daoGeneticAlteration ) throws DaoException { boolean recordStored = false; // Ignore lines starting with # if (!line.startsWith("#") && line.trim().length() > 0) { String[] parts = line.split("\t",-1); if (parts.length>nrColumns) { if (line.split("\t").length>nrColumns) { ProgressMonitor.logWarning("Ignoring line with more fields (" + parts.length + ") than specified in the headers(" + nrColumns + "): \n"+parts[0]); return false; } } String values[] = (String[]) ArrayUtils.subarray(parts, sampleStartIndex, parts.length>nrColumns?nrColumns:parts.length); values = filterOutNormalValues(filteredSampleIndices, values); String geneSymbol = null; if (hugoSymbolIndex != -1) { geneSymbol = parts[hugoSymbolIndex]; } //RPPA: //TODO - we should split up the RPPA scenario from this code...too many if/else because of this if (rppaGeneRefIndex != -1) { geneSymbol = parts[rppaGeneRefIndex]; } if (geneSymbol!=null && geneSymbol.isEmpty()) { geneSymbol = null; } if (rppaProfile && geneSymbol == null) { ProgressMonitor.logWarning("Ignoring line with no Composite.Element.REF value"); return false; } //get entrez String entrez = null; if (entrezGeneIdIndex!=-1) { entrez = parts[entrezGeneIdIndex]; } if (entrez!=null) { if (entrez.isEmpty()) { entrez = null; } else if (!entrez.matches("[0-9]+")) { //TODO - would be better to give an exception in some cases, like negative Entrez values ProgressMonitor.logWarning("Ignoring line with invalid Entrez_Id " + entrez); return false; } } //If all are empty, skip line: if (geneSymbol == null && entrez == null) { ProgressMonitor.logWarning("Ignoring line with no Hugo_Symbol or Entrez_Id value"); return false; } else { if (geneSymbol != null && (geneSymbol.contains("///") || geneSymbol.contains("---"))) { // Ignore gene IDs separated by ///. This indicates that // the line contains information regarding multiple genes, and // we cannot currently handle this. // Also, ignore gene IDs that are specified as ---. This indicates // the line contains information regarding an unknown gene, and // we cannot currently handle this. ProgressMonitor.logWarning("Ignoring gene ID: " + geneSymbol); return false; } else { List<CanonicalGene> genes = null; //If rppa, parse genes from "Composite.Element.REF" column: if (rppaProfile) { genes = parseRPPAGenes(geneSymbol); if (genes == null) { //will be null when there is a parse error in this case, so we //can return here and avoid duplicated messages: return false; } } else { //try entrez: if (entrez!=null) { CanonicalGene gene = daoGene.getGene(Long.parseLong(entrez)); if (gene!=null) { genes = Arrays.asList(gene); } else { ProgressMonitor.logWarning("Entrez_Id " + entrez + " not found. Record will be skipped for this gene."); return false; } } //no entrez, try hugo: if (genes==null && geneSymbol != null) { // deal with multiple symbols separate by |, use the first one int ix = geneSymbol.indexOf("|"); if (ix>0) { geneSymbol = geneSymbol.substring(0, ix); } genes = daoGene.getGene(geneSymbol, true); } } if (genes == null || genes.isEmpty()) { genes = Collections.emptyList(); } // If no target line is specified or we match the target, process. if (targetLine == null || parts[0].equals(targetLine)) { if (genes.isEmpty()) { // if gene is null, we might be dealing with a micro RNA ID if (geneSymbol != null && geneSymbol.toLowerCase().contains("-mir-")) { // if (microRnaIdSet.contains(geneId)) { // storeMicroRnaAlterations(values, daoMicroRnaAlteration, geneId); // numRecordsStored++; // } else { ProgressMonitor.logWarning("microRNA is not known to me: [" + geneSymbol + "]. Ignoring it " + "and all tab-delimited data associated with it!"); return false; // } } else { String gene = (geneSymbol != null) ? geneSymbol : entrez; ProgressMonitor.logWarning("Gene not found for: [" + gene + "]. Ignoring it " + "and all tab-delimited data associated with it!"); return false; } } else if (genes.size()==1) { List<CnaEvent> cnaEventsToAdd = new ArrayList<CnaEvent>(); if (discritizedCnaProfile) { long entrezGeneId = genes.get(0).getEntrezGeneId(); for (int i = 0; i < values.length; i++) { // temporary solution -- change partial deletion back to full deletion. if (values[i].equals(GeneticAlterationType.PARTIAL_DELETION)) { values[i] = GeneticAlterationType.HOMOZYGOUS_DELETION; } if (values[i].equals(GeneticAlterationType.AMPLIFICATION) // || values[i].equals(GeneticAlterationType.GAIN) >> skipping GAIN, ZERO, HEMIZYGOUS_DELETION to minimize size of dataset in DB // || values[i].equals(GeneticAlterationType.ZERO) // || values[i].equals(GeneticAlterationType.HEMIZYGOUS_DELETION) || values[i].equals(GeneticAlterationType.HOMOZYGOUS_DELETION)) { CnaEvent cnaEvent = new CnaEvent(orderedSampleList.get(i), geneticProfileId, entrezGeneId, Short.parseShort(values[i])); //delayed add: cnaEventsToAdd.add(cnaEvent); } } } recordStored = storeGeneticAlterations(values, daoGeneticAlteration, genes.get(0), geneSymbol); //only add extra CNA related records if the step above worked, otherwise skip: if (recordStored) { for (CnaEvent cnaEvent : cnaEventsToAdd) { if (existingCnaEvents.containsKey(cnaEvent.getEvent())) { cnaEvent.setEventId(existingCnaEvents.get(cnaEvent.getEvent()).getEventId()); DaoCnaEvent.addCaseCnaEvent(cnaEvent, false); } else { //cnaEvent.setEventId(++cnaEventId); not needed anymore, column now has AUTO_INCREMENT DaoCnaEvent.addCaseCnaEvent(cnaEvent, true); existingCnaEvents.put(cnaEvent.getEvent(), cnaEvent.getEvent()); } } } } else { //TODO - review: is this still correct? int otherCase = 0; for (CanonicalGene gene : genes) { if (gene.isMicroRNA() || rppaProfile) { // for micro rna or protein data, duplicate the data boolean result = storeGeneticAlterations(values, daoGeneticAlteration, gene, geneSymbol); if (result == true) { recordStored = true; nrExtraRecords++; } } else { otherCase++; } } if (recordStored) { //skip one, to avoid double counting: nrExtraRecords--; } if (!recordStored) { if (otherCase > 1) { //this means that genes.size() > 1 and data was not rppa or microRNA, so it is not defined how to deal with //the ambiguous alias list. Report this: ProgressMonitor.logWarning("Gene symbol " + geneSymbol + " found to be ambiguous. Record will be skipped for this gene."); } else { //should not occur: throw new RuntimeException("Unexpected error: unable to process row with gene " + geneSymbol); } } } } } } } return recordStored; } private boolean storeGeneticAlterations(String[] values, DaoGeneticAlteration daoGeneticAlteration, CanonicalGene gene, String geneSymbol) throws DaoException { // Check that we have not already imported information regarding this gene. // This is an important check, because a GISTIC or RAE file may contain // multiple rows for the same gene, and we only want to import the first row. try { if (!importedGeneSet.contains(gene.getEntrezGeneId())) { daoGeneticAlteration.addGeneticAlterations(geneticProfileId, gene.getEntrezGeneId(), values); importedGeneSet.add(gene.getEntrezGeneId()); return true; } else { //TODO - review this part - maybe it should be an Exception instead of just a warning. String geneSymbolMessage = ""; if (geneSymbol != null && !geneSymbol.equalsIgnoreCase(gene.getHugoGeneSymbolAllCaps())) geneSymbolMessage = "(given as alias in your file as: " + geneSymbol + ") "; ProgressMonitor.logWarning("Gene " + gene.getHugoGeneSymbolAllCaps() + " (" + gene.getEntrezGeneId() + ")" + geneSymbolMessage + " found to be duplicated in your file. Duplicated row will be ignored!"); return false; } } catch (Exception e) { throw new RuntimeException("Aborted: Error found for row starting with " + geneSymbol + ": " + e.getMessage()); } } /** * Tries to parse the genes and look them up in DaoGeneOptimized * * @param antibodyWithGene * @return returns null if something was wrong, e.g. could not parse the antibodyWithGene string; returns * a list with 0 or more elements otherwise. * @throws DaoException */ private List<CanonicalGene> parseRPPAGenes(String antibodyWithGene) throws DaoException { DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance(); String[] parts = antibodyWithGene.split("\\|"); //validate: if (parts.length < 2) { ProgressMonitor.logWarning("Could not parse Composite.Element.Ref value " + antibodyWithGene + ". Record will be skipped."); //return null when there was a parse error: return null; } String[] symbols = parts[0].split(" "); String arrayId = parts[1]; //validate arrayId: if arrayId if duplicated, warn: if (!arrayIdSet.add(arrayId)) { ProgressMonitor.logWarning("Id " + arrayId + " in [" + antibodyWithGene + "] found to be duplicated. Record will be skipped."); return null; } List<String> symbolsNotFound = new ArrayList<String>(); List<CanonicalGene> genes = new ArrayList<CanonicalGene>(); for (String symbol : symbols) { if (symbol.equalsIgnoreCase("NA")) { //workaround because of bug in firehose. See https://github.com/cBioPortal/cbioportal/issues/839#issuecomment-203523078 ProgressMonitor.logWarning("Gene " + symbol + " will be interpreted as 'Not Available' in this case. Record will be skipped for this gene."); } else { CanonicalGene gene = daoGene.getNonAmbiguousGene(symbol, null); if (gene!=null) { genes.add(gene); } else { symbolsNotFound.add(symbol); } } } if (genes.size() == 0) { //return empty list: return genes; } //So one or more genes were found, but maybe some were not found. If any //is not found, report it here: for (String symbol : symbolsNotFound) { ProgressMonitor.logWarning("Gene " + symbol + " not found in DB. Record will be skipped for this gene."); } Pattern p = Pattern.compile("(p[STY][0-9]+(?:_[STY][0-9]+)*)"); Matcher m = p.matcher(arrayId); String residue; if (!m.find()) { //type is "protein_level": return genes; } else { //type is "phosphorylation": residue = m.group(1); return importPhosphoGene(genes, residue); } } private List<CanonicalGene> importPhosphoGene(List<CanonicalGene> genes, String residue) throws DaoException { DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance(); List<CanonicalGene> phosphoGenes = new ArrayList<CanonicalGene>(); for (CanonicalGene gene : genes) { Set<String> aliases = new HashSet<String>(); aliases.add("rppa-phospho"); aliases.add("phosphoprotein"); aliases.add("phospho"+gene.getStandardSymbol()); String phosphoSymbol = gene.getStandardSymbol()+"_"+residue; CanonicalGene phosphoGene = daoGene.getGene(phosphoSymbol); if (phosphoGene==null) { ProgressMonitor.logWarning("Phosphoprotein " + phosphoSymbol + " not yet known in DB. Adding it to `gene` table with 3 aliases in `gene_alias` table."); phosphoGene = new CanonicalGene(phosphoSymbol, aliases); phosphoGene.setType(CanonicalGene.PHOSPHOPROTEIN_TYPE); phosphoGene.setCytoband(gene.getCytoband()); daoGene.addGene(phosphoGene); } phosphoGenes.add(phosphoGene); } return phosphoGenes; } private int getHugoSymbolIndex(String[] headers) { for (int i = 0; i<headers.length; i++) { if (headers[i].equalsIgnoreCase("Hugo_Symbol")) { return i; } } return -1; } private int getEntrezGeneIdIndex(String[] headers) { for (int i = 0; i<headers.length; i++) { if (headers[i].equalsIgnoreCase("Entrez_Gene_Id")) { return i; } } return -1; } private int getRppaGeneRefIndex(String[] headers) { for (int i = 0; i<headers.length; i++) { if (headers[i].equalsIgnoreCase("Composite.Element.Ref")) { return i; } } return -1; } private int getStartIndex(String[] headers, int hugoSymbolIndex, int entrezGeneIdIndex, int rppaGeneRefIndex) { int startIndex = -1; for (int i=0; i<headers.length; i++) { String h = headers[i]; //if the column is not one of the gene symbol/gene ide columns or other pre-sample columns: if (!h.equalsIgnoreCase("Gene Symbol") && !h.equalsIgnoreCase("Hugo_Symbol") && !h.equalsIgnoreCase("Entrez_Gene_Id") && !h.equalsIgnoreCase("Locus ID") && !h.equalsIgnoreCase("Cytoband") && !h.equalsIgnoreCase("Composite.Element.Ref")) { //and the column is found after hugoSymbolIndex and entrezGeneIdIndex: if (i > hugoSymbolIndex && i > entrezGeneIdIndex && i > rppaGeneRefIndex) { //then we consider this the start of the sample columns: startIndex = i; break; } } } if (startIndex == -1) throw new RuntimeException("Could not find a sample column in the file"); return startIndex; } private String[] filterOutNormalValues(List <Integer> filteredSampleIndices, String[] values) { ArrayList<String> filteredValues = new ArrayList<String>(); for (int lc = 0; lc < values.length; lc++) { if (!filteredSampleIndices.contains(lc)) { filteredValues.add(values[lc]); } } return filteredValues.toArray(new String[filteredValues.size()]); } }
core/src/main/java/org/mskcc/cbio/portal/scripts/ImportTabDelimData.java
/* * Copyright (c) 2015 Memorial Sloan-Kettering Cancer Center. * * This library 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. The software and documentation provided hereunder * is on an "as is" basis, and Memorial Sloan-Kettering Cancer Center has no * obligations to provide maintenance, support, updates, enhancements or * modifications. In no event shall Memorial Sloan-Kettering Cancer Center be * liable to any party for direct, indirect, special, incidental or * consequential damages, including lost profits, arising out of the use of this * software and its documentation, even if Memorial Sloan-Kettering Cancer * Center has been advised of the possibility of such damage. */ /* * This file is part of cBioPortal. * * cBioPortal is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.mskcc.cbio.portal.scripts; import org.mskcc.cbio.portal.dao.*; import org.mskcc.cbio.portal.model.*; import org.mskcc.cbio.portal.util.*; import org.apache.commons.lang.ArrayUtils; import org.apache.log4j.Logger; import java.io.*; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Code to Import Copy Number Alteration, MRNA Expression Data, Methylation, or protein RPPA data * * @author Ethan Cerami */ public class ImportTabDelimData { private HashSet<Long> importedGeneSet = new HashSet<Long>(); private File mutationFile; private String targetLine; private int geneticProfileId; private GeneticProfile geneticProfile; private int entriesSkipped = 0; private int nrExtraRecords = 0; private Set<String> arrayIdSet = new HashSet<String>(); /** * Constructor. * * @param dataFile Data File containing Copy Number Alteration, MRNA Expression Data, or protein RPPA data * @param targetLine The line we want to import. * If null, all lines are imported. * @param geneticProfileId GeneticProfile ID. * * @deprecated : TODO shall we deprecate this feature (i.e. the targetLine)? */ public ImportTabDelimData(File dataFile, String targetLine, int geneticProfileId) { this.mutationFile = dataFile; this.targetLine = targetLine; this.geneticProfileId = geneticProfileId; } /** * Constructor. * * @param dataFile Data File containing Copy Number Alteration, MRNA Expression Data, or protein RPPA data * @param geneticProfileId GeneticProfile ID. */ public ImportTabDelimData(File dataFile, int geneticProfileId) { this.mutationFile = dataFile; this.geneticProfileId = geneticProfileId; } /** * Import the Copy Number Alteration, MRNA Expression Data, or protein RPPA data * * @throws IOException IO Error. * @throws DaoException Database Error. */ public void importData(int numLines) throws IOException, DaoException { geneticProfile = DaoGeneticProfile.getGeneticProfileById(geneticProfileId); FileReader reader = new FileReader(mutationFile); BufferedReader buf = new BufferedReader(reader); String headerLine = buf.readLine(); String parts[] = headerLine.split("\t"); //Whether data regards CNA or RPPA: boolean discritizedCnaProfile = geneticProfile!=null && geneticProfile.getGeneticAlterationType() == GeneticAlterationType.COPY_NUMBER_ALTERATION && geneticProfile.showProfileInAnalysisTab(); boolean rppaProfile = geneticProfile!=null && geneticProfile.getGeneticAlterationType() == GeneticAlterationType.PROTEIN_LEVEL && "Composite.Element.Ref".equalsIgnoreCase(parts[0]); int numRecordsToAdd = 0; int samplesSkipped = 0; try { int hugoSymbolIndex = getHugoSymbolIndex(parts); int entrezGeneIdIndex = getEntrezGeneIdIndex(parts); int rppaGeneRefIndex = getRppaGeneRefIndex(parts); int sampleStartIndex = getStartIndex(parts, hugoSymbolIndex, entrezGeneIdIndex, rppaGeneRefIndex); if (rppaProfile) { if (rppaGeneRefIndex == -1) throw new RuntimeException("Error: the following column should be present for RPPA data: Composite.Element.Ref"); } else if (hugoSymbolIndex == -1 && entrezGeneIdIndex == -1) throw new RuntimeException("Error: at least one of the following columns should be present: Hugo_Symbol or Entrez_Gene_Id"); String sampleIds[]; sampleIds = new String[parts.length - sampleStartIndex]; System.arraycopy(parts, sampleStartIndex, sampleIds, 0, parts.length - sampleStartIndex); int nrUnknownSamplesAdded = 0; ProgressMonitor.setCurrentMessage(" --> total number of samples: " + sampleIds.length); // link Samples to the genetic profile ArrayList <Integer> orderedSampleList = new ArrayList<Integer>(); ArrayList <Integer> filteredSampleIndices = new ArrayList<Integer>(); for (int i = 0; i < sampleIds.length; i++) { // backwards compatible part (i.e. in the new process, the sample should already be there. TODO - replace this workaround later with an exception: Sample sample = DaoSample.getSampleByCancerStudyAndSampleId(geneticProfile.getCancerStudyId(), StableIdUtil.getSampleId(sampleIds[i])); if (sample == null ) { //TODO - as stated above, this part should be removed. Agreed with JJ to remove this as soon as MSK moves to new validation //procedure. In this new procedure, Patients and Samples should only be added //via the corresponding ImportClinicalData process. Furthermore, the code below is wrong as it assumes one //sample per patient, which is not always the case. ImportDataUtil.addPatients(new String[] { sampleIds[i] }, geneticProfileId); // add the sample (except if it is a 'normal' sample): nrUnknownSamplesAdded += ImportDataUtil.addSamples(new String[] { sampleIds[i] }, geneticProfileId); } // check again (repeated because of workaround above): sample = DaoSample.getSampleByCancerStudyAndSampleId(geneticProfile.getCancerStudyId(), StableIdUtil.getSampleId(sampleIds[i])); // can be null in case of 'normal' sample: if (sample == null) { assert StableIdUtil.isNormal(sampleIds[i]); filteredSampleIndices.add(i); samplesSkipped++; continue; } if (!DaoSampleProfile.sampleExistsInGeneticProfile(sample.getInternalId(), geneticProfileId)) { DaoSampleProfile.addSampleProfile(sample.getInternalId(), geneticProfileId); } orderedSampleList.add(sample.getInternalId()); } if (nrUnknownSamplesAdded > 0) { ProgressMonitor.logWarning("WARNING: Number of samples added on the fly because they were missing in clinical data: " + nrUnknownSamplesAdded); } if (samplesSkipped > 0) { ProgressMonitor.setCurrentMessage(" --> total number of samples skipped (normal samples): " + samplesSkipped); } ProgressMonitor.setCurrentMessage(" --> total number of data lines: " + (numLines-1)); DaoGeneticProfileSamples.addGeneticProfileSamples(geneticProfileId, orderedSampleList); //Gene cache: DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance(); //Object to insert records in the generic 'genetic_alteration' table: DaoGeneticAlteration daoGeneticAlteration = DaoGeneticAlteration.getInstance(); //cache for data found in cna_event' table: Map<CnaEvent.Event, CnaEvent.Event> existingCnaEvents = null; if (discritizedCnaProfile) { existingCnaEvents = new HashMap<CnaEvent.Event, CnaEvent.Event>(); for (CnaEvent.Event event : DaoCnaEvent.getAllCnaEvents()) { existingCnaEvents.put(event, event); } MySQLbulkLoader.bulkLoadOn(); } int lenParts = parts.length; String line = buf.readLine(); while (line != null) { ProgressMonitor.incrementCurValue(); ConsoleUtil.showProgress(); if (parseLine(line, lenParts, sampleStartIndex, hugoSymbolIndex, entrezGeneIdIndex, rppaGeneRefIndex, rppaProfile, discritizedCnaProfile, daoGene, filteredSampleIndices, orderedSampleList, existingCnaEvents, daoGeneticAlteration)) { numRecordsToAdd++; } else { entriesSkipped++; } line = buf.readLine(); } if (MySQLbulkLoader.isBulkLoad()) { MySQLbulkLoader.flushAll(); } if (rppaProfile) { ProgressMonitor.setCurrentMessage(" --> total number of extra records added because of multiple genes in one line: " + nrExtraRecords); } if (entriesSkipped > 0) { ProgressMonitor.setCurrentMessage(" --> total number of data entries skipped (see table below): " + entriesSkipped); } if (numRecordsToAdd == 0) { throw new DaoException ("Something has gone wrong! I did not save any records" + " to the database!"); } } finally { buf.close(); } } private boolean parseLine(String line, int nrColumns, int sampleStartIndex, int hugoSymbolIndex, int entrezGeneIdIndex, int rppaGeneRefIndex, boolean rppaProfile, boolean discritizedCnaProfile, DaoGeneOptimized daoGene, List <Integer> filteredSampleIndices, List <Integer> orderedSampleList, Map<CnaEvent.Event, CnaEvent.Event> existingCnaEvents, DaoGeneticAlteration daoGeneticAlteration ) throws DaoException { boolean recordStored = false; // Ignore lines starting with # if (!line.startsWith("#") && line.trim().length() > 0) { String[] parts = line.split("\t",-1); if (parts.length>nrColumns) { if (line.split("\t").length>nrColumns) { ProgressMonitor.logWarning("Ignoring line with more fields (" + parts.length + ") than specified in the headers(" + nrColumns + "): \n"+parts[0]); return false; } } String values[] = (String[]) ArrayUtils.subarray(parts, sampleStartIndex, parts.length>nrColumns?nrColumns:parts.length); values = filterOutNormalValues(filteredSampleIndices, values); String geneSymbol = null; if (hugoSymbolIndex != -1) { geneSymbol = parts[hugoSymbolIndex]; } //RPPA: //TODO - we should split up the RPPA scenario from this code...too many if/else because of this if (rppaGeneRefIndex != -1) { geneSymbol = parts[rppaGeneRefIndex]; } if (geneSymbol!=null && geneSymbol.isEmpty()) { geneSymbol = null; } if (rppaProfile && geneSymbol == null) { ProgressMonitor.logWarning("Ignoring line with no Composite.Element.REF value"); return false; } //get entrez String entrez = null; if (entrezGeneIdIndex!=-1) { entrez = parts[entrezGeneIdIndex]; } if (entrez!=null) { if (entrez.isEmpty()) { entrez = null; } else if (!entrez.matches("[0-9]+")) { //TODO - would be better to give an exception in some cases, like negative Entrez values ProgressMonitor.logWarning("Ignoring line with invalid Entrez_Id " + entrez); return false; } } //If all are empty, skip line: if (geneSymbol == null && entrez == null) { ProgressMonitor.logWarning("Ignoring line with no Hugo_Symbol or Entrez_Id value"); return false; } else { if (geneSymbol != null && (geneSymbol.contains("///") || geneSymbol.contains("---"))) { // Ignore gene IDs separated by ///. This indicates that // the line contains information regarding multiple genes, and // we cannot currently handle this. // Also, ignore gene IDs that are specified as ---. This indicates // the line contains information regarding an unknown gene, and // we cannot currently handle this. ProgressMonitor.logWarning("Ignoring gene ID: " + geneSymbol); return false; } else { List<CanonicalGene> genes = null; //If rppa, parse genes from "Composite.Element.REF" column: if (rppaProfile) { genes = parseRPPAGenes(geneSymbol); if (genes == null) { //will be null when there is a parse error in this case, so we //can return here and avoid duplicated messages: return false; } } else { //try entrez: if (entrez!=null) { CanonicalGene gene = daoGene.getGene(Long.parseLong(entrez)); if (gene!=null) { genes = Arrays.asList(gene); } else { ProgressMonitor.logWarning("Entrez_Id " + entrez + " not found. Record will be skipped for this gene."); return false; } } //no entrez, try hugo: if (genes==null && geneSymbol != null) { // deal with multiple symbols separate by |, use the first one int ix = geneSymbol.indexOf("|"); if (ix>0) { geneSymbol = geneSymbol.substring(0, ix); } genes = daoGene.getGene(geneSymbol, true); } } if (genes == null || genes.isEmpty()) { genes = Collections.emptyList(); } // If no target line is specified or we match the target, process. if (targetLine == null || parts[0].equals(targetLine)) { if (genes.isEmpty()) { // if gene is null, we might be dealing with a micro RNA ID if (geneSymbol != null && geneSymbol.toLowerCase().contains("-mir-")) { // if (microRnaIdSet.contains(geneId)) { // storeMicroRnaAlterations(values, daoMicroRnaAlteration, geneId); // numRecordsStored++; // } else { ProgressMonitor.logWarning("microRNA is not known to me: [" + geneSymbol + "]. Ignoring it " + "and all tab-delimited data associated with it!"); return false; // } } else { String gene = (geneSymbol != null) ? geneSymbol : entrez; ProgressMonitor.logWarning("Gene not found for: [" + gene + "]. Ignoring it " + "and all tab-delimited data associated with it!"); return false; } } else if (genes.size()==1) { List<CnaEvent> cnaEventsToAdd = new ArrayList<CnaEvent>(); if (discritizedCnaProfile) { long entrezGeneId = genes.get(0).getEntrezGeneId(); for (int i = 0; i < values.length; i++) { // temporary solution -- change partial deletion back to full deletion. if (values[i].equals(GeneticAlterationType.PARTIAL_DELETION)) { values[i] = GeneticAlterationType.HOMOZYGOUS_DELETION; } if (values[i].equals(GeneticAlterationType.AMPLIFICATION) // || values[i].equals(GeneticAlterationType.GAIN) >> skipping GAIN, ZERO, HEMIZYGOUS_DELETION to minimize size of dataset in DB // || values[i].equals(GeneticAlterationType.ZERO) // || values[i].equals(GeneticAlterationType.HEMIZYGOUS_DELETION) || values[i].equals(GeneticAlterationType.HOMOZYGOUS_DELETION)) { CnaEvent cnaEvent = new CnaEvent(orderedSampleList.get(i), geneticProfileId, entrezGeneId, Short.parseShort(values[i])); //delayed add: cnaEventsToAdd.add(cnaEvent); } } } recordStored = storeGeneticAlterations(values, daoGeneticAlteration, genes.get(0), geneSymbol); //only add extra CNA related records if the step above worked, otherwise skip: if (recordStored) { for (CnaEvent cnaEvent : cnaEventsToAdd) { if (existingCnaEvents.containsKey(cnaEvent.getEvent())) { cnaEvent.setEventId(existingCnaEvents.get(cnaEvent.getEvent()).getEventId()); DaoCnaEvent.addCaseCnaEvent(cnaEvent, false); } else { //cnaEvent.setEventId(++cnaEventId); not needed anymore, column now has AUTO_INCREMENT DaoCnaEvent.addCaseCnaEvent(cnaEvent, true); existingCnaEvents.put(cnaEvent.getEvent(), cnaEvent.getEvent()); } } } } else { //TODO - review: is this still correct? int otherCase = 0; for (CanonicalGene gene : genes) { if (gene.isMicroRNA() || rppaProfile) { // for micro rna or protein data, duplicate the data boolean result = storeGeneticAlterations(values, daoGeneticAlteration, gene, geneSymbol); if (result == true) { recordStored = true; nrExtraRecords++; } } else { otherCase++; } } if (recordStored) { //skip one, to avoid double counting: nrExtraRecords--; } if (!recordStored) { if (otherCase > 1) { //this means that genes.size() > 1 and data was not rppa or microRNA, so it is not defined how to deal with //the ambiguous alias list. Report this: ProgressMonitor.logWarning("Gene symbol " + geneSymbol + " found to be ambiguous. Record will be skipped for this gene."); } else { //should not occur: throw new RuntimeException("Unexpected error: unable to process row with gene " + geneSymbol); } } } } } } } return recordStored; } private boolean storeGeneticAlterations(String[] values, DaoGeneticAlteration daoGeneticAlteration, CanonicalGene gene, String geneSymbol) throws DaoException { // Check that we have not already imported information regarding this gene. // This is an important check, because a GISTIC or RAE file may contain // multiple rows for the same gene, and we only want to import the first row. try { if (!importedGeneSet.contains(gene.getEntrezGeneId())) { daoGeneticAlteration.addGeneticAlterations(geneticProfileId, gene.getEntrezGeneId(), values); importedGeneSet.add(gene.getEntrezGeneId()); return true; } else { //TODO - review this part - maybe it should be an Exception instead of just a warning. String geneSymbolMessage = ""; if (geneSymbol != null && !geneSymbol.equalsIgnoreCase(gene.getHugoGeneSymbolAllCaps())) geneSymbolMessage = "(given as alias in your file as: " + geneSymbol + ") "; ProgressMonitor.logWarning("Gene " + gene.getHugoGeneSymbolAllCaps() + " (" + gene.getEntrezGeneId() + ")" + geneSymbolMessage + " found to be duplicated in your file. Duplicated row will be ignored!"); return false; } } catch (Exception e) { throw new RuntimeException("Aborted: Error found for row starting with " + geneSymbol + ": " + e.getMessage()); } } /** * Tries to parse the genes and look them up in DaoGeneOptimized * * @param antibodyWithGene * @return returns null if something was wrong, e.g. could not parse the antibodyWithGene string; returns * a list with 0 or more elements otherwise. * @throws DaoException */ private List<CanonicalGene> parseRPPAGenes(String antibodyWithGene) throws DaoException { DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance(); String[] parts = antibodyWithGene.split("\\|"); //validate: if (parts.length < 2) { ProgressMonitor.logWarning("Could not parse Composite.Element.Ref value " + antibodyWithGene + ". Record will be skipped."); //return null when there was a parse error: return null; } String[] symbols = parts[0].split(" "); String arrayId = parts[1]; //validate arrayId: if arrayId if duplicated, warn: if (!arrayIdSet.add(arrayId)) { ProgressMonitor.logWarning("Id " + arrayId + " in [" + antibodyWithGene + "] found to be duplicated. Record will be skipped."); return null; } List<String> symbolsNotFound = new ArrayList<String>(); List<CanonicalGene> genes = new ArrayList<CanonicalGene>(); for (String symbol : symbols) { if (symbol.equalsIgnoreCase("NA")) { //workaround because of bug in firehose. See https://github.com/cBioPortal/cbioportal/issues/839#issuecomment-203523078 ProgressMonitor.logWarning("Gene " + symbol + " will be interpreted as 'Not Available' in this case. Record will be skipped for this gene."); } else { CanonicalGene gene = daoGene.getNonAmbiguousGene(symbol, null); if (gene!=null) { genes.add(gene); } else { symbolsNotFound.add(symbol); } } } if (genes.size() == 0) { //return empty list: return genes; } //So one or more genes were found, but maybe some were not found. If any //is not found, report it here: for (String symbol : symbolsNotFound) { ProgressMonitor.logWarning("Gene " + symbol + " not found in DB. Record will be skipped for this gene."); } Pattern p = Pattern.compile("(p[STY][0-9]+)"); Matcher m = p.matcher(arrayId); String residue; if (!m.find()) { //type is "protein_level": return genes; } else { //type is "phosphorylation": residue = m.group(1); return importPhosphoGene(genes, residue); } } private List<CanonicalGene> importPhosphoGene(List<CanonicalGene> genes, String residue) throws DaoException { DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance(); List<CanonicalGene> phosphoGenes = new ArrayList<CanonicalGene>(); for (CanonicalGene gene : genes) { Set<String> aliases = new HashSet<String>(); aliases.add("rppa-phospho"); aliases.add("phosphoprotein"); aliases.add("phospho"+gene.getStandardSymbol()); String phosphoSymbol = gene.getStandardSymbol()+"_"+residue; CanonicalGene phosphoGene = daoGene.getGene(phosphoSymbol); if (phosphoGene==null) { ProgressMonitor.logWarning("Phosphoprotein " + phosphoSymbol + " not yet known in DB. Adding it to `gene` table with 3 aliases in `gene_alias` table."); phosphoGene = new CanonicalGene(phosphoSymbol, aliases); phosphoGene.setType(CanonicalGene.PHOSPHOPROTEIN_TYPE); phosphoGene.setCytoband(gene.getCytoband()); daoGene.addGene(phosphoGene); } phosphoGenes.add(phosphoGene); } return phosphoGenes; } private int getHugoSymbolIndex(String[] headers) { for (int i = 0; i<headers.length; i++) { if (headers[i].equalsIgnoreCase("Hugo_Symbol")) { return i; } } return -1; } private int getEntrezGeneIdIndex(String[] headers) { for (int i = 0; i<headers.length; i++) { if (headers[i].equalsIgnoreCase("Entrez_Gene_Id")) { return i; } } return -1; } private int getRppaGeneRefIndex(String[] headers) { for (int i = 0; i<headers.length; i++) { if (headers[i].equalsIgnoreCase("Composite.Element.Ref")) { return i; } } return -1; } private int getStartIndex(String[] headers, int hugoSymbolIndex, int entrezGeneIdIndex, int rppaGeneRefIndex) { int startIndex = -1; for (int i=0; i<headers.length; i++) { String h = headers[i]; //if the column is not one of the gene symbol/gene ide columns or other pre-sample columns: if (!h.equalsIgnoreCase("Gene Symbol") && !h.equalsIgnoreCase("Hugo_Symbol") && !h.equalsIgnoreCase("Entrez_Gene_Id") && !h.equalsIgnoreCase("Locus ID") && !h.equalsIgnoreCase("Cytoband") && !h.equalsIgnoreCase("Composite.Element.Ref")) { //and the column is found after hugoSymbolIndex and entrezGeneIdIndex: if (i > hugoSymbolIndex && i > entrezGeneIdIndex && i > rppaGeneRefIndex) { //then we consider this the start of the sample columns: startIndex = i; break; } } } if (startIndex == -1) throw new RuntimeException("Could not find a sample column in the file"); return startIndex; } private String[] filterOutNormalValues(List <Integer> filteredSampleIndices, String[] values) { ArrayList<String> filteredValues = new ArrayList<String>(); for (int lc = 0; lc < values.length; lc++) { if (!filteredSampleIndices.contains(lc)) { filteredValues.add(values[lc]); } } return filteredValues.toArray(new String[filteredValues.size()]); } }
Allow mutliple phospho sites to import For RPPA data
core/src/main/java/org/mskcc/cbio/portal/scripts/ImportTabDelimData.java
Allow mutliple phospho sites to import
Java
lgpl-2.1
3e10a4d533d6a3f7b1a39d107961c6a8038eb01e
0
ekiwi/jade-mirror,ekiwi/jade-mirror,ekiwi/jade-mirror,ekiwi/jade-mirror
/***************************************************************** JADE - Java Agent DEvelopment Framework is a framework to develop multi-agent systems in compliance with the FIPA specifications. Copyright (C) 2000 CSELT S.p.A. GNU Lesser General Public License This library 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, version 2.1 of the License. This library 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 library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *****************************************************************/ package jade.core; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamClass; import java.io.FileWriter; import java.io.StringWriter; import java.net.InetAddress; import java.net.MalformedURLException; import java.rmi.*; import java.rmi.server.UnicastRemoteObject; import java.lang.reflect.*; import java.util.Iterator; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.Iterator; import java.util.HashMap; import java.util.Set; import jade.lang.acl.*; import jade.domain.MobilityOntology; import jade.mtp.*; /** @author Giovanni Rimassa - Universita` di Parma @version $Date$ $Revision$ */ class AgentContainerImpl extends UnicastRemoteObject implements AgentContainer, AgentToolkit { private static final int CACHE_SIZE = 10; // Local agents, indexed by agent name protected LADT localAgents = new LADT(); // Agents cache, indexed by agent name private AgentCache cachedProxies = new AgentCache(CACHE_SIZE); // ClassLoader table, used for agent mobility private Map loaders = new HashMap(); // The agent platform this container belongs to protected MainContainer myPlatform; protected String myName; // The Agent Communication Channel, managing the external MTPs. protected acc theACC; // Unique ID of the platform, used to build the GUID of resident // agents. protected String platformID; private Map SniffedAgents = new HashMap(); private String theSniffer; // This monitor is used to hang a remote ping() call from the front // end, in order to detect container failures. private java.lang.Object pingLock = new java.lang.Object(); private ThreadGroup agentThreads = new ThreadGroup("JADE Agents"); private ThreadGroup criticalThreads = new ThreadGroup("JADE time-critical threads"); public AgentContainerImpl() throws RemoteException { // Configure Java runtime system to put the whole host address in RMI messages try { System.getProperties().put("java.rmi.server.hostname", InetAddress.getLocalHost().getHostAddress()); } catch(java.net.UnknownHostException jnue) { jnue.printStackTrace(); } // Set up attributes for agents thread group agentThreads.setMaxPriority(Thread.NORM_PRIORITY); // Set up attributes for time critical threads criticalThreads.setMaxPriority(Thread.MAX_PRIORITY); // Initialize timer dispatcher TimerDispatcher td = new TimerDispatcher(); Thread t = new Thread(criticalThreads, td); t.setPriority(criticalThreads.getMaxPriority()); td.setThread(t); // This call starts the timer dispatcher thread Agent.setDispatcher(td); } // Interface AgentContainer implementation public void createAgent(AID agentID, String className,String[] args, boolean startIt) throws RemoteException { Agent agent = null; try { if(args.length == 0) //no arguments agent = (Agent)Class.forName(new String(className)).newInstance(); else { Class agentDefinition = Class.forName(new String(className)); Class[] stringArgsClass = new Class[]{ String[].class }; Constructor[] constr = agentDefinition.getConstructors(); Constructor stringArgsConstructor = agentDefinition.getConstructor(stringArgsClass); Object[] objArg = new Object[] {args}; agent = (Agent)stringArgsConstructor.newInstance(objArg); } } catch(ClassNotFoundException cnfe) { System.err.println("Class " + className + " for agent " + agentID + " was not found."); return; }catch(java.lang.NoSuchMethodException nsme){ System.err.println("Not found an appropriate constructor for agent " + agentID +" class "+className); return; } catch( Exception e ){ e.printStackTrace(); } initAgent(agentID, agent, startIt); } public void createAgent(AID agentID, byte[] serializedInstance, AgentContainer classSite, boolean startIt) throws RemoteException { final AgentContainer ac = classSite; class Deserializer extends ObjectInputStream { public Deserializer(InputStream inner) throws IOException { super(inner); } protected Class resolveClass(ObjectStreamClass v) throws IOException, ClassNotFoundException { ClassLoader cl = (ClassLoader)loaders.get(ac); if(cl == null) { cl = new JADEClassLoader(ac); loaders.put(ac, cl); } return(cl.loadClass(v.getName())); } } try { ObjectInputStream in = new Deserializer(new ByteArrayInputStream(serializedInstance)); Agent instance = (Agent)in.readObject(); initAgent(agentID, instance, startIt); } catch(IOException ioe) { ioe.printStackTrace(); } catch(ClassNotFoundException cnfe) { cnfe.printStackTrace(); } } // Accepts the fully qualified class name as parameter and searches // the class file in the classpath public byte[] fetchClassFile(String name) throws RemoteException, ClassNotFoundException { name = name.replace( '.' , '/') + ".class"; InputStream classStream = ClassLoader.getSystemResourceAsStream(name); if (classStream == null) throw new ClassNotFoundException(); try { byte[] bytes = new byte[classStream.available()]; classStream.read(bytes); return(bytes); } catch (IOException ioe) { throw new ClassNotFoundException(); } } void initAgent(AID agentID, Agent instance, boolean startIt) { // Subscribe as a listener for the new agent instance.setToolkit(this); // put the agent in the local table and get the previous one, if any Agent previous = localAgents.put(agentID, instance); if(startIt) { try { RemoteProxyRMI rp = new RemoteProxyRMI(this, agentID); myPlatform.bornAgent(agentID, rp, myName); // RMI call instance.powerUp(agentID, agentThreads); } catch(NameClashException nce) { System.out.println("Agentname already in use:"+nce.getMessage()); localAgents.remove(agentID); localAgents.put(agentID,previous); } catch(RemoteException re) { System.out.println("Communication error while adding a new agent to the platform."); re.printStackTrace(); } } } public void suspendAgent(AID agentID) throws RemoteException, NotFoundException { Agent agent = localAgents.get(agentID); if(agent == null) throw new NotFoundException("SuspendAgent failed to find " + agentID); agent.doSuspend(); } public void resumeAgent(AID agentID) throws RemoteException, NotFoundException { Agent agent = localAgents.get(agentID); if(agent == null) throw new NotFoundException("ResumeAgent failed to find " + agentID); agent.doActivate(); } public void waitAgent(AID agentID) throws RemoteException, NotFoundException { Agent agent = localAgents.get(agentID); if(agent==null) throw new NotFoundException("WaitAgent failed to find " + agentID); agent.doWait(); } public void wakeAgent(AID agentID) throws RemoteException, NotFoundException { Agent agent = localAgents.get(agentID); if(agent==null) throw new NotFoundException("WakeAgent failed to find " + agentID); agent.doWake(); } public void moveAgent(AID agentID, Location where) throws RemoteException, NotFoundException { Agent agent = localAgents.get(agentID); if(agent==null) throw new NotFoundException("MoveAgent failed to find " + agentID); agent.doMove(where); } public void copyAgent(AID agentID, Location where, String newName) throws RemoteException, NotFoundException { Agent agent = localAgents.get(agentID); if(agent == null) throw new NotFoundException("CopyAgent failed to find " + agentID); agent.doClone(where, newName); } public void killAgent(AID agentID) throws RemoteException, NotFoundException { Agent agent = localAgents.get(agentID); if(agent == null) throw new NotFoundException("KillAgent failed to find " + agentID); agent.doDelete(); } public void exit() throws RemoteException { shutDown(); System.exit(0); } public void postTransferResult(AID agentID, boolean result, List messages) throws RemoteException, NotFoundException { synchronized(localAgents) { Agent agent = localAgents.get(agentID); if((agent == null)||(agent.getState() != Agent.AP_TRANSIT)) { throw new NotFoundException("postTransferResult() unable to find a suitable agent."); } if(result == TRANSFER_ABORT) localAgents.remove(agentID); else { // Insert received messages at the start of the queue for(int i = messages.size(); i > 0; i--) agent.putBack((ACLMessage)messages.get(i - 1)); agent.powerUp(agentID, agentThreads); } } } /** @param toBeSniffer is an Iterator over the AIDs of agents to be sniffed **/ public void enableSniffer(AID snifferName , List toBeSniffed) throws RemoteException { // In the SniffedAgents hashmap the key is the agent name and the value // is a list containing the sniffer names for that agent Iterator iOnToBeSniffed = toBeSniffed.iterator(); while(iOnToBeSniffed.hasNext()) { AID aid = (AID)iOnToBeSniffed.next(); ArrayList l; if (SniffedAgents.containsKey(aid)) { l = (ArrayList)SniffedAgents.get(aid); if (!l.contains(snifferName)) l.add(snifferName); } else { l = new ArrayList(1); l.add(snifferName); SniffedAgents.put(aid,l); } } } public void disableSniffer(AID snifferName, List notToBeSniffed) throws RemoteException { // In the SniffedAgents hashmap the key is the agent name and the value // is a list containing the sniffer names for that agent Iterator iOnNotToBeSniffed = notToBeSniffed.iterator(); while(iOnNotToBeSniffed.hasNext()) { AID aid = (AID)iOnNotToBeSniffed.next(); ArrayList l; if (SniffedAgents.containsKey(aid)) { l = (ArrayList)SniffedAgents.get(aid); int ind = l.indexOf(snifferName); if (ind >= 0) l.remove(ind); } } } public void dispatch(ACLMessage msg, AID receiverID) throws RemoteException, NotFoundException { // Mutual exclusion with handleMove() method synchronized(localAgents) { Agent receiver = localAgents.get(receiverID); if(receiver == null) { throw new NotFoundException("DispatchMessage failed to find " + receiverID); } receiver.postMessage(msg); } } public void ping(boolean hang) throws RemoteException { if(hang) { synchronized(pingLock) { try { pingLock.wait(); } catch(InterruptedException ie) { // Do nothing } } } } public String installMTP(String address, String className) throws RemoteException { try { Class c = Class.forName(className); MTP proto = (MTP)c.newInstance(); TransportAddress ta = theACC.addMTP(proto, address); String result = proto.addrToStr(ta); myPlatform.newMTP(result, myName); return result; } catch(ClassNotFoundException cnfe) { System.out.println("ERROR: The class for the IIOP MTP was not found"); return null; } catch(InstantiationException ie) { ie.printStackTrace(); return null; } catch(IllegalAccessException iae) { iae.printStackTrace(); return null; } catch(MTP.MTPException mtpe) { System.out.println("ERROR: Could not initialize MTP from class " + className + "!!!"); mtpe.printStackTrace(); return null; } } public void uninstallMTP(String address) throws RemoteException, NotFoundException { // FIXME: To be implemented } public void updateRoutingTable(int op, String address, AgentContainer ac) throws RemoteException { switch(op) { case ADD_RT: theACC.addRoute(address, ac); break; case DEL_RT: theACC.removeRoute(address, ac); break; } } public void route(Object env, byte[] payload, String address) throws RemoteException, NotFoundException { boolean ok = theACC.routeMessage(env, payload, address); if(!ok) throw new NotFoundException("MTP not found on this container."); } public void joinPlatform(String pID, Iterator agentSpecifiers, String[] MTPs) { // This string will be used to build the GUID for every agent on this platform. platformID = pID; // Build the Agent IDs for the AMS and for the Default DF. Agent.initReservedAIDs(globalAID("ams"), globalAID("df")); try { // Retrieve agent platform from RMI registry and register as agent container String platformRMI = "rmi://" + platformID; myPlatform = lookup3(platformRMI); theACC = new acc(this); InetAddress netAddr = InetAddress.getLocalHost(); myName = myPlatform.addContainer(this, netAddr); // RMI call // Install required MTPs FileWriter f = new FileWriter("MTPs-" + myName + ".txt"); for(int i = 0; i < MTPs.length; i += 2) { String className = MTPs[i]; String addressURL = MTPs[i+1]; if(addressURL.equals("")) addressURL = null; String s = installMTP(addressURL, className); f.write(s, 0, s.length()); f.write('\n'); System.out.println(s); } f.close(); } catch(RemoteException re) { System.err.println("Communication failure while contacting agent platform."); re.printStackTrace(); } catch(Exception e) { System.err.println("Some problem occurred while contacting agent platform."); e.printStackTrace(); } /* Create all agents and set up necessary links for message passing. The link chain is: a) Agent 1 -> AgentContainer1 -- Through CommEvent b) AgentContainer 1 -> AgentContainer 2 -- Through RMI (cached or retreived from MainContainer) c) AgentContainer 2 -> Agent 2 -- Through postMessage() (direct insertion in message queue, no events here) agentSpecifiers is a List of List.Every list contains ,orderly, th a agent name the agent class and the arguments (if any). */ while(agentSpecifiers.hasNext()) { Iterator i = ((List)agentSpecifiers.next()).iterator(); String agentName =(String)i.next(); String agentClass = (String)i.next(); List tmp = new ArrayList(); for ( ; i.hasNext(); ) tmp.add((String)i.next()); //Create the String[] args to pass to the createAgent method int size = tmp.size(); String arguments[] = new String[size]; Iterator it = tmp.iterator(); for(int n = 0; it.hasNext(); n++) arguments[n] = (String)it.next(); AID agentID = globalAID(agentName); try { createAgent(agentID, agentClass, arguments, NOSTART); RemoteProxyRMI rp = new RemoteProxyRMI(this, agentID); myPlatform.bornAgent(agentID, rp, myName); } catch(RemoteException re) { // It should never happen re.printStackTrace(); } catch(NameClashException nce) { System.out.println("Agent name already in use: "+nce.getMessage()); localAgents.remove(agentID); } } // Now activate all agents (this call starts their embedded threads) AID[] allLocalNames = localAgents.keys(); for(int i = 0; i < allLocalNames.length; i++) { AID id = allLocalNames[i]; Agent agent = localAgents.get(id); agent.powerUp(id, agentThreads); } System.out.println("Agent container " + myName + " is ready."); } public void shutDown() { // Shuts down the Timer Dispatcher Agent.stopDispatcher(); // Remove all agents Agent[] allLocalAgents = localAgents.values(); for(int i = 0; i < allLocalAgents.length; i++) { // Kill agent and wait for its termination Agent a = allLocalAgents[i]; a.doDelete(); a.join(); a.resetToolkit(); } // Unblock threads hung in ping() method (this will deregister the container) synchronized(pingLock) { pingLock.notifyAll(); } // Now, close all MTP links to the outside world theACC.shutdown(); } /* * This method returns the vector of the sniffers registered for * theAgent */ private List getSniffer(AID id, java.util.Map theMap) { ArrayList tmp = (ArrayList)theMap.get(id); if (tmp == null) { //might be that the AID is a local agent without '@hap' in its name // then I try it AID fullId = new AID(id.getName()+'@'+getPlatformID()); tmp = (ArrayList)theMap.get(fullId); } return tmp; } /* * Creates the message to be sent to the sniffer. The ontology must be set to * "sniffed-message" otherwise the sniffer doesn't recognize it. The sniffed * message is put in the content field of this message. * * @param theMsg handler of the sniffed message * @param theDests list of the destination (sniffers) */ private void sendMsgToSniffers(ACLMessage theMsg, List theDests){ AID currentSniffer; for (int z = 0; z < theDests.size(); z++) { currentSniffer = (AID)theDests.get(z); ACLMessage SniffedMessage = new ACLMessage(ACLMessage.INFORM); SniffedMessage.clearAllReceiver(); SniffedMessage.addReceiver(currentSniffer); SniffedMessage.setSender(null); SniffedMessage.setContent(theMsg.toString()); SniffedMessage.setOntology("sniffed-message"); unicastPostMessage(SniffedMessage,currentSniffer); } } // Implementation of AgentToolkit interface public void handleSend(ACLMessage msg) { String currentSniffer; List currentSnifferVector; boolean sniffedSource = false; // The AID of the message sender must have the complete GUID AID msgSource = msg.getSender(); if(!livesHere(msgSource)) { String guid = msgSource.getName(); guid = guid.concat("@" + platformID); msgSource.setName(guid); } currentSnifferVector = getSniffer(msgSource, SniffedAgents); if (currentSnifferVector != null) { sniffedSource = true; sendMsgToSniffers(msg, currentSnifferVector); } Iterator it = msg.getAllReceiver(); while(it.hasNext()) { AID dest = (AID)it.next(); currentSnifferVector = getSniffer(dest, SniffedAgents); if((currentSnifferVector != null) && (!sniffedSource)) { sendMsgToSniffers(msg,currentSnifferVector); } // If this AID has no explicit addresses, but it does not seem // to live here, then the platform ID is appended to the AID // name Iterator addresses = dest.getAllAddresses(); if(!addresses.hasNext() && !livesHere(dest)) { String guid = dest.getName(); guid = guid.concat("@" + platformID); dest.setName(guid); } ACLMessage copy = (ACLMessage)msg.clone(); unicastPostMessage(copy, dest); } } public void handleStart(String localName, Agent instance) { AID agentID = globalAID(localName); initAgent(agentID, instance, START); } public void handleEnd(AID agentID) { try { localAgents.remove(agentID); myPlatform.deadAgent(agentID); // RMI call cachedProxies.remove(agentID); // FIXME: It shouldn't be needed } catch(RemoteException re) { re.printStackTrace(); } catch(NotFoundException nfe) { nfe.printStackTrace(); } } public void handleMove(AID agentID, Location where) { // Mutual exclusion with dispatch() method synchronized(localAgents) { try { String proto = where.getProtocol(); if(!proto.equalsIgnoreCase(MobilityOntology.Location.DEFAULT_LOCATION_TP)) throw new NotFoundException("Internal error: Mobility protocol not supported !!!"); String destName = where.getName(); AgentContainer ac = myPlatform.lookup(destName); Agent a = localAgents.get(agentID); if(a == null) throw new NotFoundException("Internal error: handleMove() called with a wrong name !!!"); // Handle special 'running to stand still' case if(where.getName().equalsIgnoreCase(myName)) { a.doExecute(); return; } ByteArrayOutputStream out = new ByteArrayOutputStream(); try { ObjectOutputStream encoder = new ObjectOutputStream(out); encoder.writeObject(a); } catch(IOException ioe) { ioe.printStackTrace(); } byte[] bytes = out.toByteArray(); ac.createAgent(agentID, bytes, this, NOSTART); // Perform an atomic transaction for agent identity transfer boolean transferResult = myPlatform.transferIdentity(agentID, myName, destName); List messages = new ArrayList(); if(transferResult == TRANSFER_COMMIT) { // Send received messages to the destination container Iterator i = a.messages(); while(i.hasNext()) messages.add(i.next()); ac.postTransferResult(agentID, transferResult, messages); // From now on, messages will be routed to the new agent a.doGone(); localAgents.remove(agentID); cachedProxies.remove(agentID); // FIXME: It shouldn't be needed } else { a.doExecute(); ac.postTransferResult(agentID, transferResult, messages); } } catch(RemoteException re) { re.printStackTrace(); // FIXME: Complete undo on exception Agent a = localAgents.get(agentID); if(a != null) a.doDelete(); } catch(NotFoundException nfe) { nfe.printStackTrace(); // FIXME: Complete undo on exception Agent a = localAgents.get(agentID); if(a != null) a.doDelete(); } } } public void handleClone(AID agentID, Location where, String newName) { try { String proto = where.getProtocol(); if(!proto.equalsIgnoreCase(MobilityOntology.Location.DEFAULT_LOCATION_TP)) throw new NotFoundException("Internal error: Mobility protocol not supported !!!"); AgentContainer ac = myPlatform.lookup(where.getName()); Agent a = localAgents.get(agentID); if(a == null) throw new NotFoundException("Internal error: handleCopy() called with a wrong name !!!"); ByteArrayOutputStream out = new ByteArrayOutputStream(); try { ObjectOutputStream encoder = new ObjectOutputStream(out); encoder.writeObject(a); } catch(IOException ioe) { ioe.printStackTrace(); } AID newID = globalAID(newName); byte[] bytes = out.toByteArray(); ac.createAgent(newID, bytes, this, START); } catch(RemoteException re) { re.printStackTrace(); } catch(NotFoundException nfe) { nfe.printStackTrace(); } } protected AID localAID(String agentName) { if(!agentName.endsWith('@' + platformID)) agentName = agentName.concat('@' + platformID); AID id = new AID(); id.setName(agentName); id.clearAllAddresses(); id.clearAllResolvers(); return id; } protected AID globalAID(String agentName) { AID id = localAID(agentName); // FIXME: Add all platform addresses to this AID return id; } // Private methods private boolean livesHere(AID id) { String hap = id.getHap(); return hap.equalsIgnoreCase(platformID); } // This hack is needed to overcome a bug in java.rmi.Naming class: // when an object reference is binded, unbinded and then rebinded // with the same URL, the next two lookup() calls will throw an // Exception without a reason. private MainContainer lookup3(String URL) throws RemoteException, NotBoundException, MalformedURLException, UnknownHostException { java.lang.Object o = null; try { o = Naming.lookup(URL); } catch(RemoteException re1) { // First one try { o = Naming.lookup(URL); } catch(RemoteException re2) { // Second one // Third attempt. If this one fails, there's really // something wrong, so we let the RemoteException go. o = Naming.lookup(URL); } } return (MainContainer)o; } String getPlatformID() { return platformID; } // FIXME: Temporary hack (this should be private) void unicastPostMessage(ACLMessage msg, AID receiverID) { AgentProxy ap = cachedProxies.get(receiverID); if(ap != null) { // Cache hit :-) try { ap.dispatch(msg); } catch(NotFoundException nfe) { // Stale cache entry cachedProxies.remove(receiverID); dispatchUntilOK(msg, receiverID); } } else { // Cache miss :-( dispatchUntilOK(msg, receiverID); } } private void dispatchUntilOK(ACLMessage msg, AID receiverID) { boolean ok; int i = 0; do { AgentProxy proxy; try { proxy = getFreshProxy(receiverID); } catch(NotFoundException nfe) { // Agent not found in GADT: error !!! System.err.println("Agent " + receiverID.getLocalName() + " was not found on agent platform."); System.err.println("Message from platform was: " + nfe.getMessage()); return; } try { proxy.dispatch(msg); cachedProxies.put(receiverID, proxy); ok = true; } catch(acc.NoMoreAddressesException nmae) { // The AID has no more valid addresses System.err.println("Agent " + receiverID.getLocalName() + " has no valid addresses."); return; } catch(NotFoundException nfe) { // Agent not found in destination LADT: need to recheck GADT ok = false; } /* i++; if(i > 100) { // Watchdog counter... System.out.println("==================================================================="); System.out.println(" Possible livelock in message dispatching:"); System.out.println(" Receiver is:"); receiverID.toText(new java.io.OutputStreamWriter(System.out)); System.out.println(); System.out.println(); System.out.println(" Message is:"); msg.toText(new java.io.OutputStreamWriter(System.out)); System.out.println(); System.out.println(); System.out.println("==================================================================="); try { Thread.sleep(3000); } catch(InterruptedException ie) { System.out.println("Interrupted !!!"); } return; } */ } while(!ok); } private AgentProxy getFreshProxy(AID id) throws NotFoundException { AgentProxy result = null; if(livesHere(id)) { // the receiver agent lives in this platform... // Look first in local agents Agent a = localAgents.get(id); if(a != null) { result = new LocalProxy(localAgents, id); } else { // Agent is not local // Maybe it's registered with this AP on some other container... try { result = myPlatform.getProxy(id); // RMI call } catch(RemoteException re) { System.out.println("Communication error while contacting agent platform"); re.printStackTrace(); } } } else { // It lives outside: then it's a job for the ACC... result = theACC.getProxy(id); } return result; } }
src/jade/core/AgentContainerImpl.java
/***************************************************************** JADE - Java Agent DEvelopment Framework is a framework to develop multi-agent systems in compliance with the FIPA specifications. Copyright (C) 2000 CSELT S.p.A. GNU Lesser General Public License This library 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, version 2.1 of the License. This library 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 library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *****************************************************************/ package jade.core; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamClass; import java.io.StringWriter; import java.net.InetAddress; import java.net.MalformedURLException; import java.rmi.*; import java.rmi.server.UnicastRemoteObject; import java.lang.reflect.*; import java.util.Iterator; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.Iterator; import java.util.HashMap; import java.util.Set; import jade.lang.acl.*; import jade.domain.MobilityOntology; import jade.mtp.*; /** @author Giovanni Rimassa - Universita` di Parma @version $Date$ $Revision$ */ class AgentContainerImpl extends UnicastRemoteObject implements AgentContainer, AgentToolkit { private static final int CACHE_SIZE = 10; // Local agents, indexed by agent name protected LADT localAgents = new LADT(); // Agents cache, indexed by agent name private AgentCache cachedProxies = new AgentCache(CACHE_SIZE); // ClassLoader table, used for agent mobility private Map loaders = new HashMap(); // The agent platform this container belongs to protected MainContainer myPlatform; protected String myName; // The Agent Communication Channel, managing the external MTPs. protected acc theACC; // Unique ID of the platform, used to build the GUID of resident // agents. protected String platformID; private Map SniffedAgents = new HashMap(); private String theSniffer; // This monitor is used to hang a remote ping() call from the front // end, in order to detect container failures. private java.lang.Object pingLock = new java.lang.Object(); private ThreadGroup agentThreads = new ThreadGroup("JADE Agents"); private ThreadGroup criticalThreads = new ThreadGroup("JADE time-critical threads"); public AgentContainerImpl() throws RemoteException { // Configure Java runtime system to put the whole host address in RMI messages try { System.getProperties().put("java.rmi.server.hostname", InetAddress.getLocalHost().getHostAddress()); } catch(java.net.UnknownHostException jnue) { jnue.printStackTrace(); } // Set up attributes for agents thread group agentThreads.setMaxPriority(Thread.NORM_PRIORITY); // Set up attributes for time critical threads criticalThreads.setMaxPriority(Thread.MAX_PRIORITY); // Initialize timer dispatcher TimerDispatcher td = new TimerDispatcher(); Thread t = new Thread(criticalThreads, td); t.setPriority(criticalThreads.getMaxPriority()); td.setThread(t); // This call starts the timer dispatcher thread Agent.setDispatcher(td); } // Interface AgentContainer implementation public void createAgent(AID agentID, String className,String[] args, boolean startIt) throws RemoteException { Agent agent = null; try { if(args.length == 0) //no arguments agent = (Agent)Class.forName(new String(className)).newInstance(); else { Class agentDefinition = Class.forName(new String(className)); Class[] stringArgsClass = new Class[]{ String[].class }; Constructor[] constr = agentDefinition.getConstructors(); Constructor stringArgsConstructor = agentDefinition.getConstructor(stringArgsClass); Object[] objArg = new Object[] {args}; agent = (Agent)stringArgsConstructor.newInstance(objArg); } } catch(ClassNotFoundException cnfe) { System.err.println("Class " + className + " for agent " + agentID + " was not found."); return; }catch(java.lang.NoSuchMethodException nsme){ System.err.println("Not found an appropriate constructor for agent " + agentID +" class "+className); return; } catch( Exception e ){ e.printStackTrace(); } initAgent(agentID, agent, startIt); } public void createAgent(AID agentID, byte[] serializedInstance, AgentContainer classSite, boolean startIt) throws RemoteException { final AgentContainer ac = classSite; class Deserializer extends ObjectInputStream { public Deserializer(InputStream inner) throws IOException { super(inner); } protected Class resolveClass(ObjectStreamClass v) throws IOException, ClassNotFoundException { ClassLoader cl = (ClassLoader)loaders.get(ac); if(cl == null) { cl = new JADEClassLoader(ac); loaders.put(ac, cl); } return(cl.loadClass(v.getName())); } } try { ObjectInputStream in = new Deserializer(new ByteArrayInputStream(serializedInstance)); Agent instance = (Agent)in.readObject(); initAgent(agentID, instance, startIt); } catch(IOException ioe) { ioe.printStackTrace(); } catch(ClassNotFoundException cnfe) { cnfe.printStackTrace(); } } // Accepts the fully qualified class name as parameter and searches // the class file in the classpath public byte[] fetchClassFile(String name) throws RemoteException, ClassNotFoundException { name = name.replace( '.' , '/') + ".class"; InputStream classStream = ClassLoader.getSystemResourceAsStream(name); if (classStream == null) throw new ClassNotFoundException(); try { byte[] bytes = new byte[classStream.available()]; classStream.read(bytes); return(bytes); } catch (IOException ioe) { throw new ClassNotFoundException(); } } void initAgent(AID agentID, Agent instance, boolean startIt) { // Subscribe as a listener for the new agent instance.setToolkit(this); // put the agent in the local table and get the previous one, if any Agent previous = localAgents.put(agentID, instance); if(startIt) { try { RemoteProxyRMI rp = new RemoteProxyRMI(this, agentID); myPlatform.bornAgent(agentID, rp, myName); // RMI call instance.powerUp(agentID, agentThreads); } catch(NameClashException nce) { System.out.println("Agentname already in use:"+nce.getMessage()); localAgents.remove(agentID); localAgents.put(agentID,previous); } catch(RemoteException re) { System.out.println("Communication error while adding a new agent to the platform."); re.printStackTrace(); } } } public void suspendAgent(AID agentID) throws RemoteException, NotFoundException { Agent agent = localAgents.get(agentID); if(agent == null) throw new NotFoundException("SuspendAgent failed to find " + agentID); agent.doSuspend(); } public void resumeAgent(AID agentID) throws RemoteException, NotFoundException { Agent agent = localAgents.get(agentID); if(agent == null) throw new NotFoundException("ResumeAgent failed to find " + agentID); agent.doActivate(); } public void waitAgent(AID agentID) throws RemoteException, NotFoundException { Agent agent = localAgents.get(agentID); if(agent==null) throw new NotFoundException("WaitAgent failed to find " + agentID); agent.doWait(); } public void wakeAgent(AID agentID) throws RemoteException, NotFoundException { Agent agent = localAgents.get(agentID); if(agent==null) throw new NotFoundException("WakeAgent failed to find " + agentID); agent.doWake(); } public void moveAgent(AID agentID, Location where) throws RemoteException, NotFoundException { Agent agent = localAgents.get(agentID); if(agent==null) throw new NotFoundException("MoveAgent failed to find " + agentID); agent.doMove(where); } public void copyAgent(AID agentID, Location where, String newName) throws RemoteException, NotFoundException { Agent agent = localAgents.get(agentID); if(agent == null) throw new NotFoundException("CopyAgent failed to find " + agentID); agent.doClone(where, newName); } public void killAgent(AID agentID) throws RemoteException, NotFoundException { Agent agent = localAgents.get(agentID); if(agent == null) throw new NotFoundException("KillAgent failed to find " + agentID); agent.doDelete(); } public void exit() throws RemoteException { shutDown(); System.exit(0); } public void postTransferResult(AID agentID, boolean result, List messages) throws RemoteException, NotFoundException { synchronized(localAgents) { Agent agent = localAgents.get(agentID); if((agent == null)||(agent.getState() != Agent.AP_TRANSIT)) { throw new NotFoundException("postTransferResult() unable to find a suitable agent."); } if(result == TRANSFER_ABORT) localAgents.remove(agentID); else { // Insert received messages at the start of the queue for(int i = messages.size(); i > 0; i--) agent.putBack((ACLMessage)messages.get(i - 1)); agent.powerUp(agentID, agentThreads); } } } /** @param toBeSniffer is an Iterator over the AIDs of agents to be sniffed **/ public void enableSniffer(AID snifferName , List toBeSniffed) throws RemoteException { // In the SniffedAgents hashmap the key is the agent name and the value // is a list containing the sniffer names for that agent Iterator iOnToBeSniffed = toBeSniffed.iterator(); while(iOnToBeSniffed.hasNext()) { AID aid = (AID)iOnToBeSniffed.next(); ArrayList l; if (SniffedAgents.containsKey(aid)) { l = (ArrayList)SniffedAgents.get(aid); if (!l.contains(snifferName)) l.add(snifferName); } else { l = new ArrayList(1); l.add(snifferName); SniffedAgents.put(aid,l); } } } public void disableSniffer(AID snifferName, List notToBeSniffed) throws RemoteException { // In the SniffedAgents hashmap the key is the agent name and the value // is a list containing the sniffer names for that agent Iterator iOnNotToBeSniffed = notToBeSniffed.iterator(); while(iOnNotToBeSniffed.hasNext()) { AID aid = (AID)iOnNotToBeSniffed.next(); ArrayList l; if (SniffedAgents.containsKey(aid)) { l = (ArrayList)SniffedAgents.get(aid); int ind = l.indexOf(snifferName); if (ind >= 0) l.remove(ind); } } } public void dispatch(ACLMessage msg, AID receiverID) throws RemoteException, NotFoundException { // Mutual exclusion with handleMove() method synchronized(localAgents) { Agent receiver = localAgents.get(receiverID); if(receiver == null) { throw new NotFoundException("DispatchMessage failed to find " + receiverID); } receiver.postMessage(msg); } } public void ping(boolean hang) throws RemoteException { if(hang) { synchronized(pingLock) { try { pingLock.wait(); } catch(InterruptedException ie) { // Do nothing } } } } public String installMTP(String address, String className) throws RemoteException { try { Class c = Class.forName(className); MTP proto = (MTP)c.newInstance(); TransportAddress ta = theACC.addMTP(proto, address); return proto.addrToStr(ta); } catch(ClassNotFoundException cnfe) { System.out.println("ERROR: The class for the IIOP MTP was not found"); return null; } catch(InstantiationException ie) { ie.printStackTrace(); return null; } catch(IllegalAccessException iae) { iae.printStackTrace(); return null; } catch(MTP.MTPException mtpe) { System.out.println("ERROR: Could not initialize MTP from class " + className + "!!!"); mtpe.printStackTrace(); return null; } } public void uninstallMTP(String address) throws RemoteException, NotFoundException { // FIXME: To be implemented } public void updateRoutingTable(int op, String address, AgentContainer ac) throws RemoteException { switch(op) { case ADD_RT: theACC.addRoute(address, ac); break; case DEL_RT: theACC.removeRoute(address, ac); break; } } public void route(Object env, byte[] payload, String address) throws RemoteException, NotFoundException { boolean ok = theACC.routeMessage(env, payload, address); if(!ok) throw new NotFoundException("MTP not found on this container."); } public void joinPlatform(String pID, Iterator agentSpecifiers) { // This string will be used to build the GUID for every agent on this platform. platformID = pID; // Build the Agent IDs for the AMS and for the Default DF. Agent.initReservedAIDs(globalAID("ams"), globalAID("df")); try { // Retrieve agent platform from RMI registry and register as agent container String platformRMI = "rmi://" + platformID; myPlatform = lookup3(platformRMI); theACC = new acc(this); InetAddress netAddr = InetAddress.getLocalHost(); myName = myPlatform.addContainer(this, netAddr); // RMI call } catch(RemoteException re) { System.err.println("Communication failure while contacting agent platform."); re.printStackTrace(); } catch(Exception e) { System.err.println("Some problem occurred while contacting agent platform."); e.printStackTrace(); } /* Create all agents and set up necessary links for message passing. The link chain is: a) Agent 1 -> AgentContainer1 -- Through CommEvent b) AgentContainer 1 -> AgentContainer 2 -- Through RMI (cached or retreived from MainContainer) c) AgentContainer 2 -> Agent 2 -- Through postMessage() (direct insertion in message queue, no events here) agentSpecifiers is a List of List.Every list contains ,orderly, th a agent name the agent class and the arguments (if any). */ while(agentSpecifiers.hasNext()) { Iterator i = ((List)agentSpecifiers.next()).iterator(); String agentName =(String)i.next(); String agentClass = (String)i.next(); List tmp = new ArrayList(); for ( ; i.hasNext(); ) tmp.add((String)i.next()); //Create the String[] args to pass to the createAgent method int size = tmp.size(); String arguments[] = new String[size]; Iterator it = tmp.iterator(); for(int n = 0; it.hasNext(); n++) arguments[n] = (String)it.next(); AID agentID = globalAID(agentName); try { createAgent(agentID, agentClass, arguments, NOSTART); RemoteProxyRMI rp = new RemoteProxyRMI(this, agentID); myPlatform.bornAgent(agentID, rp, myName); } catch(RemoteException re) { // It should never happen re.printStackTrace(); } catch(NameClashException nce) { System.out.println("Agent name already in use: "+nce.getMessage()); localAgents.remove(agentID); } } // Now activate all agents (this call starts their embedded threads) AID[] allLocalNames = localAgents.keys(); for(int i = 0; i < allLocalNames.length; i++) { AID id = allLocalNames[i]; Agent agent = localAgents.get(id); agent.powerUp(id, agentThreads); } System.out.println("Agent container " + myName + " is ready."); } public void shutDown() { // Shuts down the Timer Dispatcher Agent.stopDispatcher(); // Remove all agents Agent[] allLocalAgents = localAgents.values(); for(int i = 0; i < allLocalAgents.length; i++) { // Kill agent and wait for its termination Agent a = allLocalAgents[i]; a.doDelete(); a.join(); a.resetToolkit(); } // Unblock threads hung in ping() method (this will deregister the container) synchronized(pingLock) { pingLock.notifyAll(); } // Now, close all MTP links to the outside world theACC.shutdown(); } /* * This method returns the vector of the sniffers registered for * theAgent */ private List getSniffer(AID id, java.util.Map theMap) { ArrayList tmp = (ArrayList)theMap.get(id); if (tmp == null) { //might be that the AID is a local agent without '@hap' in its name // then I try it AID fullId = new AID(id.getName()+'@'+getPlatformID()); tmp = (ArrayList)theMap.get(fullId); } return tmp; } /* * Creates the message to be sent to the sniffer. The ontology must be set to * "sniffed-message" otherwise the sniffer doesn't recognize it. The sniffed * message is put in the content field of this message. * * @param theMsg handler of the sniffed message * @param theDests list of the destination (sniffers) */ private void sendMsgToSniffers(ACLMessage theMsg, List theDests){ AID currentSniffer; for (int z = 0; z < theDests.size(); z++) { currentSniffer = (AID)theDests.get(z); ACLMessage SniffedMessage = new ACLMessage(ACLMessage.INFORM); SniffedMessage.clearAllReceiver(); SniffedMessage.addReceiver(currentSniffer); SniffedMessage.setSender(null); SniffedMessage.setContent(theMsg.toString()); SniffedMessage.setOntology("sniffed-message"); unicastPostMessage(SniffedMessage,currentSniffer); } } // Implementation of AgentToolkit interface public void handleSend(ACLMessage msg) { String currentSniffer; List currentSnifferVector; boolean sniffedSource = false; // The AID of the message sender must have the complete GUID AID msgSource = msg.getSender(); if(!livesHere(msgSource)) { String guid = msgSource.getName(); guid = guid.concat("@" + platformID); msgSource.setName(guid); } currentSnifferVector = getSniffer(msgSource, SniffedAgents); if (currentSnifferVector != null) { sniffedSource = true; sendMsgToSniffers(msg, currentSnifferVector); } Iterator it = msg.getAllReceiver(); while(it.hasNext()) { AID dest = (AID)it.next(); currentSnifferVector = getSniffer(dest, SniffedAgents); if((currentSnifferVector != null) && (!sniffedSource)) { sendMsgToSniffers(msg,currentSnifferVector); } // If this AID has no explicit addresses, but it does not seem // to live here, then the platform ID is appended to the AID // name Iterator addresses = dest.getAllAddresses(); if(!addresses.hasNext() && !livesHere(dest)) { String guid = dest.getName(); guid = guid.concat("@" + platformID); dest.setName(guid); } ACLMessage copy = (ACLMessage)msg.clone(); unicastPostMessage(copy, dest); } } public void handleStart(String localName, Agent instance) { AID agentID = globalAID(localName); initAgent(agentID, instance, START); } public void handleEnd(AID agentID) { try { localAgents.remove(agentID); myPlatform.deadAgent(agentID); // RMI call cachedProxies.remove(agentID); // FIXME: It shouldn't be needed } catch(RemoteException re) { re.printStackTrace(); } catch(NotFoundException nfe) { nfe.printStackTrace(); } } public void handleMove(AID agentID, Location where) { // Mutual exclusion with dispatch() method synchronized(localAgents) { try { String proto = where.getProtocol(); if(!proto.equalsIgnoreCase(MobilityOntology.Location.DEFAULT_LOCATION_TP)) throw new NotFoundException("Internal error: Mobility protocol not supported !!!"); String destName = where.getName(); AgentContainer ac = myPlatform.lookup(destName); Agent a = localAgents.get(agentID); if(a == null) throw new NotFoundException("Internal error: handleMove() called with a wrong name !!!"); // Handle special 'running to stand still' case if(where.getName().equalsIgnoreCase(myName)) { a.doExecute(); return; } ByteArrayOutputStream out = new ByteArrayOutputStream(); try { ObjectOutputStream encoder = new ObjectOutputStream(out); encoder.writeObject(a); } catch(IOException ioe) { ioe.printStackTrace(); } byte[] bytes = out.toByteArray(); ac.createAgent(agentID, bytes, this, NOSTART); // Perform an atomic transaction for agent identity transfer boolean transferResult = myPlatform.transferIdentity(agentID, myName, destName); List messages = new ArrayList(); if(transferResult == TRANSFER_COMMIT) { // Send received messages to the destination container Iterator i = a.messages(); while(i.hasNext()) messages.add(i.next()); ac.postTransferResult(agentID, transferResult, messages); // From now on, messages will be routed to the new agent a.doGone(); localAgents.remove(agentID); cachedProxies.remove(agentID); // FIXME: It shouldn't be needed } else { a.doExecute(); ac.postTransferResult(agentID, transferResult, messages); } } catch(RemoteException re) { re.printStackTrace(); // FIXME: Complete undo on exception Agent a = localAgents.get(agentID); if(a != null) a.doDelete(); } catch(NotFoundException nfe) { nfe.printStackTrace(); // FIXME: Complete undo on exception Agent a = localAgents.get(agentID); if(a != null) a.doDelete(); } } } public void handleClone(AID agentID, Location where, String newName) { try { String proto = where.getProtocol(); if(!proto.equalsIgnoreCase(MobilityOntology.Location.DEFAULT_LOCATION_TP)) throw new NotFoundException("Internal error: Mobility protocol not supported !!!"); AgentContainer ac = myPlatform.lookup(where.getName()); Agent a = localAgents.get(agentID); if(a == null) throw new NotFoundException("Internal error: handleCopy() called with a wrong name !!!"); ByteArrayOutputStream out = new ByteArrayOutputStream(); try { ObjectOutputStream encoder = new ObjectOutputStream(out); encoder.writeObject(a); } catch(IOException ioe) { ioe.printStackTrace(); } AID newID = globalAID(newName); byte[] bytes = out.toByteArray(); ac.createAgent(newID, bytes, this, START); } catch(RemoteException re) { re.printStackTrace(); } catch(NotFoundException nfe) { nfe.printStackTrace(); } } protected AID localAID(String agentName) { if(!agentName.endsWith('@' + platformID)) agentName = agentName.concat('@' + platformID); AID id = new AID(); id.setName(agentName); id.clearAllAddresses(); id.clearAllResolvers(); return id; } protected AID globalAID(String agentName) { AID id = localAID(agentName); // FIXME: Add all platform addresses to this AID return id; } // Private methods private boolean livesHere(AID id) { String hap = id.getHap(); return hap.equalsIgnoreCase(platformID); } // This hack is needed to overcome a bug in java.rmi.Naming class: // when an object reference is binded, unbinded and then rebinded // with the same URL, the next two lookup() calls will throw an // Exception without a reason. private MainContainer lookup3(String URL) throws RemoteException, NotBoundException, MalformedURLException, UnknownHostException { java.lang.Object o = null; try { o = Naming.lookup(URL); } catch(RemoteException re1) { // First one try { o = Naming.lookup(URL); } catch(RemoteException re2) { // Second one // Third attempt. If this one fails, there's really // something wrong, so we let the RemoteException go. o = Naming.lookup(URL); } } return (MainContainer)o; } String getPlatformID() { return platformID; } // FIXME: Temporary hack (this should be private) void unicastPostMessage(ACLMessage msg, AID receiverID) { AgentProxy ap = cachedProxies.get(receiverID); if(ap != null) { // Cache hit :-) try { ap.dispatch(msg); } catch(NotFoundException nfe) { // Stale cache entry cachedProxies.remove(receiverID); dispatchUntilOK(msg, receiverID); } } else { // Cache miss :-( dispatchUntilOK(msg, receiverID); } } private void dispatchUntilOK(ACLMessage msg, AID receiverID) { boolean ok; int i = 0; do { AgentProxy proxy; try { proxy = getFreshProxy(receiverID); } catch(NotFoundException nfe) { // Agent not found in GADT: error !!! System.err.println("Agent " + receiverID.getLocalName() + " was not found on agent platform."); System.err.println("Message from platform was: " + nfe.getMessage()); return; } try { proxy.dispatch(msg); cachedProxies.put(receiverID, proxy); ok = true; } catch(acc.NoMoreAddressesException nmae) { // The AID has no more valid addresses System.err.println("Agent " + receiverID.getLocalName() + " has no valid addresses."); return; } catch(NotFoundException nfe) { // Agent not found in destination LADT: need to recheck GADT ok = false; } /* i++; if(i > 100) { // Watchdog counter... System.out.println("==================================================================="); System.out.println(" Possible livelock in message dispatching:"); System.out.println(" Receiver is:"); receiverID.toText(new java.io.OutputStreamWriter(System.out)); System.out.println(); System.out.println(); System.out.println(" Message is:"); msg.toText(new java.io.OutputStreamWriter(System.out)); System.out.println(); System.out.println(); System.out.println("==================================================================="); try { Thread.sleep(3000); } catch(InterruptedException ie) { System.out.println("Interrupted !!!"); } return; } */ } while(!ok); } private AgentProxy getFreshProxy(AID id) throws NotFoundException { AgentProxy result = null; if(livesHere(id)) { // the receiver agent lives in this platform... // Look first in local agents Agent a = localAgents.get(id); if(a != null) { result = new LocalProxy(localAgents, id); } else { // Agent is not local // Maybe it's registered with this AP on some other container... try { result = myPlatform.getProxy(id); // RMI call } catch(RemoteException re) { System.out.println("Communication error while contacting agent platform"); re.printStackTrace(); } } } else { // It lives outside: then it's a job for the ACC... result = theACC.getProxy(id); } return result; } }
Completed support and fixed a bug in MTP installation code.
src/jade/core/AgentContainerImpl.java
Completed support and fixed a bug in MTP installation code.
Java
lgpl-2.1
3bdaf59549cf9af1b5dc4463f19c2ed70b513abe
0
marc4j/marc4j,jasonzou/marc4j,kylieloo/473marc4j,Dyrcona/marc4j,Dyrcona/marc4j,marc4j/marc4j,kylieloo/473marc4j,jasonzou/marc4j,kylieloo/473marc4j
// $Id: MarcStreamReader.java,v 1.9 2006/12/04 17:39:33 bpeters Exp $ /** * Copyright (C) 2004 Bas Peters * * This file is part of MARC4J * * MARC4J 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 2.1 of the License, or (at your option) any later version. * * MARC4J 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 MARC4J; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.marc4j; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import org.marc4j.marc.ControlField; import org.marc4j.marc.DataField; import org.marc4j.marc.Leader; import org.marc4j.marc.MarcFactory; import org.marc4j.marc.Record; import org.marc4j.marc.Subfield; import org.marc4j.marc.impl.Verifier; /** * An iterator over a collection of MARC records in ISO 2709 format. * <p> * Example usage: * * <pre> * InputStream input = new FileInputStream(&quot;file.mrc&quot;); * MarcReader reader = new MarcStreamReader(input); * while (reader.hasNext()) { * Record record = reader.next(); * // Process record * } * </pre> * * <p> * Check the {@link org.marc4j.marc}&nbsp;package for examples about the use of * the {@link org.marc4j.marc.Record}&nbsp;object model. * </p> * * <p> * When no encoding is given as an constructor argument the parser tries to * resolve the encoding by looking at the character coding scheme (leader * position 9) in MARC21 records. For UNIMARC records this position is not * defined. * </p> * * @author Bas Peters * @version $Revision: 1.9 $ * */ public class MarcStreamReader implements MarcReader { private InputStream input = null; private Record record; private MarcFactory factory; private String encoding = null; private boolean hasNext = true; /** * Constructs an instance with the specified input stream. */ public MarcStreamReader(InputStream input) { this(input, null); } /** * Constructs an instance with the specified input stream and character * encoding. */ public MarcStreamReader(InputStream input, String encoding) { this.input = input; factory = MarcFactory.newInstance(); if (encoding != null) this.encoding = encoding; } /** * Returns true if the iteration has more records, false otherwise. */ public boolean hasNext() { try { if (input.available() == 0) return false; } catch (IOException e) { throw new MarcException(e.getMessage(), e); } return true; } /** * Returns the next record in the iteration. * * @return Record - the record object */ public Record next() { Leader ldr; int bytesRead = 0; record = factory.newRecord(); try { byte[] byteArray = new byte[24]; bytesRead = input.read(byteArray); if (bytesRead == -1) throw new MarcException("no data to read"); while (bytesRead != -1 && bytesRead != byteArray.length) bytesRead += input.read(byteArray, bytesRead, byteArray.length - bytesRead); try { ldr = parseLeader(byteArray); } catch (IOException e) { throw new MarcException("error parsing leader with data: " + new String(byteArray), e); } switch (ldr.getCharCodingScheme()) { case ' ': if (encoding == null) encoding = "ISO8859_1"; break; case 'a': if (encoding == null) encoding = "UTF8"; } record.setLeader(ldr); int directoryLength = ldr.getBaseAddressOfData() - (24 + 1); if ((directoryLength % 12) != 0) throw new MarcException("invalid directory"); int size = directoryLength / 12; String[] tags = new String[size]; int[] lengths = new int[size]; byte[] tag = new byte[3]; byte[] length = new byte[4]; byte[] start = new byte[5]; String tmp; for (int i = 0; i < size; i++) { bytesRead = input.read(tag); while (bytesRead != -1 && bytesRead != tag.length) bytesRead += input.read(tag, bytesRead, tag.length - bytesRead); tmp = new String(tag); tags[i] = tmp; bytesRead = input.read(length); while (bytesRead != -1 && bytesRead != length.length) bytesRead += input.read(length, bytesRead, length.length - bytesRead); tmp = new String(length); lengths[i] = Integer.parseInt(tmp); bytesRead = input.read(start); while (bytesRead != -1 && bytesRead != start.length) bytesRead += input.read(start, bytesRead, start.length - bytesRead); } if (input.read() != Constants.FT) throw new MarcException( "expected field terminator at end of directory"); for (int i = 0; i < size; i++) { if (Verifier.isControlField(tags[i])) { byteArray = new byte[lengths[i] - 1]; bytesRead = input.read(byteArray); while (bytesRead != -1 && bytesRead != byteArray.length) bytesRead += input.read(byteArray, bytesRead, byteArray.length - bytesRead); if (input.read() != Constants.FT) throw new MarcException( "expected field terminator at end of field"); ControlField field = factory.newControlField(); field.setTag(tags[i]); field.setData(getDataAsString(byteArray)); record.addVariableField(field); } else { byteArray = new byte[lengths[i]]; bytesRead = input.read(byteArray); while (bytesRead != -1 && bytesRead != byteArray.length) bytesRead += input.read(byteArray, bytesRead, byteArray.length - bytesRead); try { record.addVariableField(parseDataField(tags[i], byteArray)); } catch (IOException e) { throw new MarcException( "error parsing data field for tag: " + tags[i] + " with data: " + new String(byteArray), e); } } } if (input.read() != Constants.RT) throw new MarcException("expected record terminator"); } catch (IOException e) { throw new MarcException("an error occured reading input", e); } return record; } private DataField parseDataField(String tag, byte[] field) throws IOException { ByteArrayInputStream bais = new ByteArrayInputStream(field); char ind1 = (char) bais.read(); char ind2 = (char) bais.read(); DataField dataField = factory.newDataField(); dataField.setTag(tag); dataField.setIndicator1(ind1); dataField.setIndicator2(ind2); int code; int size; int readByte; byte[] data; Subfield subfield; while (true) { readByte = bais.read(); if (readByte < 0) break; switch (readByte) { case Constants.US: code = bais.read(); if (code < 0) throw new IOException("unexpected end of data field"); if (code == Constants.FT) break; size = getSubfieldLength(bais); data = new byte[size]; bais.read(data); subfield = factory.newSubfield(); subfield.setCode((char) code); subfield.setData(getDataAsString(data)); dataField.addSubfield(subfield); break; case Constants.FT: break; } } return dataField; } private int getSubfieldLength(ByteArrayInputStream bais) throws IOException { bais.mark(9999); int bytesRead = 0; while (true) { switch (bais.read()) { case Constants.US: case Constants.FT: bais.reset(); return bytesRead; case -1: bais.reset(); throw new IOException("subfield not terminated"); default: bytesRead++; } } } private Leader parseLeader(byte[] leaderData) throws IOException { InputStreamReader isr = new InputStreamReader(new ByteArrayInputStream( leaderData)); Leader ldr = factory.newLeader(); char[] tmp = new char[5]; isr.read(tmp); try { ldr.setRecordLength(Integer.parseInt(new String(tmp))); } catch (NumberFormatException e) { throw new MarcException("unable to parse record length", e); } ldr.setRecordStatus((char) isr.read()); ldr.setTypeOfRecord((char) isr.read()); tmp = new char[2]; isr.read(tmp); ldr.setImplDefined1(tmp); ldr.setCharCodingScheme((char) isr.read()); try { ldr.setIndicatorCount(Integer.parseInt(String.valueOf((char) isr .read()))); } catch (NumberFormatException e) { throw new MarcException("unable to parse indicator count", e); } try { ldr.setSubfieldCodeLength(Integer.parseInt(String .valueOf((char) isr.read()))); } catch (NumberFormatException e) { throw new MarcException("unable to parse subfield code length", e); } tmp = new char[5]; isr.read(tmp); try { ldr.setBaseAddressOfData(Integer.parseInt(new String(tmp))); } catch (NumberFormatException e) { throw new MarcException("unable to parse base address of data", e); } tmp = new char[3]; isr.read(tmp); ldr.setImplDefined2(tmp); tmp = new char[4]; isr.read(tmp); ldr.setEntryMap(tmp); isr.close(); return ldr; } private String getDataAsString(byte[] bytes) { String dataElement = null; if (encoding != null) try { dataElement = new String(bytes, encoding); } catch (UnsupportedEncodingException e) { throw new MarcException("unsupported encoding", e); } else dataElement = new String(bytes); return dataElement; } }
src/org/marc4j/MarcStreamReader.java
// $Id: MarcStreamReader.java,v 1.8 2006/12/04 17:37:49 bpeters Exp $ /** * Copyright (C) 2004 Bas Peters * * This file is part of MARC4J * * MARC4J 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 2.1 of the License, or (at your option) any later version. * * MARC4J 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 MARC4J; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.marc4j; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import org.marc4j.marc.ControlField; import org.marc4j.marc.DataField; import org.marc4j.marc.Leader; import org.marc4j.marc.MarcFactory; import org.marc4j.marc.Record; import org.marc4j.marc.Subfield; import org.marc4j.marc.impl.Verifier; /** * An iterator over a collection of MARC records in ISO 2709 format. * <p> * Example usage: * * <pre> * InputStream input = new FileInputStream(&quot;file.mrc&quot;); * MarcReader reader = new MarcStreamReader(input); * while (reader.hasNext()) { * Record record = reader.next(); * // Process record * } * </pre> * * <p> * Check the {@link org.marc4j.marc}&nbsp;package for examples about the use of * the {@link org.marc4j.marc.Record}&nbsp;object model. * </p> * * <p> * When no encoding is given as an constructor argument the parser tries to * resolve the encoding by looking at the character coding scheme (leader * position 9) in MARC21 records. For UNIMARC records this position is not * defined. * </p> * * @author Bas Peters * @version $Revision: 1.8 $ * */ public class MarcStreamReader implements MarcReader { private InputStream input = null; private Record record; private MarcFactory factory; private String encoding = "ISO8859_1"; private boolean hasNext = true; /** * Constructs an instance with the specified input stream. */ public MarcStreamReader(InputStream input) { this(input, null); } /** * Constructs an instance with the specified input stream and character * encoding. */ public MarcStreamReader(InputStream input, String encoding) { this.input = input; factory = MarcFactory.newInstance(); if (encoding != null) this.encoding = encoding; } /** * Returns true if the iteration has more records, false otherwise. */ public boolean hasNext() { try { if (input.available() == 0) return false; } catch (IOException e) { throw new MarcException(e.getMessage(), e); } return true; } /** * Returns the next record in the iteration. * * @return Record - the record object */ public Record next() { Leader ldr; int bytesRead = 0; record = factory.newRecord(); try { byte[] byteArray = new byte[24]; bytesRead = input.read(byteArray); if (bytesRead == -1) throw new MarcException("no data to read"); while (bytesRead != -1 && bytesRead != byteArray.length) bytesRead += input.read(byteArray, bytesRead, byteArray.length - bytesRead); try { ldr = parseLeader(byteArray); } catch (IOException e) { throw new MarcException("error parsing leader with data: " + new String(byteArray), e); } switch (ldr.getCharCodingScheme()) { case ' ': if (encoding == null) encoding = "ISO8859_1"; break; case 'a': if (encoding == null) encoding = "UTF8"; } record.setLeader(ldr); int directoryLength = ldr.getBaseAddressOfData() - (24 + 1); if ((directoryLength % 12) != 0) throw new MarcException("invalid directory"); int size = directoryLength / 12; String[] tags = new String[size]; int[] lengths = new int[size]; byte[] tag = new byte[3]; byte[] length = new byte[4]; byte[] start = new byte[5]; String tmp; for (int i = 0; i < size; i++) { bytesRead = input.read(tag); while (bytesRead != -1 && bytesRead != tag.length) bytesRead += input.read(tag, bytesRead, tag.length - bytesRead); tmp = new String(tag); tags[i] = tmp; bytesRead = input.read(length); while (bytesRead != -1 && bytesRead != length.length) bytesRead += input.read(length, bytesRead, length.length - bytesRead); tmp = new String(length); lengths[i] = Integer.parseInt(tmp); bytesRead = input.read(start); while (bytesRead != -1 && bytesRead != start.length) bytesRead += input.read(start, bytesRead, start.length - bytesRead); } if (input.read() != Constants.FT) throw new MarcException( "expected field terminator at end of directory"); for (int i = 0; i < size; i++) { if (Verifier.isControlField(tags[i])) { byteArray = new byte[lengths[i] - 1]; bytesRead = input.read(byteArray); while (bytesRead != -1 && bytesRead != byteArray.length) bytesRead += input.read(byteArray, bytesRead, byteArray.length - bytesRead); if (input.read() != Constants.FT) throw new MarcException( "expected field terminator at end of field"); ControlField field = factory.newControlField(); field.setTag(tags[i]); field.setData(getDataAsString(byteArray)); record.addVariableField(field); } else { byteArray = new byte[lengths[i]]; bytesRead = input.read(byteArray); while (bytesRead != -1 && bytesRead != byteArray.length) bytesRead += input.read(byteArray, bytesRead, byteArray.length - bytesRead); try { record.addVariableField(parseDataField(tags[i], byteArray)); } catch (IOException e) { throw new MarcException( "error parsing data field for tag: " + tags[i] + " with data: " + new String(byteArray), e); } } } if (input.read() != Constants.RT) throw new MarcException("expected record terminator"); } catch (IOException e) { throw new MarcException("an error occured reading input", e); } return record; } private DataField parseDataField(String tag, byte[] field) throws IOException { ByteArrayInputStream bais = new ByteArrayInputStream(field); char ind1 = (char) bais.read(); char ind2 = (char) bais.read(); DataField dataField = factory.newDataField(); dataField.setTag(tag); dataField.setIndicator1(ind1); dataField.setIndicator2(ind2); int code; int size; int readByte; byte[] data; Subfield subfield; while (true) { readByte = bais.read(); if (readByte < 0) break; switch (readByte) { case Constants.US: code = bais.read(); if (code < 0) throw new IOException("unexpected end of data field"); if (code == Constants.FT) break; size = getSubfieldLength(bais); data = new byte[size]; bais.read(data); subfield = factory.newSubfield(); subfield.setCode((char) code); subfield.setData(getDataAsString(data)); dataField.addSubfield(subfield); break; case Constants.FT: break; } } return dataField; } private int getSubfieldLength(ByteArrayInputStream bais) throws IOException { bais.mark(9999); int bytesRead = 0; while (true) { switch (bais.read()) { case Constants.US: case Constants.FT: bais.reset(); return bytesRead; case -1: bais.reset(); throw new IOException("subfield not terminated"); default: bytesRead++; } } } private Leader parseLeader(byte[] leaderData) throws IOException { InputStreamReader isr = new InputStreamReader(new ByteArrayInputStream( leaderData)); Leader ldr = factory.newLeader(); char[] tmp = new char[5]; isr.read(tmp); try { ldr.setRecordLength(Integer.parseInt(new String(tmp))); } catch (NumberFormatException e) { throw new MarcException("unable to parse record length", e); } ldr.setRecordStatus((char) isr.read()); ldr.setTypeOfRecord((char) isr.read()); tmp = new char[2]; isr.read(tmp); ldr.setImplDefined1(tmp); ldr.setCharCodingScheme((char) isr.read()); try { ldr.setIndicatorCount(Integer.parseInt(String.valueOf((char) isr .read()))); } catch (NumberFormatException e) { throw new MarcException("unable to parse indicator count", e); } try { ldr.setSubfieldCodeLength(Integer.parseInt(String .valueOf((char) isr.read()))); } catch (NumberFormatException e) { throw new MarcException("unable to parse subfield code length", e); } tmp = new char[5]; isr.read(tmp); try { ldr.setBaseAddressOfData(Integer.parseInt(new String(tmp))); } catch (NumberFormatException e) { throw new MarcException("unable to parse base address of data", e); } tmp = new char[3]; isr.read(tmp); ldr.setImplDefined2(tmp); tmp = new char[4]; isr.read(tmp); ldr.setEntryMap(tmp); isr.close(); return ldr; } private String getDataAsString(byte[] bytes) { String dataElement = null; if (encoding != null) try { dataElement = new String(bytes, encoding); } catch (UnsupportedEncodingException e) { throw new MarcException("unsupported encoding", e); } else dataElement = new String(bytes); return dataElement; } }
*** empty log message ***
src/org/marc4j/MarcStreamReader.java
*** empty log message ***
Java
lgpl-2.1
87ccc453ee9d63a36514b7ea7ff39555265ae983
0
simoc/mapyrus,simoc/mapyrus,simoc/mapyrus
/* * This file is part of Mapyrus, software for plotting maps. * Copyright (C) 2003 Simon Chenery. * * Mapyrus is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Mapyrus 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 Mapyrus; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * @(#) $Id$ */ package au.id.chenery.mapyrus; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.geom.AffineTransform; import java.awt.geom.NoninvertibleTransformException; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.HashMap; import java.util.HashSet; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import au.id.chenery.mapyrus.dataset.GeographicDataset; /** * Maintains state information during interpretation inside a single procedure block. * Holds the graphics attributes (color, line styles, transformations, etc.), the * variables set by the user and connections to external data sources. */ public class Context { /* * Units of world coordinate system. */ public static final int WORLD_UNITS_METRES = 1; public static final int WORLD_UNITS_FEET = 2; public static final int WORLD_UNITS_DEGREES = 3; /* * Projection transformation may results in some strange warping. * To get a better estimate of extents when projecting to world coordinate * system we project many points in a grid to find minimum and maximum values. */ private static final int PROJECTED_GRID_STEPS = 5; /* * Page size and resolution to use when no output page defined. */ private static final int DEFAULT_PAGE_WIDTH = 210; private static final int DEFAULT_PAGE_HEIGHT = 297; private static final int DEFAULT_RESOLUTION = 96; /* * Fixed miter limit for line joins. */ private static final float MITER_LIMIT = 10.0f; /* * Graphical attributes */ private Color mColor; private BasicStroke mLinestyle; private int mJustify; private String mFontName; private int mFontStyle; private double mFontSize; private double mFontRotation; /* * Have graphical attributes been set in this context? * Have graphical attributes been changed in this context * since something was last drawn? */ private boolean mAttributesSet; private boolean mAttributesChanged; /* * Transformation matrix and cumulative scaling factors and rotation. */ private AffineTransform mCtm; private double mXScaling; private double mYScaling; private double mScalingMagnitude; private double mRotation; /* * Projection transformation from one world coordinate system to another. */ private WorldCoordinateTransform mProjectionTransform; /* * Transformation matrix from world coordinates to page coordinates * and the units of world coordinates. */ private AffineTransform mWorldCtm; private Rectangle2D.Double mWorldExtents; private int mWorldUnits; /* * Coordinates making up path. */ private GeometricPath mPath; /* * Path in context from which this context was created. * Used when path is not modified in this context to avoid * needlessly copying paths from one context to another. */ private GeometricPath mExistingPath; /* * List of clip polygons making up the complete clipping path. * We need a list of clip polygons instead of a single clip * polygon to preserve the inside/outside of each individual * clip polygon. */ private ArrayList mClippingPaths; /* * Currently defined variables and variables that are local * to this context. */ private HashMap mVars; private HashSet mLocalVars; /* * Output device we are drawing to. */ private OutputFormat mOutputFormat; /* * Flag true if output defined in this context. In this case * we must close the output file when this context is finished. */ private boolean mOutputDefined; /* * Dataset currently being read from, the next row to provide to caller * and the number of rows already fetched from it. */ private Dataset mDataset; /** * Create a new context with reasonable default values. */ public Context() { mColor = Color.GRAY; mLinestyle = new BasicStroke(); mJustify = OutputFormat.JUSTIFY_LEFT | OutputFormat.JUSTIFY_BOTTOM; mFontName = "SansSerif"; mFontStyle = Font.PLAIN; mFontSize = 5; mFontRotation = 0; mCtm = new AffineTransform(); mProjectionTransform = null; mWorldCtm = null; mXScaling = mYScaling = mScalingMagnitude = 1.0; mRotation = 0.0; mVars = null; mLocalVars = null; mPath = null; mClippingPaths = null; mOutputFormat = null; mOutputDefined = false; mAttributesChanged = true; mAttributesSet = false; mDataset = null; } /** * Create a new context, making a copy from an existing context. * @param existing is context to copy from. */ public Context(Context existing) { mColor = existing.mColor; mLinestyle = existing.mLinestyle; mJustify = existing.mJustify; mFontName = existing.mFontName; mFontStyle = existing.mFontStyle; mFontSize = existing.mFontSize; mFontRotation = existing.mFontRotation; mCtm = new AffineTransform(existing.mCtm); mProjectionTransform = null; mWorldCtm = null; mXScaling = existing.mXScaling; mYScaling = existing.mYScaling; mScalingMagnitude = existing.mScalingMagnitude; mRotation = existing.mRotation; mDataset = existing.mDataset; /* * Only create variable lookup tables when some values are * defined locally. */ mVars = null; mLocalVars = null; /* * Don't copy path -- it can be large. * Just keep reference to existing path. * * Create path locally when needed. If path is referenced without * being created then we can reuse path from existing context instead. * * This saves unnecessary copying of paths when contexts are created. */ mPath = null; if (existing.mPath != null) mExistingPath = existing.mPath; else mExistingPath = existing.mExistingPath; /* * Copy list of paths we must clip against. */ if (existing.mClippingPaths != null) mClippingPaths = (ArrayList)(existing.mClippingPaths.clone()); else mClippingPaths = null; mOutputFormat = existing.mOutputFormat; mOutputDefined = false; /* * Save state in parent context so it won't be disturbed by anything * that gets changed in this new context. */ if (mOutputFormat != null) { mOutputFormat.saveState(); } mAttributesChanged = existing.mAttributesChanged; mAttributesSet = false; } private GeometricPath getDefinedPath() { GeometricPath retval; /* * Return path defined in this context, or one defined * in previous context if nothing set here. */ if (mPath != null) retval = mPath; else retval = mExistingPath; return(retval); } /** * Return page width for output we are currently writing. * @return width in millimetres. */ public double getPageWidth() { double retval; if (mOutputFormat == null) retval = 0.0; else retval = mOutputFormat.getPageWidth(); return(retval); } /** * Return page height for output we are currently writing. * @return height in millimetres. */ public double getPageHeight() { double retval; if (mOutputFormat == null) retval = 0.0; else retval = mOutputFormat.getPageHeight(); return(retval); } /** * Return file format for output we are currently writing. * @return file format. */ public String getPageFormat() { String retval; if (mOutputFormat == null) retval = ""; else retval = mOutputFormat.getPageFormat(); return(retval); } /** * Return resolution of page we are writing to as a distance measurement. * @return distance in millimetres between centres of adjacent pixels. */ public double getResolution() throws MapyrusException { double retval; if (mOutputFormat == null) retval = Constants.MM_PER_INCH / DEFAULT_RESOLUTION; else retval = mOutputFormat.getResolution(); return(retval); } /** * Set graphics attributes (color, line width, etc.) if they * have changed since the last time we drew something. */ private void setGraphicsAttributes() { if (mAttributesChanged) { mOutputFormat.setAttributes(mColor, mLinestyle, mJustify, mFontName, mFontStyle, mFontSize, mFontRotation, mClippingPaths); mAttributesChanged = false; } } /** * Flag that graphics attributes have been changed. */ public void setAttributesChanged() { mAttributesChanged = mAttributesSet = true; } /** * Sets output file for drawing to. * @param filename name of image file output will be saved to. * @param format is image format for saving output. * @param width is the page width (in mm). * @param height is the page height (in mm). * @param resolution is resolution for output in dots per inch (DPI) * @param extras contains extra settings for this output. * @param stdoutStream standard output stream for program. */ public void setOutputFormat(String format, String filename, int width, int height, int resolution, String extras, PrintStream stdoutStream) throws IOException, MapyrusException { if (mOutputDefined && mOutputFormat != null) { /* * Finish any previous page before beginning a new one. */ mOutputFormat.closeOutputFormat(); /* * Clear world extents, projection and clip path from previous page. * Other page settings are independent of a particular page so leave * them alone. */ mWorldExtents = null; mWorldCtm = null; mProjectionTransform = null; mClippingPaths = null; } mOutputFormat = new OutputFormat(filename, format, width, height, resolution, extras, stdoutStream); mAttributesChanged = true; mOutputDefined = true; } /** * Closes a context. Any output started in this context is completed, * memory used for context is released. * A context cannot be used again after this call. * @return flag true if graphical attributes were set in this context * and cannot be restored. */ public boolean closeContext() throws IOException, MapyrusException { boolean restoredState; if (mOutputFormat != null && !mOutputDefined) { /* * If state could be restored then no need for caller to set * graphical attributes back to their old values again. */ restoredState = mOutputFormat.restoreState(); if (restoredState) mAttributesSet = false; } if (mOutputDefined) { mOutputFormat.closeOutputFormat(); mOutputFormat = null; mOutputDefined = false; } mPath = mExistingPath = null; mClippingPaths = null; mVars = null; mLocalVars = null; mDataset = null; return(mAttributesSet); } /** * Sets linestyle. * @param width is width for lines in millimetres. * @param cap is a BasicStroke end cap value. * @param join is a BasicStroke line join value. * @param phase is offset at which pattern is started. * @param dashes list of dash pattern lengths. */ public void setLinestyle(double width, int cap, int join, double phase, float []dashes) { /* * Adjust width and dashes by current scaling factor. */ if (dashes == null) { mLinestyle = new BasicStroke((float)(width * mScalingMagnitude), cap, join, MITER_LIMIT); } else { for (int i = 0; i < dashes.length; i++) dashes[i] *= mScalingMagnitude; mLinestyle = new BasicStroke((float)(width * mScalingMagnitude), cap, join, MITER_LIMIT, dashes, (float)phase); } mAttributesChanged = mAttributesSet = true; } /** * Sets color. * @param c is new color for drawing. */ public void setColor(Color color) { mColor = color; mAttributesChanged = mAttributesSet = true; } /** * Sets font for labelling with. * @param fontName is name of font as defined in java.awt.Font class. * @param fontStyle is a style as defined in java.awt.Font class. * @param fontSize is size for labelling in millimetres. */ public void setFont(String fontName, int fontStyle, double fontSize) { mFontName = fontName; mFontStyle = fontStyle; mFontSize = fontSize * mScalingMagnitude; mFontRotation = mRotation; mAttributesChanged = mAttributesSet = true; } /** * Sets horizontal and vertical justification for labelling. * @param code is bit flags of JUSTIFY_* constant values for justification. */ public void setJustify(int code) { mJustify = code; mAttributesChanged = mAttributesSet = true; } /** * Sets scaling for subsequent coordinates. * @param x is new scaling in X axis. * @param y is new scaling in Y axis. */ public void setScaling(double x, double y) { mCtm.scale(x, y); mXScaling *= x; mYScaling *= y; mScalingMagnitude = Math.max(Math.abs(mXScaling), Math.abs(mYScaling)); mAttributesChanged = mAttributesSet = true; } /** * Sets translation for subsequent coordinates. * @param x is new point for origin on X axis. * @param y is new point for origin on Y axis. */ public void setTranslation(double x, double y) { mCtm.translate(x, y); mAttributesChanged = mAttributesSet = true; } /** * Sets rotation for subsequent coordinates. * @param angle is rotation angle in radians, measured counter-clockwise. */ public void setRotation(double angle) { mCtm.rotate(angle); mRotation += angle; mRotation = Math.IEEEremainder(mRotation, Math.PI * 2); mAttributesChanged = mAttributesSet = true; } /** * Sets transformation from real world coordinates to page coordinates. * @param x1 minimum X world coordinate. * @param y1 minimum Y world coordinate. * @param x2 maximum X world coordinate. * @param y2 maximum Y world coordinate. * @param units units of world coordinates (WORLD_UNITS_METRES,WORLD_UNITS_FEET, etc.) */ public void setWorlds(double x1, double y1, double x2, double y2, int units) throws MapyrusException { double xDiff = x2 - x1; double yDiff = y2 - y1; double xMid, yMid; double worldAspectRatio = yDiff / xDiff; double pageAspectRatio; if (mOutputFormat == null) throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.NO_OUTPUT)); pageAspectRatio = mOutputFormat.getPageHeight() / mOutputFormat.getPageWidth(); /* * Expand world coordinate range in either X or Y axis so * it has same aspect ratio as page. */ if (worldAspectRatio > pageAspectRatio) { /* * World coordinate range is taller than page coordinate * system. Expand X axis range to compensate: * * PAGE WORLDS EXPANDED WORLDS * +---+ +---+ +-+---+-+ * | | | | |<| |>| * |___| | | => |<| |>| * | | |<| |>| * +---+ +-+---+-+ */ xMid = (x1 + x2) / 2.0; x1 = xMid - (xDiff / 2.0) * (worldAspectRatio / pageAspectRatio); x2 = xMid + (xDiff / 2.0) * (worldAspectRatio / pageAspectRatio); } else if (worldAspectRatio < pageAspectRatio) { /* * World coordinate range is wider than page coordinate system. * Expand Y axis range. */ yMid = (y1 + y2) / 2.0; y1 = yMid - (yDiff / 2.0) * (pageAspectRatio / worldAspectRatio); y2 = yMid + (yDiff / 2.0) * (pageAspectRatio / worldAspectRatio); } /* * Setup CTM from world coordinates to page coordinates. */ mWorldCtm = new AffineTransform(); mWorldCtm.scale(mOutputFormat.getPageWidth() / (x2 - x1), mOutputFormat.getPageHeight() / (y2 - y1)); mWorldCtm.translate(-x1, -y1); mWorldExtents = new Rectangle2D.Double(x1, y1, x2 - x1, y2 - y1); mWorldUnits = units; } /** * Sets reprojection between two world coordinate systems. * @param sourceSystem description of coordinate system coordinates transformed form. * @param destinationSystem description of coordinate system coordinates * are transformed to. */ public void setReprojection(String sourceSystem, String destinationSystem) throws MapyrusException { mProjectionTransform = new WorldCoordinateTransform(sourceSystem, destinationSystem); } /** * Set current dataset that can be queried and fetched from. * @param dataset opened dataset for subsequent queries. */ public void setDataset(GeographicDataset dataset) throws MapyrusException { mDataset = new Dataset(dataset); } /** * Returns X scaling value in current transformation. * @return X scale value. */ public double getScalingX() { return(mXScaling); } /** * Returns Y scaling value in current transformation. * @return Y scale value */ public double getScalingY() { return(mYScaling); } /** * Returns rotation angle in current transformation. * @return rotation in radians. */ public double getRotation() { return(mRotation); } /** * Returns world coordinate extents being shown on page. * @return rectangular area covered by extents. */ public Rectangle2D.Double getWorldExtents() throws MapyrusException { Rectangle2D.Double retval; if (mWorldExtents != null) { retval = mWorldExtents; } else if (mOutputFormat != null) { retval = new Rectangle2D.Double(0, 0, mOutputFormat.getPageWidth(), mOutputFormat.getPageHeight()); } else { retval = new Rectangle2D.Double(); } return(retval); } /** * Return scale of world coordinates. The world coordinate range divided * by the page size. * @return scale, (1:2000) is returned as value 2000. */ public double getWorldScale() { double scale; double worldWidthInMM; if (mOutputFormat != null && mWorldCtm != null) { worldWidthInMM = mWorldExtents.width; if (mWorldUnits == WORLD_UNITS_METRES) worldWidthInMM *= 1000.0; else if (mWorldUnits == WORLD_UNITS_FEET) worldWidthInMM *= (1000.0 / 0.3048); else worldWidthInMM *= (110000 * 1000.0); scale = worldWidthInMM / mOutputFormat.getPageWidth(); } else { scale = 1.0; } return(scale); } /** * Returns bounding that when transformed through projection results * in same bounding box as current world coordinate system. * @return bounding box. */ public Rectangle2D.Double getUnprojectedExtents() throws MapyrusException { Rectangle2D.Double retval; double xMin, yMin, xMax, yMax; int i, j; double coords[] = new double[2]; xMin = yMin = Float.MAX_VALUE; xMax = yMax = Float.MIN_VALUE; if (mWorldExtents != null) { if (mProjectionTransform != null) { /* * Transform points around boundary of world coordinate extents * backwards through projection transformation. * Find minimum and maximum values. */ for (i = 0; i <= PROJECTED_GRID_STEPS; i++) { for (j = 0; j <= PROJECTED_GRID_STEPS; j++) { /* * Only transform points around boundary. */ if ((i == 0 || i == PROJECTED_GRID_STEPS) && (j == 0 || j == PROJECTED_GRID_STEPS)) { coords[0] = mWorldExtents.x + ((double)i / PROJECTED_GRID_STEPS) * mWorldExtents.width; coords[1] = mWorldExtents.y + ((double)j / PROJECTED_GRID_STEPS) * mWorldExtents.height; mProjectionTransform.backwardTransform(coords); if (coords[0] < xMin) xMin = coords[0]; if (coords[1] < yMin) yMin = coords[1]; if (coords[0] > xMax) xMax = coords[0]; if (coords[1] > yMax) yMax = coords[1]; } } } retval = new Rectangle2D.Double(xMin, yMin, xMax - xMin, yMax - yMin); } else { /* * No projection transformation set so just return plain world * coordinate extents. */ retval = mWorldExtents; } } else if (mOutputFormat != null) { /* * No world coordinate system set, just return page coordinate. */ retval = new Rectangle2D.Double(0, 0, mOutputFormat.getPageWidth(), mOutputFormat.getPageHeight()); } else { retval = new Rectangle2D.Double(0, 0, 1, 1); } return(retval); } /** * Get dataset currently being queried. * @return dataset being queried, or null if not dataset is being queried. */ public Dataset getDataset() { return(mDataset); } /** * Add point to path. * @param x X coordinate to add to path. * @param y Y coordinate to add to path. */ public void moveTo(double x, double y) throws MapyrusException { double srcPts[] = new double[2]; float dstPts[] = new float[2]; srcPts[0] = x; srcPts[1] = y; /* * Transform to correct world coordinate system. */ if (mProjectionTransform != null) { mProjectionTransform.forwardTransform(srcPts); } /* * Transform point from world coordinates * to millimetre position on page. */ if (mWorldCtm != null) mWorldCtm.transform(srcPts, 0, srcPts, 0, 1); mCtm.transform(srcPts, 0, dstPts, 0, 1); if (mPath == null) mPath = new GeometricPath(); /* * Set no rotation for point. */ mPath.moveTo(dstPts[0], dstPts[1], 0.0f); } /** * Add point to path with straight line segment from last point. * @param x X coordinate to add to path. * @param y Y coordinate to add to path. */ public void lineTo(double x, double y) throws MapyrusException { double srcPts[] = new double[2]; float dstPts[] = new float[2]; srcPts[0] = x; srcPts[1] = y; /* * Make sure that a start point for path was defined. */ if (mPath == null || mPath.getMoveToCount() == 0) throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.NO_MOVETO)); /* * Transform to correct world coordinate system. */ if (mProjectionTransform != null) { mProjectionTransform.forwardTransform(srcPts); } /* * Transform point from world coordinates * to millimetre position on page. */ if (mWorldCtm != null) mWorldCtm.transform(srcPts, 0, srcPts, 0, 1); mCtm.transform(srcPts, 0, dstPts, 0, 1); if (mPath == null) mPath = new GeometricPath(); mPath.lineTo(dstPts[0], dstPts[1]); } /** * Add circular arc to path from last point to a new point, given centre and direction. * @param direction positive for clockwise, negative for anti-clockwise. * @param xCentre X coordinate of centre point of arc. * @param yCentre Y coordinate of centre point of arc. * @param xEnd X coordinate of end point of arc. * @param yEnd Y coordinate of end point of arc. */ public void arcTo(int direction, double xCentre, double yCentre, double xEnd, double yEnd) throws MapyrusException { double centrePts[] = new double[2]; double endPts[] = new double[2]; float dstPts[] = new float[4]; centrePts[0] = xCentre; centrePts[1] = yCentre; endPts[0] = xEnd; endPts[1] = yEnd; /* * Make sure that a start point for arc was defined. */ if (mPath == null || mPath.getMoveToCount() == 0) throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.NO_ARC_START)); /* * Transform to correct world coordinate system. */ if (mProjectionTransform != null) { mProjectionTransform.forwardTransform(centrePts); mProjectionTransform.forwardTransform(endPts); } /* * Transform points from world coordinates * to millimetre position on page. */ if (mWorldCtm != null) { mWorldCtm.transform(centrePts, 0, centrePts, 0, 1); mWorldCtm.transform(endPts, 0, endPts, 0, 1); } mCtm.transform(centrePts, 0, dstPts, 0, 1); mCtm.transform(endPts, 0, dstPts, 2, 1); mPath.arcTo(direction, dstPts[0], dstPts[1], dstPts[2], dstPts[3]); } /** * Clears currently defined path. */ public void clearPath() { /* * If a path was defined then clear it. * If no path then clear any path we are using from another * context too. */ if (mPath != null) mPath.reset(); else mExistingPath = null; } /** * Replace path with regularly spaced points along it. * @param spacing is distance between points. * @param offset is starting offset of first point. */ public void samplePath(double spacing, double offset) throws MapyrusException { GeometricPath path = getDefinedPath(); double resolution = getResolution(); if (path != null) { mPath = path.samplePath(spacing * mScalingMagnitude, offset * mScalingMagnitude, resolution); } } /** * Replace path defining polygon with parallel stripe * lines covering the polygon. * @param spacing is distance between stripes. * @param angle is angle of stripes, in radians, with zero horizontal. */ public void stripePath(double spacing, double angle) { GeometricPath path = getDefinedPath(); if (path != null) mPath = path.stripePath(spacing * mScalingMagnitude, angle); } /** * Draw currently defined path. */ public void stroke() { GeometricPath path = getDefinedPath(); if (path != null && mOutputFormat != null) { setGraphicsAttributes(); mOutputFormat.stroke(path.getShape()); } } /** * Fill currently defined path. */ public void fill() { GeometricPath path = getDefinedPath(); if (path != null && mOutputFormat != null) { setGraphicsAttributes(); mOutputFormat.fill(path.getShape()); } } /** * Clip to show only area outside currently defined path, * protecting what is inside path. */ public void protect() throws MapyrusException { GeometricPath path = getDefinedPath(); GeometricPath protectedPath; if (path != null && mOutputFormat != null) { /* * Add a rectangle around the edge of the page as the new polygon * perimeter. The path becomes an island in the polygon (with * opposite direction so winding rule works) and only * the area outside the path is then visible. */ float width = (float)(mOutputFormat.getPageWidth()); float height = (float)(mOutputFormat.getPageHeight()); protectedPath = new GeometricPath(); protectedPath.moveTo(0.0f, 0.0f, 0.0); if (path.isClockwise(getResolution())) { /* * Outer rectange should be anti-clockwise. */ protectedPath.lineTo(width, 0.0f); protectedPath.lineTo(width, height); protectedPath.lineTo(0.0f, height); } else { /* * Outer rectangle should be clockwise. */ protectedPath.lineTo(0.0f, height); protectedPath.lineTo(width, height); protectedPath.lineTo(width, 0.0f); } protectedPath.closePath(); protectedPath.append(path, false); mAttributesChanged = mAttributesSet = true; mOutputFormat.clip(protectedPath.getShape()); /* * Add this polygon to list of paths we are clipping against. */ if (mClippingPaths == null) mClippingPaths = new ArrayList(); mClippingPaths.add(protectedPath); } } /** * Clip to show only inside of currently defined path. */ public void clip() { GeometricPath path = getDefinedPath(); GeometricPath clipPath; if (path != null && mOutputFormat != null) { clipPath = new GeometricPath(path); if (mClippingPaths == null) mClippingPaths = new ArrayList(); mClippingPaths.add(clipPath); mAttributesChanged = mAttributesSet = true; if (mOutputFormat != null) { mOutputFormat.clip(clipPath.getShape()); } } } /** * Draw label positioned at (or along) currently defined path. * @param label is string to draw on page. */ public void label(String label) { GeometricPath path = getDefinedPath(); if (path != null && mOutputFormat != null) { setGraphicsAttributes(); mOutputFormat.label(path.getMoveTos(), label); } } /** * Returns the number of moveTo's in path defined in this context. * @return count of moveTo calls made. */ public int getMoveToCount() { int retval; GeometricPath path = getDefinedPath(); if (path == null) retval = 0; else retval = path.getMoveToCount(); return(retval); } /** * Returns the number of lineTo's in path defined in this context. * @return count of lineTo calls made for this path. */ public int getLineToCount() { int retval; GeometricPath path = getDefinedPath(); if (path == null) retval = 0; else retval = path.getLineToCount(); return(retval); } /** * Returns geometric length of current path. * @return length of current path. */ public double getPathLength() throws MapyrusException { double retval; GeometricPath path = getDefinedPath(); double resolution = getResolution(); if (path == null) retval = 0.0; else retval = path.getLength(resolution); return(retval); } /** * Returns geometric area of current path. * @return area of current path. */ public double getPathArea() throws MapyrusException { double retval; GeometricPath path = getDefinedPath(); double resolution = getResolution(); if (path == null) retval = 0.0; else retval = path.getArea(resolution); return(retval); } /** * Returns geometric centroid of current path. * @return centroid of current path. */ public Point2D.Double getPathCentroid() throws MapyrusException { Point2D.Double retval; GeometricPath path = getDefinedPath(); double resolution = getResolution(); if (path == null) retval = new Point2D.Double(); else retval = path.getCentroid(resolution); return(retval); } /** * Returns rotation angle for each each moveTo point in current path * @return array of rotation angles relative to rotation in current * transformation matrix. */ public ArrayList getMoveToRotations() { ArrayList retval; GeometricPath path = getDefinedPath(); if (path == null) retval = null; else retval = path.getMoveToRotations(); return(retval); } /** * Returns coordinate for each each moveTo point in current path. * @return array of Point2D.Float objects relative to current transformation matrix. */ public ArrayList getMoveTos() throws MapyrusException { ArrayList retval = null; GeometricPath path = getDefinedPath(); AffineTransform inverse; ArrayList moveTos; try { if (path != null) { /* * If there is no transformation matrix then we can return original * coordinates, otherwise we must convert all coordinates to be relative * to the current transformation matrix and build a new list. */ if (mCtm.isIdentity()) { retval = path.getMoveTos(); } else { inverse = mCtm.createInverse(); moveTos = path.getMoveTos(); retval = new ArrayList(moveTos.size()); for (int i = 0; i < moveTos.size(); i++) { Point2D.Float pt = (Point2D.Float)(moveTos.get(i)); retval.add(inverse.transform(pt, null)); } } } } catch (NoninvertibleTransformException e) { throw new MapyrusException(e.getMessage()); } return(retval); } /** * Returns bounding box of this geometry. * @return bounding box, or null if no path is defined. */ public Rectangle2D getBounds2D() { Rectangle2D bounds; GeometricPath path = getDefinedPath(); if (path == null) bounds = null; else bounds = path.getBounds2D(); return(bounds); } /** * Returns value of a variable. * @param variable name to lookup. * @return value of variable, or null if it is not defined. */ public Argument getVariableValue(String varName) { Argument retval; /* * Variable is not set if no lookup table is defined. */ if (mVars == null) retval = null; else retval = (Argument)mVars.get(varName); return(retval); } /** * Indicates that a variable is to be stored locally in this context * and not be made available to other contexts. * @param varName name of variable to be treated as local. */ public void setLocalScope(String varName) { /* * Record that variable is local. */ if (mLocalVars == null) mLocalVars = new HashSet(); mLocalVars.add(varName); } /** * Returns true if variable has been defined local in this context * with @see setLocalScope(). * @param varName is name of variable to check. * @return true if variable defined local. */ public boolean hasLocalScope(String varName) { return(mLocalVars != null && mLocalVars.contains(varName)); } /** * Define variable in current context, replacing any existing * variable with the same name. * @param varName name of variable to define. * @param value is value for this variable */ public void defineVariable(String varName, Argument value) { /* * Create new variable. */ if (mVars == null) mVars = new HashMap(); mVars.put(varName, value); } }
src/org/mapyrus/Context.java
/* * This file is part of Mapyrus, software for plotting maps. * Copyright (C) 2003 Simon Chenery. * * Mapyrus is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Mapyrus 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 Mapyrus; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * @(#) $Id$ */ package au.id.chenery.mapyrus; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.geom.AffineTransform; import java.awt.geom.NoninvertibleTransformException; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.HashMap; import java.util.HashSet; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import au.id.chenery.mapyrus.dataset.GeographicDataset; /** * Maintains state information during interpretation inside a single procedure block. * Holds the graphics attributes (color, line styles, transformations, etc.), the * variables set by the user and connections to external data sources. */ public class Context { /* * Units of world coordinate system. */ public static final int WORLD_UNITS_METRES = 1; public static final int WORLD_UNITS_FEET = 2; public static final int WORLD_UNITS_DEGREES = 3; /* * Projection transformation may results in some strange warping. * To get a better estimate of extents when projecting to world coordinate * system we project many points in a grid to find minimum and maximum values. */ private static final int PROJECTED_GRID_STEPS = 5; /* * Page size and resolution to use when no output page defined. */ private static final int DEFAULT_PAGE_WIDTH = 210; private static final int DEFAULT_PAGE_HEIGHT = 297; private static final int DEFAULT_RESOLUTION = 96; /* * Fixed miter limit for line joins. */ private static final float MITER_LIMIT = 10.0f; /* * Graphical attributes */ private Color mColor; private BasicStroke mLinestyle; private int mJustify; private String mFontName; private int mFontStyle; private double mFontSize; private double mFontRotation; /* * Have graphical attributes been set in this context? * Have graphical attributes been changed in this context * since something was last drawn? */ private boolean mAttributesSet; private boolean mAttributesChanged; /* * Transformation matrix and cumulative scaling factors and rotation. */ private AffineTransform mCtm; private double mXScaling; private double mYScaling; private double mScalingMagnitude; private double mRotation; /* * Projection transformation from one world coordinate system to another. */ private WorldCoordinateTransform mProjectionTransform; /* * Transformation matrix from world coordinates to page coordinates * and the units of world coordinates. */ private AffineTransform mWorldCtm; private Rectangle2D.Double mWorldExtents; private int mWorldUnits; /* * Coordinates making up path. */ private GeometricPath mPath; /* * Path in context from which this context was created. * Used when path is not modified in this context to avoid * needlessly copying paths from one context to another. */ private GeometricPath mExistingPath; /* * List of clip polygons making up the complete clipping path. * We need a list of clip polygons instead of a single clip * polygon to preserve the inside/outside of each individual * clip polygon. */ private ArrayList mClippingPaths; /* * Currently defined variables and variables that are local * to this context. */ private HashMap mVars; private HashSet mLocalVars; /* * Output device we are drawing to. */ private OutputFormat mOutputFormat; /* * Flag true if output defined in this context. In this case * we must close the output file when this context is finished. */ private boolean mOutputDefined; /* * Dataset currently being read from, the next row to provide to caller * and the number of rows already fetched from it. */ private Dataset mDataset; /** * Create a new context with reasonable default values. */ public Context() { mColor = Color.GRAY; mLinestyle = new BasicStroke(); mJustify = OutputFormat.JUSTIFY_LEFT | OutputFormat.JUSTIFY_BOTTOM; mFontName = "SansSerif"; mFontStyle = Font.PLAIN; mFontSize = 5; mFontRotation = 0; mCtm = new AffineTransform(); mProjectionTransform = null; mWorldCtm = null; mXScaling = mYScaling = mScalingMagnitude = 1.0; mRotation = 0.0; mVars = null; mLocalVars = null; mPath = null; mClippingPaths = null; mOutputFormat = null; mOutputDefined = false; mAttributesChanged = true; mAttributesSet = false; mDataset = null; } /** * Create a new context, making a copy from an existing context. * @param existing is context to copy from. */ public Context(Context existing) { mColor = existing.mColor; mLinestyle = existing.mLinestyle; mJustify = existing.mJustify; mFontName = existing.mFontName; mFontStyle = existing.mFontStyle; mFontSize = existing.mFontSize; mFontRotation = existing.mFontRotation; mCtm = new AffineTransform(existing.mCtm); mProjectionTransform = null; mWorldCtm = null; mXScaling = existing.mXScaling; mYScaling = existing.mYScaling; mScalingMagnitude = existing.mScalingMagnitude; mRotation = existing.mRotation; mDataset = existing.mDataset; /* * Only create variable lookup tables when some values are * defined locally. */ mVars = null; mLocalVars = null; /* * Don't copy path -- it can be large. * Just keep reference to existing path. * * Create path locally when needed. If path is referenced without * being created then we can reuse path from existing context instead. * * This saves unnecessary copying of paths when contexts are created. */ mPath = null; if (existing.mPath != null) mExistingPath = existing.mPath; else mExistingPath = existing.mExistingPath; /* * Copy list of paths we must clip against. */ if (existing.mClippingPaths != null) mClippingPaths = (ArrayList)(existing.mClippingPaths.clone()); else mClippingPaths = null; mOutputFormat = existing.mOutputFormat; mOutputDefined = false; /* * Save state in parent context so it won't be disturbed by anything * that gets changed in this new context. */ if (mOutputFormat != null) { mOutputFormat.saveState(); } mAttributesChanged = existing.mAttributesChanged; mAttributesSet = false; } private GeometricPath getDefinedPath() { GeometricPath retval; /* * Return path defined in this context, or one defined * in previous context if nothing set here. */ if (mPath != null) retval = mPath; else retval = mExistingPath; return(retval); } /** * Return page width for output we are currently writing. * @return width in millimetres. */ public double getPageWidth() { double retval; if (mOutputFormat == null) retval = 0.0; else retval = mOutputFormat.getPageWidth(); return(retval); } /** * Return page height for output we are currently writing. * @return height in millimetres. */ public double getPageHeight() { double retval; if (mOutputFormat == null) retval = 0.0; else retval = mOutputFormat.getPageHeight(); return(retval); } /** * Return file format for output we are currently writing. * @return file format. */ public String getPageFormat() { String retval; if (mOutputFormat == null) retval = ""; else retval = mOutputFormat.getPageFormat(); return(retval); } /** * Return resolution of page we are writing to as a distance measurement. * @return distance in millimetres between centres of adjacent pixels. */ public double getResolution() throws MapyrusException { double retval; if (mOutputFormat == null) retval = Constants.MM_PER_INCH / DEFAULT_RESOLUTION; else retval = mOutputFormat.getResolution(); return(retval); } /** * Set graphics attributes (color, line width, etc.) if they * have changed since the last time we drew something. */ private void setGraphicsAttributes() { if (mAttributesChanged) { mOutputFormat.setAttributes(mColor, mLinestyle, mJustify, mFontName, mFontStyle, mFontSize, mFontRotation, mClippingPaths); mAttributesChanged = false; } } /** * Flag that graphics attributes have been changed. */ public void setAttributesChanged() { mAttributesChanged = mAttributesSet = true; } /** * Sets output file for drawing to. * @param filename name of image file output will be saved to. * @param format is image format for saving output. * @param width is the page width (in mm). * @param height is the page height (in mm). * @param resolution is resolution for output in dots per inch (DPI) * @param extras contains extra settings for this output. * @param stdoutStream standard output stream for program. */ public void setOutputFormat(String format, String filename, int width, int height, int resolution, String extras, PrintStream stdoutStream) throws IOException, MapyrusException { if (mOutputDefined && mOutputFormat != null) { /* * Finish any previous page before beginning a new one. */ mOutputFormat.closeOutputFormat(); /* * Clear world extents, projection and clip path from previous page. * Other page settings are independent of a particular page so leave * them alone. */ mWorldExtents = null; mWorldCtm = null; mProjectionTransform = null; mClippingPaths = null; } mOutputFormat = new OutputFormat(filename, format, width, height, resolution, extras, stdoutStream); mAttributesChanged = true; mOutputDefined = true; } /** * Closes a context. Any output started in this context is completed, * memory used for context is released. * A context cannot be used again after this call. * @return flag true if graphical attributes were set in this context * and cannot be restored. */ public boolean closeContext() throws IOException, MapyrusException { boolean restoredState; if (mOutputFormat != null && !mOutputDefined) { /* * If state could be restored then no need for caller to set * graphical attributes back to their old values again. */ restoredState = mOutputFormat.restoreState(); if (restoredState) mAttributesSet = false; } if (mOutputDefined) { mOutputFormat.closeOutputFormat(); mOutputFormat = null; mOutputDefined = false; } mPath = mExistingPath = null; mClippingPaths = null; mVars = null; mLocalVars = null; mDataset = null; return(mAttributesSet); } /** * Sets linestyle. * @param width is width for lines in millimetres. * @param cap is a BasicStroke end cap value. * @param join is a BasicStroke line join value. * @param phase is offset at which pattern is started. * @param dashes list of dash pattern lengths. */ public void setLinestyle(double width, int cap, int join, double phase, float []dashes) { /* * Adjust width and dashes by current scaling factor. */ if (dashes == null) { mLinestyle = new BasicStroke((float)(width * mScalingMagnitude), cap, join, MITER_LIMIT); } else { for (int i = 0; i < dashes.length; i++) dashes[i] *= mScalingMagnitude; mLinestyle = new BasicStroke((float)(width * mScalingMagnitude), cap, join, MITER_LIMIT, dashes, (float)phase); } mAttributesChanged = mAttributesSet = true; } /** * Sets color. * @param c is new color for drawing. */ public void setColor(Color color) { mColor = color; mAttributesChanged = mAttributesSet = true; } /** * Sets font for labelling with. * @param fontName is name of font as defined in java.awt.Font class. * @param fontStyle is a style as defined in java.awt.Font class. * @param fontSize is size for labelling in millimetres. */ public void setFont(String fontName, int fontStyle, double fontSize) { mFontName = fontName; mFontStyle = fontStyle; mFontSize = fontSize * mScalingMagnitude; mFontRotation = mRotation; mAttributesChanged = mAttributesSet = true; } /** * Sets horizontal and vertical justification for labelling. * @param code is bit flags of JUSTIFY_* constant values for justification. */ public void setJustify(int code) { mJustify = code; mAttributesChanged = mAttributesSet = true; } /** * Sets scaling for subsequent coordinates. * @param x is new scaling in X axis. * @param y is new scaling in Y axis. */ public void setScaling(double x, double y) { mCtm.scale(x, y); mXScaling *= x; mYScaling *= y; mScalingMagnitude = Math.max(Math.abs(mXScaling), Math.abs(mYScaling)); mAttributesChanged = mAttributesSet = true; } /** * Sets translation for subsequent coordinates. * @param x is new point for origin on X axis. * @param y is new point for origin on Y axis. */ public void setTranslation(double x, double y) { mCtm.translate(x, y); mAttributesChanged = mAttributesSet = true; } /** * Sets rotation for subsequent coordinates. * @param angle is rotation angle in radians, measured counter-clockwise. */ public void setRotation(double angle) { mCtm.rotate(angle); mRotation += angle; mRotation = Math.IEEEremainder(mRotation, Math.PI * 2); mAttributesChanged = mAttributesSet = true; } /** * Sets transformation from real world coordinates to page coordinates. * @param x1 minimum X world coordinate. * @param y1 minimum Y world coordinate. * @param x2 maximum X world coordinate. * @param y2 maximum Y world coordinate. * @param units units of world coordinates (WORLD_UNITS_METRES,WORLD_UNITS_FEET, etc.) */ public void setWorlds(double x1, double y1, double x2, double y2, int units) throws MapyrusException { double xDiff = x2 - x1; double yDiff = y2 - y1; double xMid, yMid; double worldAspectRatio = yDiff / xDiff; double pageAspectRatio; if (mOutputFormat == null) throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.NO_OUTPUT)); pageAspectRatio = mOutputFormat.getPageHeight() / mOutputFormat.getPageWidth(); /* * Expand world coordinate range in either X or Y axis so * it has same aspect ratio as page. */ if (worldAspectRatio > pageAspectRatio) { /* * World coordinate range is taller than page coordinate * system. Expand X axis range to compensate: * * PAGE WORLDS EXPANDED WORLDS * +---+ +---+ +-+---+-+ * | | | | |<| |>| * |___| | | => |<| |>| * | | |<| |>| * +---+ +-+---+-+ */ xMid = (x1 + x2) / 2.0; x1 = xMid - (xDiff / 2.0) * (worldAspectRatio / pageAspectRatio); x2 = xMid + (xDiff / 2.0) * (worldAspectRatio / pageAspectRatio); } else if (worldAspectRatio < pageAspectRatio) { /* * World coordinate range is wider than page coordinate system. * Expand Y axis range. */ yMid = (y1 + y2) / 2.0; y1 = yMid - (yDiff / 2.0) * (pageAspectRatio / worldAspectRatio); y2 = yMid + (yDiff / 2.0) * (pageAspectRatio / worldAspectRatio); } /* * Setup CTM from world coordinates to page coordinates. */ mWorldCtm = new AffineTransform(); mWorldCtm.scale(mOutputFormat.getPageWidth() / (x2 - x1), mOutputFormat.getPageHeight() / (y2 - y1)); mWorldCtm.translate(-x1, -y1); mWorldExtents = new Rectangle2D.Double(x1, y1, x2 - x1, y2 - y1); mWorldUnits = units; } /** * Sets reprojection between two world coordinate systems. * @param sourceSystem description of coordinate system coordinates transformed form. * @param destinationSystem description of coordinate system coordinates * are transformed to. */ public void setReprojection(String sourceSystem, String destinationSystem) throws MapyrusException { mProjectionTransform = new WorldCoordinateTransform(sourceSystem, destinationSystem); } /** * Set current dataset that can be queried and fetched from. * @param dataset opened dataset for subsequent queries. */ public void setDataset(GeographicDataset dataset) throws MapyrusException { mDataset = new Dataset(dataset); } /** * Returns X scaling value in current transformation. * @return X scale value. */ public double getScalingX() { return(mXScaling); } /** * Returns Y scaling value in current transformation. * @return Y scale value */ public double getScalingY() { return(mYScaling); } /** * Returns rotation angle in current transformation. * @return rotation in radians. */ public double getRotation() { return(mRotation); } /** * Returns world coordinate extents being shown on page. * @return rectangular area covered by extents. */ public Rectangle2D.Double getWorldExtents() throws MapyrusException { Rectangle2D.Double retval; if (mWorldExtents != null) { retval = mWorldExtents; } else if (mOutputFormat != null) { retval = new Rectangle2D.Double(0, 0, mOutputFormat.getPageWidth(), mOutputFormat.getPageHeight()); } else { retval = new Rectangle2D.Double(); } return(retval); } /** * Return scale of world coordinates. The world coordinate range divided * by the page size. * @return scale, (1:2000) is returned as value 2000. */ public double getWorldScale() { double scale; double worldWidthInMM; if (mOutputFormat != null && mWorldCtm != null) { worldWidthInMM = mWorldExtents.width; if (mWorldUnits == WORLD_UNITS_METRES) worldWidthInMM *= 1000.0; else if (mWorldUnits == WORLD_UNITS_FEET) worldWidthInMM *= (1000.0 / 0.3048); else worldWidthInMM *= (110000 * 1000.0); scale = worldWidthInMM / mOutputFormat.getPageWidth(); } else { scale = 1.0; } return(scale); } /** * Returns bounding that when transformed through projection results * in same bounding box as current world coordinate system. * @return bounding box. */ public Rectangle2D.Double getUnprojectedExtents() throws MapyrusException { Rectangle2D.Double retval; double xMin, yMin, xMax, yMax; int i, j; double coords[] = new double[2]; xMin = yMin = Float.MAX_VALUE; xMax = yMax = Float.MIN_VALUE; if (mWorldExtents != null) { if (mProjectionTransform != null) { /* * Transform points around boundary of world coordinate extents * backwards through projection transformation. * Find minimum and maximum values. */ for (i = 0; i <= PROJECTED_GRID_STEPS; i++) { for (j = 0; j <= PROJECTED_GRID_STEPS; j++) { /* * Only transform points around boundary. */ if ((i == 0 || i == PROJECTED_GRID_STEPS) && (j == 0 || j == PROJECTED_GRID_STEPS)) { coords[0] = mWorldExtents.x + ((double)i / PROJECTED_GRID_STEPS) * mWorldExtents.width; coords[1] = mWorldExtents.y + ((double)j / PROJECTED_GRID_STEPS) * mWorldExtents.height; mProjectionTransform.backwardTransform(coords); if (coords[0] < xMin) xMin = coords[0]; if (coords[1] < yMin) yMin = coords[1]; if (coords[0] > xMax) xMax = coords[0]; if (coords[1] > yMax) yMax = coords[1]; } } } retval = new Rectangle2D.Double(xMin, yMin, xMax - xMin, yMax - yMin); } else { /* * No projection transformation set so just return plain world * coordinate extents. */ retval = mWorldExtents; } } else if (mOutputFormat != null) { /* * No world coordinate system set, just return page coordinate. */ retval = new Rectangle2D.Double(0, 0, mOutputFormat.getPageWidth(), mOutputFormat.getPageHeight()); } else { retval = new Rectangle2D.Double(0, 0, 1, 1); } return(retval); } /** * Get dataset currently being queried. * @return dataset being queried, or null if not dataset is being queried. */ public Dataset getDataset() { return(mDataset); } /** * Add point to path. * @param x X coordinate to add to path. * @param y Y coordinate to add to path. */ public void moveTo(double x, double y) throws MapyrusException { double srcPts[] = new double[2]; float dstPts[] = new float[2]; srcPts[0] = x; srcPts[1] = y; /* * Transform to correct world coordinate system. */ if (mProjectionTransform != null) { mProjectionTransform.forwardTransform(srcPts); } /* * Transform point from world coordinates * to millimetre position on page. */ if (mWorldCtm != null) mWorldCtm.transform(srcPts, 0, srcPts, 0, 1); mCtm.transform(srcPts, 0, dstPts, 0, 1); if (mPath == null) mPath = new GeometricPath(); /* * Set no rotation for point. */ mPath.moveTo(dstPts[0], dstPts[1], 0.0f); } /** * Add point to path with straight line segment from last point. * @param x X coordinate to add to path. * @param y Y coordinate to add to path. */ public void lineTo(double x, double y) throws MapyrusException { double srcPts[] = new double[2]; float dstPts[] = new float[2]; srcPts[0] = x; srcPts[1] = y; /* * Make sure that a start point for path was defined. */ if (mPath == null || mPath.getMoveToCount() == 0) throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.NO_MOVETO)); /* * Transform to correct world coordinate system. */ if (mProjectionTransform != null) { mProjectionTransform.forwardTransform(srcPts); } /* * Transform point from world coordinates * to millimetre position on page. */ if (mWorldCtm != null) mWorldCtm.transform(srcPts, 0, srcPts, 0, 1); mCtm.transform(srcPts, 0, dstPts, 0, 1); if (mPath == null) mPath = new GeometricPath(); mPath.lineTo(dstPts[0], dstPts[1]); } /** * Add circular arc to path from last point to a new point, given centre and direction. * @param direction positive for clockwise, negative for anti-clockwise. * @param xCentre X coordinate of centre point of arc. * @param yCentre Y coordinate of centre point of arc. * @param xEnd X coordinate of end point of arc. * @param yEnd Y coordinate of end point of arc. */ public void arcTo(int direction, double xCentre, double yCentre, double xEnd, double yEnd) throws MapyrusException { double centrePts[] = new double[2]; double endPts[] = new double[2]; float dstPts[] = new float[4]; centrePts[0] = xCentre; centrePts[1] = yCentre; endPts[0] = xEnd; endPts[1] = yEnd; /* * Make sure that a start point for arc was defined. */ if (mPath == null || mPath.getMoveToCount() == 0) throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.NO_ARC_START)); /* * Transform to correct world coordinate system. */ if (mProjectionTransform != null) { mProjectionTransform.forwardTransform(centrePts); mProjectionTransform.forwardTransform(endPts); } /* * Transform points from world coordinates * to millimetre position on page. */ if (mWorldCtm != null) { mWorldCtm.transform(centrePts, 0, centrePts, 0, 1); mWorldCtm.transform(endPts, 0, endPts, 0, 1); } mCtm.transform(centrePts, 0, dstPts, 0, 1); mCtm.transform(endPts, 0, dstPts, 2, 1); mPath.arcTo(direction, dstPts[0], dstPts[1], dstPts[2], dstPts[3]); } /** * Clears currently defined path. */ public void clearPath() { /* * If a path was defined then clear it. * If no path then clear any path we are using from another * context too. */ if (mPath != null) mPath.reset(); else mExistingPath = null; } /** * Replace path with regularly spaced points along it. * @param spacing is distance between points. * @param offset is starting offset of first point. */ public void samplePath(double spacing, double offset) throws MapyrusException { GeometricPath path = getDefinedPath(); double resolution = getResolution(); if (path != null) { mPath = path.samplePath(spacing * mScalingMagnitude, offset * mScalingMagnitude, resolution); } } /** * Replace path defining polygon with parallel stripe * lines covering the polygon. * @param spacing is distance between stripes. * @param angle is angle of stripes, in radians, with zero horizontal. */ public void stripePath(double spacing, double angle) { GeometricPath path = getDefinedPath(); if (path != null) mPath = path.stripePath(spacing * mScalingMagnitude, angle); } /** * Draw currently defined path. */ public void stroke() { GeometricPath path = getDefinedPath(); if (path != null && mOutputFormat != null) { setGraphicsAttributes(); mOutputFormat.stroke(path.getShape()); } } /** * Fill currently defined path. */ public void fill() { GeometricPath path = getDefinedPath(); if (path != null && mOutputFormat != null) { setGraphicsAttributes(); mOutputFormat.fill(path.getShape()); } } /** * Clip to show only area outside currently defined path, * protecting what is inside path. */ public void protect() throws MapyrusException { GeometricPath path = getDefinedPath(); GeometricPath protectedPath; if (path != null && mOutputFormat != null) { /* * Add a rectangle around the edge of the page as the new polygon * perimeter. The path becomes an island in the polygon (with * opposite direction so winding rule works) and only * the area outside the path is then visible. */ float width = (float)(mOutputFormat.getPageWidth()); float height = (float)(mOutputFormat.getPageHeight()); protectedPath = new GeometricPath(); protectedPath.moveTo(0.0f, 0.0f, 0.0); if (path.isClockwise(getResolution())) { /* * Outer rectange should be anti-clockwise. */ protectedPath.lineTo(width, 0.0f); protectedPath.lineTo(width, height); protectedPath.lineTo(0.0f, height); } else { /* * Outer rectangle should be clockwise. */ protectedPath.lineTo(0.0f, height); protectedPath.lineTo(width, height); protectedPath.lineTo(width, 0.0f); } protectedPath.closePath(); protectedPath.append(path, false); mAttributesChanged = mAttributesSet = true; mOutputFormat.clip(protectedPath.getShape()); /* * Add this polygon to list of paths we are clipping against. */ if (mClippingPaths == null) mClippingPaths = new ArrayList(); mClippingPaths.add(protectedPath); } } /** * Clip to show only inside of currently defined path. */ public void clip() { GeometricPath path = getDefinedPath(); GeometricPath clipPath; if (path != null && mOutputFormat != null) { clipPath = new GeometricPath(path); if (mClippingPaths == null) mClippingPaths = new ArrayList(); mClippingPaths.add(clipPath); mAttributesChanged = mAttributesSet = true; if (mOutputFormat != null) { mOutputFormat.clip(clipPath.getShape()); } } } /** * Draw label positioned at (or along) currently defined path. * @param label is string to draw on page. */ public void label(String label) { GeometricPath path = getDefinedPath(); if (path != null && mOutputFormat != null) { setGraphicsAttributes(); mOutputFormat.label(path.getMoveTos(), label); } } /** * Returns the number of moveTo's in path defined in this context. * @return count of moveTo calls made. */ public int getMoveToCount() { int retval; GeometricPath path = getDefinedPath(); if (path == null) retval = 0; else retval = path.getMoveToCount(); return(retval); } /** * Returns the number of lineTo's in path defined in this context. * @return count of lineTo calls made for this path. */ public int getLineToCount() { int retval; GeometricPath path = getDefinedPath(); if (path == null) retval = 0; else retval = path.getLineToCount(); return(retval); } /** * Returns geometric length of current path. * @return length of current path. */ public double getPathLength() throws MapyrusException { double retval; GeometricPath path = getDefinedPath(); double resolution = getResolution(); if (path == null) retval = 0.0; else retval = path.getLength(resolution); return(retval); } /** * Returns geometric area of current path. * @return area of current path. */ public double getPathArea() throws MapyrusException { double retval; GeometricPath path = getDefinedPath(); double resolution = getResolution(); if (path == null) retval = 0.0; else retval = path.getArea(resolution); return(retval); } /** * Returns geometric centroid of current path. * @return centroid of current path. */ public Point2D.Double getPathCentroid() throws MapyrusException { Point2D.Double retval; GeometricPath path = getDefinedPath(); double resolution = getResolution(); if (path == null) retval = new Point2D.Double(); else retval = path.getCentroid(resolution); return(retval); } /** * Returns rotation angle for each each moveTo point in current path * @return array of rotation angles relative to rotation in current * transformation matrix. */ public ArrayList getMoveToRotations() { ArrayList retval; ArrayList list; double rotation; GeometricPath path = getDefinedPath(); if (path == null) retval = null; else retval = path.getMoveToRotations(); return(retval); } /** * Returns coordinate for each each moveTo point in current path. * @return array of Point2D.Float objects relative to current transformation matrix. */ public ArrayList getMoveTos() throws MapyrusException { ArrayList retval = null; GeometricPath path = getDefinedPath(); AffineTransform inverse; ArrayList moveTos; try { if (path != null) { /* * If there is no transformation matrix then we can return original * coordinates, otherwise we must convert all coordinates to be relative * to the current transformation matrix and build a new list. */ if (mCtm.isIdentity()) { retval = path.getMoveTos(); } else { inverse = mCtm.createInverse(); moveTos = path.getMoveTos(); retval = new ArrayList(moveTos.size()); for (int i = 0; i < moveTos.size(); i++) { Point2D.Float pt = (Point2D.Float)(moveTos.get(i)); retval.add(inverse.transform(pt, null)); } } } } catch (NoninvertibleTransformException e) { throw new MapyrusException(e.getMessage()); } return(retval); } /** * Returns bounding box of this geometry. * @return bounding box, or null if no path is defined. */ public Rectangle2D getBounds2D() { Rectangle2D bounds; GeometricPath path = getDefinedPath(); if (path == null) bounds = null; else bounds = path.getBounds2D(); return(bounds); } /** * Returns value of a variable. * @param variable name to lookup. * @return value of variable, or null if it is not defined. */ public Argument getVariableValue(String varName) { Argument retval; /* * Variable is not set if no lookup table is defined. */ if (mVars == null) retval = null; else retval = (Argument)mVars.get(varName); return(retval); } /** * Indicates that a variable is to be stored locally in this context * and not be made available to other contexts. * @param varName name of variable to be treated as local. */ public void setLocalScope(String varName) { /* * Record that variable is local. */ if (mLocalVars == null) mLocalVars = new HashSet(); mLocalVars.add(varName); } /** * Returns true if variable has been defined local in this context * with @see setLocalScope(). * @param varName is name of variable to check. * @return true if variable defined local. */ public boolean hasLocalScope(String varName) { return(mLocalVars != null && mLocalVars.contains(varName)); } /** * Define variable in current context, replacing any existing * variable with the same name. * @param varName name of variable to define. * @param value is value for this variable */ public void defineVariable(String varName, Argument value) { /* * Create new variable. */ if (mVars == null) mVars = new HashMap(); mVars.put(varName, value); } }
Remove unused variables.
src/org/mapyrus/Context.java
Remove unused variables.
Java
lgpl-2.1
92658db56862a8ce20339638d3bc78b3a15f4893
0
sbliven/biojava,sbliven/biojava,sbliven/biojava
/* * BioJava development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the individual * authors. These should be listed in @author doc comments. * * For more information on the BioJava project and its aims, * or to join the biojava-l mailing list, visit the home page * at: * * http://www.biojava.org/ * * Created on 05.03.2004 * @author Andreas Prlic * */ package org.biojava.bio.structure; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.biojava.bio.structure.io.PDBParseException; /** * * Generic Implementation of a Group interface. * AminoAcidImpl and NucleotideImpl are closely related classes. * @see AminoAcidImpl * @see NucleotideImpl * @author Andreas Prlic * @author Horvath Tamas * @version %I% %G% * @since 1.4 */ public class HetatomImpl implements Group,Serializable { /** * */ private static final long serialVersionUID = 4491470432023820382L; /** this is a "hetatm". * */ public static final String type = GroupType.HETATM ; Map<String, Object> properties ; long id; /* stores if 3d coordinates are available. */ protected boolean pdb_flag ; /* 3 letter name of amino acid in pdb file. */ protected String pdb_name ; /* pdb numbering. */ protected String pdb_code ; protected List<Atom> atoms ; Chain parent; Map<String,Atom> atomLookup = new HashMap<String,Atom>(); /* Construct a Hetatom instance. */ public HetatomImpl() { super(); pdb_flag = false; pdb_name = null ; pdb_code = null ; atoms = new ArrayList<Atom>(); properties = new HashMap<String,Object>(); parent = null; } /* returns an identical copy of this structure public Object clone() { Hetatom n = new Hetatom(); } */ /** * returns true or false, depending if this group has 3D coordinates or not. * @return true if Group has 3D coordinates */ public boolean has3D() { return pdb_flag; } /** flag if group has 3D data. * * @param flag true to set flag that this Group has 3D coordinates */ public void setPDBFlag(boolean flag){ pdb_flag = flag ; } /** * Returns the PDBCode. * @see #setPDBCode * @return a String representing the PDBCode value */ public String getPDBCode() { return pdb_code; } /** set the PDB code. * @see #getPDBCode */ public void setPDBCode(String pdb) { pdb_code = pdb ; } /** set three character name of Group . * * @param s a String specifying the PDBName value * @see #getPDBName * @throws PDBParseException ... */ public void setPDBName(String s) throws PDBParseException { // hetatoms can have pdb_name length < 3. e.g. CU (see 1a4a position 1200 ) //if (s.length() != 3) { //throw new PDBParseException("amino acid name is not of length 3!"); //} pdb_name =s ; } /** * Returns the PDBName. * * @return a String representing the PDBName value * @see #setPDBName */ public String getPDBName() { return pdb_name;} /** add an atom to this group. */ public void addAtom(Atom atom){ atom.setParent(this); atoms.add(atom); if (atom.getCoords() != null){ // we have got coordinates! setPDBFlag(true); } atomLookup.put(atom.getName(),atom); }; /** remove all atoms * */ public void clearAtoms() { atoms.clear(); setPDBFlag(false); atomLookup.clear(); } /** getnumber of atoms. * @return number of atoms */ public int size(){ return atoms.size(); } /** get all atoms of this group . * returns a List of all atoms in this Group * @return an List object representing the atoms value */ public List<Atom> getAtoms(){ //Atom[] atms = (Atom[])atoms.toArray(new Atom[atoms.size()]); return atoms ; } /** set the atoms of this group * @see org.biojava.bio.structure.Atom * @param atoms a list of atoms */ public void setAtoms(List<Atom> atoms){ for (Atom a: atoms){ a.setParent(this); atomLookup.put(a.getName(), a); } this.atoms = atoms; if ( atoms.size() > 0) { pdb_flag = true; } } /** get an atom throws StructureException if atom not found. * @param name a String * @return an Atom object * @throws StructureException ... */ public Atom getAtom(String name) throws StructureException { // todo: add speedup by internal hashmap... Atom a = atomLookup.get(name); if ( a != null) return a; // something is deeply wrong... for (int i=0;i<atoms.size();i++){ Atom atom = atoms.get(i); if ( name.length() > 2) { if ( atom.getFullName().equals(name)){ return atom; } } if (atom.getName().equals(name)){ if ( name.equals("CA")) { if (atom.getElement().equals(Element.C)) return atom; } } } throw new StructureException(" No atom "+name + " in group " + pdb_name + " " + pdb_code + " !"); } /** Get an atom by the full PDB name e.g. " N " for N. Throws StructureException if atom not found. * @param name a String * @return an Atom object * @throws StructureException ... */ public Atom getAtomByPDBname(String name) throws StructureException { for (int i=0;i<atoms.size();i++){ Atom atom = atoms.get(i); if (atom.getFullName().equals(name)){ return atom; } } throw new StructureException(" No atom "+name + " in group " + pdb_name + " " + pdb_code + " !"); } /** return an atom by its position in the internal List. * * @param position an int * @return an Atom object * @throws StructureException ... */ public Atom getAtom(int position) throws StructureException { if ((position < 0)|| ( position >= atoms.size())) { throw new StructureException("No atom found at position "+position); } Atom a = atoms.get(position); return a ; } /** test is an Atom with name is existing. */ public boolean hasAtom(String name){ Atom a = atomLookup.get(name); if ( a != null) return true; return false; // for (int i=0;i<atoms.size();i++){ // Atom atom = atoms.get(i); // if (atom.getName().equals(name)){ // return true; // } // } // return false ; } /** * Returns the type value. * * @return a String representing the type value */ public String getType(){ return type;} public String toString(){ String str = "Hetatom "+ pdb_code + " " + pdb_name + " "+ pdb_flag; if (pdb_flag) { str = str + " atoms: "+atoms.size(); } return str ; } /** calculate if a groups has all atoms required for an amino acid this allows to include chemically modified amino acids that are labeled hetatoms into some computations ... the usual way to identify if a group is an amino acid is getType() ! <p> amino atoms are : N, CA, C, O, CB GLY does not have CB (unless we would calculate some artificially </p> Example: 1DW9 chain A first group is a Selenomethionine, provided as HETATM, but here returns true. <pre> HETATM 1 N MSE A 1 11.720 20.973 1.584 0.00 0.00 N HETATM 2 CA MSE A 1 10.381 20.548 1.139 0.00 0.00 C HETATM 3 C MSE A 1 9.637 20.037 2.398 0.00 0.00 C HETATM 4 O MSE A 1 10.198 19.156 2.985 0.00 0.00 O HETATM 5 CB MSE A 1 10.407 19.441 0.088 0.00 0.00 C </pre> @see #getType */ public boolean hasAminoAtoms(){ // if this method call is performed too often, it should become a // private method and provide a flag for Group object ... String[] atoms ; if ( getType().equals("amino") & getPDBName().equals("GLY")){ atoms = new String[] { "N","CA","C","O"}; } else { atoms = new String[] { "N","CA","C","O","CB" }; } for (int i = 0 ; i < atoms.length; i++) { if ( ! hasAtom(atoms[i])) { //System.out.println("not amino atoms"); return false ; } } return true ; } /** properties of this amino acid. currerntly available properties. * are: * phi * psi * * @see #getProperties */ public void setProperties(Map<String,Object> props) { properties = props ; } /** return properties. * * @return a HashMap object representing the properties value * @see #setProperties */ public Map<String, Object> getProperties() { return properties ; } /** set a single property . * * @see #getProperties * @see #getProperty */ public void setProperty(String key, Object value){ properties.put(key,value); } /** get a single property . * @param key a String * @return an Object * @see #setProperty * @see #setProperties */ public Object getProperty(String key){ return properties.get(key); } /** return an AtomIterator. * * @return an Iterator object */ public Iterator<Atom> iterator() { Iterator<Atom> iter = new AtomIterator(this); return iter ; } /** returns and identical copy of this Group object . * @return and identical copy of this Group object */ public Object clone(){ HetatomImpl n = new HetatomImpl(); n.setPDBFlag(has3D()); n.setPDBCode(getPDBCode()); try { n.setPDBName(getPDBName()); } catch (PDBParseException e) { e.printStackTrace(); } // copy the atoms for (int i=0;i<atoms.size();i++){ Atom atom = atoms.get(i); n.addAtom((Atom)atom.clone()); } return n; } /** Set the back-reference (to its parent Chain) * @param parent the parent Chain */ public void setParent(Chain parent) { this.parent = parent ; } /** Returns the parent Chain of the Group * * @return Chain the Chain object that contains the Group * * */ public Chain getParent() { return parent; } /** the Hibernate database ID * * @return the id */ public long getId() { return id; } /** the Hibernate database ID * * @param id the hibernate id */ public void setId(long id) { this.id = id; } }
structure/src/main/java/org/biojava/bio/structure/HetatomImpl.java
/* * BioJava development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the individual * authors. These should be listed in @author doc comments. * * For more information on the BioJava project and its aims, * or to join the biojava-l mailing list, visit the home page * at: * * http://www.biojava.org/ * * Created on 05.03.2004 * @author Andreas Prlic * */ package org.biojava.bio.structure; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.biojava.bio.structure.io.PDBParseException; /** * * Generic Implementation of a Group interface. * AminoAcidImpl and NucleotideImpl are closely related classes. * @see AminoAcidImpl * @see NucleotideImpl * @author Andreas Prlic * @author Horvath Tamas * @version %I% %G% * @since 1.4 */ public class HetatomImpl implements Group,Serializable { /** * */ private static final long serialVersionUID = 4491470432023820382L; /** this is a "hetatm". * */ public static final String type = GroupType.HETATM ; Map<String, Object> properties ; long id; /* stores if 3d coordinates are available. */ protected boolean pdb_flag ; /* 3 letter name of amino acid in pdb file. */ protected String pdb_name ; /* pdb numbering. */ protected String pdb_code ; protected List<Atom> atoms ; Chain parent; Map<String,Atom> atomLookup = new HashMap<String,Atom>(); /* Construct a Hetatom instance. */ public HetatomImpl() { super(); pdb_flag = false; pdb_name = null ; pdb_code = null ; atoms = new ArrayList<Atom>(); properties = new HashMap<String,Object>(); parent = null; } /* returns an identical copy of this structure public Object clone() { Hetatom n = new Hetatom(); } */ /** * returns true or false, depending if this group has 3D coordinates or not. * @return true if Group has 3D coordinates */ public boolean has3D() { return pdb_flag; } /** flag if group has 3D data. * * @param flag true to set flag that this Group has 3D coordinates */ public void setPDBFlag(boolean flag){ pdb_flag = flag ; } /** * Returns the PDBCode. * @see #setPDBCode * @return a String representing the PDBCode value */ public String getPDBCode() { return pdb_code; } /** set the PDB code. * @see #getPDBCode */ public void setPDBCode(String pdb) { pdb_code = pdb ; } /** set three character name of Group . * * @param s a String specifying the PDBName value * @see #getPDBName * @throws PDBParseException ... */ public void setPDBName(String s) throws PDBParseException { // hetatoms can have pdb_name length < 3. e.g. CU (see 1a4a position 1200 ) //if (s.length() != 3) { //throw new PDBParseException("amino acid name is not of length 3!"); //} pdb_name =s ; } /** * Returns the PDBName. * * @return a String representing the PDBName value * @see #setPDBName */ public String getPDBName() { return pdb_name;} /** add an atom to this group. */ public void addAtom(Atom atom){ atom.setParent(this); atoms.add(atom); if (atom.getCoords() != null){ // we have got coordinates! setPDBFlag(true); } atomLookup.put(atom.getName(),atom); }; /** remove all atoms * */ public void clearAtoms() { atoms.clear(); setPDBFlag(false); atomLookup.clear(); } /** getnumber of atoms. * @return number of atoms */ public int size(){ return atoms.size(); } /** get all atoms of this group . * returns a List of all atoms in this Group * @return an List object representing the atoms value */ public List<Atom> getAtoms(){ //Atom[] atms = (Atom[])atoms.toArray(new Atom[atoms.size()]); return atoms ; } /** set the atoms of this group * @see org.biojava.bio.structure.Atom * @param atoms a list of atoms */ public void setAtoms(List<Atom> atoms){ for (Atom a: atoms){ a.setParent(this); atomLookup.put(a.getName(), a); } this.atoms = atoms; if ( atoms.size() > 0) { pdb_flag = true; } } /** get an atom throws StructureException if atom not found. * @param name a String * @return an Atom object * @throws StructureException ... */ public Atom getAtom(String name) throws StructureException { // todo: add speedup by internal hashmap... Atom a = atomLookup.get(name); if ( a != null) return a; // something is deeply wrong... for (int i=0;i<atoms.size();i++){ Atom atom = atoms.get(i); if (atom.getName().equals(name)){ if ( name.equals("CA")) { if (atom.getElement().equals(Element.C)) return atom; } } } throw new StructureException(" No atom "+name + " in group " + pdb_name + " " + pdb_code + " !"); } /** Get an atom by the full PDB name e.g. " N " for N. Throws StructureException if atom not found. * @param name a String * @return an Atom object * @throws StructureException ... */ public Atom getAtomByPDBname(String name) throws StructureException { for (int i=0;i<atoms.size();i++){ Atom atom = atoms.get(i); if (atom.getFullName().equals(name)){ return atom; } } throw new StructureException(" No atom "+name + " in group " + pdb_name + " " + pdb_code + " !"); } /** return an atom by its position in the internal List. * * @param position an int * @return an Atom object * @throws StructureException ... */ public Atom getAtom(int position) throws StructureException { if ((position < 0)|| ( position >= atoms.size())) { throw new StructureException("No atom found at position "+position); } Atom a = atoms.get(position); return a ; } /** test is an Atom with name is existing. */ public boolean hasAtom(String name){ Atom a = atomLookup.get(name); if ( a != null) return true; return false; // for (int i=0;i<atoms.size();i++){ // Atom atom = atoms.get(i); // if (atom.getName().equals(name)){ // return true; // } // } // return false ; } /** * Returns the type value. * * @return a String representing the type value */ public String getType(){ return type;} public String toString(){ String str = "Hetatom "+ pdb_code + " " + pdb_name + " "+ pdb_flag; if (pdb_flag) { str = str + " atoms: "+atoms.size(); } return str ; } /** calculate if a groups has all atoms required for an amino acid this allows to include chemically modified amino acids that are labeled hetatoms into some computations ... the usual way to identify if a group is an amino acid is getType() ! <p> amino atoms are : N, CA, C, O, CB GLY does not have CB (unless we would calculate some artificially </p> Example: 1DW9 chain A first group is a Selenomethionine, provided as HETATM, but here returns true. <pre> HETATM 1 N MSE A 1 11.720 20.973 1.584 0.00 0.00 N HETATM 2 CA MSE A 1 10.381 20.548 1.139 0.00 0.00 C HETATM 3 C MSE A 1 9.637 20.037 2.398 0.00 0.00 C HETATM 4 O MSE A 1 10.198 19.156 2.985 0.00 0.00 O HETATM 5 CB MSE A 1 10.407 19.441 0.088 0.00 0.00 C </pre> @see #getType */ public boolean hasAminoAtoms(){ // if this method call is performed too often, it should become a // private method and provide a flag for Group object ... String[] atoms ; if ( getType().equals("amino") & getPDBName().equals("GLY")){ atoms = new String[] { "N","CA","C","O"}; } else { atoms = new String[] { "N","CA","C","O","CB" }; } for (int i = 0 ; i < atoms.length; i++) { if ( ! hasAtom(atoms[i])) { //System.out.println("not amino atoms"); return false ; } } return true ; } /** properties of this amino acid. currerntly available properties. * are: * phi * psi * * @see #getProperties */ public void setProperties(Map<String,Object> props) { properties = props ; } /** return properties. * * @return a HashMap object representing the properties value * @see #setProperties */ public Map<String, Object> getProperties() { return properties ; } /** set a single property . * * @see #getProperties * @see #getProperty */ public void setProperty(String key, Object value){ properties.put(key,value); } /** get a single property . * @param key a String * @return an Object * @see #setProperty * @see #setProperties */ public Object getProperty(String key){ return properties.get(key); } /** return an AtomIterator. * * @return an Iterator object */ public Iterator<Atom> iterator() { Iterator<Atom> iter = new AtomIterator(this); return iter ; } /** returns and identical copy of this Group object . * @return and identical copy of this Group object */ public Object clone(){ HetatomImpl n = new HetatomImpl(); n.setPDBFlag(has3D()); n.setPDBCode(getPDBCode()); try { n.setPDBName(getPDBName()); } catch (PDBParseException e) { e.printStackTrace(); } // copy the atoms for (int i=0;i<atoms.size();i++){ Atom atom = atoms.get(i); n.addAtom((Atom)atom.clone()); } return n; } /** Set the back-reference (to its parent Chain) * @param parent the parent Chain */ public void setParent(Chain parent) { this.parent = parent ; } /** Returns the parent Chain of the Group * * @return Chain the Chain object that contains the Group * * */ public Chain getParent() { return parent; } /** the Hibernate database ID * * @return the id */ public long getId() { return id; } /** the Hibernate database ID * * @param id the hibernate id */ public void setId(long id) { this.id = id; } }
now making sure not to return Calcium's when Calpha atoms are requested git-svn-id: ed25c26de1c5325e8eb0deed0b990ab8af8a4def@7765 7c6358e6-4a41-0410-a743-a5b2a554c398
structure/src/main/java/org/biojava/bio/structure/HetatomImpl.java
now making sure not to return Calcium's when Calpha atoms are requested
Java
apache-2.0
68c716430c82023a9ed6146621530d6f7a3a6c93
0
sonamuthu/rice-1,kuali/kc-rice,kuali/kc-rice,kuali/kc-rice,jwillia/kc-rice1,shahess/rice,gathreya/rice-kc,smith750/rice,bsmith83/rice-1,shahess/rice,rojlarge/rice-kc,bsmith83/rice-1,geothomasp/kualico-rice-kc,bhutchinson/rice,ewestfal/rice,ewestfal/rice-svn2git-test,jwillia/kc-rice1,smith750/rice,gathreya/rice-kc,shahess/rice,geothomasp/kualico-rice-kc,UniversityOfHawaiiORS/rice,UniversityOfHawaiiORS/rice,sonamuthu/rice-1,smith750/rice,bhutchinson/rice,rojlarge/rice-kc,ewestfal/rice,ewestfal/rice-svn2git-test,jwillia/kc-rice1,rojlarge/rice-kc,sonamuthu/rice-1,cniesen/rice,geothomasp/kualico-rice-kc,bhutchinson/rice,gathreya/rice-kc,rojlarge/rice-kc,smith750/rice,shahess/rice,gathreya/rice-kc,jwillia/kc-rice1,ewestfal/rice-svn2git-test,kuali/kc-rice,UniversityOfHawaiiORS/rice,cniesen/rice,gathreya/rice-kc,geothomasp/kualico-rice-kc,UniversityOfHawaiiORS/rice,rojlarge/rice-kc,bsmith83/rice-1,jwillia/kc-rice1,ewestfal/rice,bsmith83/rice-1,UniversityOfHawaiiORS/rice,shahess/rice,ewestfal/rice,kuali/kc-rice,bhutchinson/rice,smith750/rice,ewestfal/rice-svn2git-test,cniesen/rice,cniesen/rice,cniesen/rice,sonamuthu/rice-1,bhutchinson/rice,geothomasp/kualico-rice-kc,ewestfal/rice
/* * Copyright 2007 The Kuali Foundation. * * Licensed under the Educational Community License, Version 1.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/ecl1.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.kns.service; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.persistence.EntityManagerFactory; import org.kuali.rice.core.resourceloader.GlobalResourceLoader; import org.kuali.rice.core.resourceloader.RiceResourceLoaderFactory; import org.kuali.rice.core.resourceloader.SpringResourceLoader; import org.kuali.rice.core.service.EncryptionService; import org.kuali.rice.kns.dao.BusinessObjectDao; import org.kuali.rice.kns.dao.DocumentDao; import org.kuali.rice.kns.dbplatform.KualiDBPlatform; import org.kuali.rice.kns.inquiry.Inquirable; import org.kuali.rice.kns.lookup.LookupResultsService; import org.kuali.rice.kns.lookup.Lookupable; import org.kuali.rice.kns.question.Question; import org.kuali.rice.kns.util.OjbCollectionHelper; import org.kuali.rice.kns.util.cache.MethodCacheInterceptor; import org.kuali.rice.kns.util.spring.NamedOrderedListBean; import org.kuali.rice.kns.workflow.service.KualiWorkflowInfo; import org.kuali.rice.kns.workflow.service.WorkflowDocumentService; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.support.TransactionTemplate; import com.opensymphony.oscache.general.GeneralCacheAdministrator; public class KNSServiceLocator<T extends Object> { public static final String VALIDATION_COMPLETION_UTILS = "validationCompletionUtils"; public static Object getService(String serviceName) { return GlobalResourceLoader.getService(serviceName); } public static <T> T getNervousSystemContextBean(Class<T> type) { Collection<T> beansOfType = getBeansOfType(type).values(); if (beansOfType.isEmpty()) { throw new NoSuchBeanDefinitionException("No beans of this type in the KNS application context: " + type.getName()); } if (beansOfType.size() > 1) { return getNervousSystemContextBean(type, type.getSimpleName().substring(0, 1).toLowerCase() + type.getSimpleName().substring(1)); } return beansOfType.iterator().next(); } @SuppressWarnings("unchecked") public static <T> T getNervousSystemContextBean(Class<T> type, String name) { return (T) RiceResourceLoaderFactory.getSpringResourceLoader().getContext().getBean(name); } @SuppressWarnings("unchecked") public static <T> Map<String, T> getBeansOfType(Class<T> type) { SpringResourceLoader springResourceLoader = RiceResourceLoaderFactory.getSpringResourceLoader(); if ( springResourceLoader != null ) { return new HashMap((Map) springResourceLoader.getContext().getBeansOfType(type)); } else { return new HashMap(0); } } public static String[] getBeanNames() { return RiceResourceLoaderFactory.getSpringResourceLoader().getContext().getBeanDefinitionNames(); } public static Set<String> getSingletonNames() { Set<String> singletonNames = new HashSet<String>(); Collections.addAll(singletonNames, RiceResourceLoaderFactory.getSpringResourceLoader().getContext().getBeanFactory() .getSingletonNames()); return singletonNames; } public static Set<Class> getSingletonTypes() { Set<Class> singletonTypes = new HashSet<Class>(); for (String singletonName : getSingletonNames()) { singletonTypes.add(RiceResourceLoaderFactory.getSpringResourceLoader().getContext().getBeanFactory().getType( singletonName)); } return singletonTypes; } public static boolean isSingleton( String beanName ) { try { return RiceResourceLoaderFactory.getSpringResourceLoader().getContext().getBeanFactory().isSingleton(beanName); } catch ( NoSuchBeanDefinitionException ex ) { // service is not in Spring so we can't assume return false; } } public static List<NamedOrderedListBean> getNamedOrderedListBeans(String listName) { List<NamedOrderedListBean> namedOrderedListBeans = new ArrayList<NamedOrderedListBean>(); for (Object namedOrderedListBean : RiceResourceLoaderFactory.getSpringResourceLoader().getContext().getBeansOfType( NamedOrderedListBean.class).values()) { if (((NamedOrderedListBean) namedOrderedListBean).getName().equals(listName)) { namedOrderedListBeans.add((NamedOrderedListBean) namedOrderedListBean); } } return namedOrderedListBeans; } public static final String ENCRYPTION_SERVICE = "encryptionService"; public static final EncryptionService getEncryptionService() { return (EncryptionService) getService(ENCRYPTION_SERVICE); } public static final String EXCEPTION_INCIDENT_REPORT_SERVICE = "knsExceptionIncidentService"; public static final KualiExceptionIncidentService getKualiExceptionIncidentService() { return (KualiExceptionIncidentService) getService(EXCEPTION_INCIDENT_REPORT_SERVICE); } public static final String MAIL_SERVICE = "mailService"; public static final MailService getMailService() { return (MailService) getService(MAIL_SERVICE); } public static final String METHOD_CACHE_INTERCEPTOR = "methodCacheInterceptor"; public static MethodCacheInterceptor getMethodCacheInterceptor() { return (MethodCacheInterceptor) getService(METHOD_CACHE_INTERCEPTOR); } public static final String BUSINESS_OBJECT_AUTHORIZATION_SERVICE = "businessObjectAuthorizationService"; public static BusinessObjectAuthorizationService getBusinessObjectAuthorizationService() { return (BusinessObjectAuthorizationService) getService(BUSINESS_OBJECT_AUTHORIZATION_SERVICE); } public static final String XML_OBJECT_SERIALIZER_SERVICE = "xmlObjectSerializerService"; public static XmlObjectSerializerService getXmlObjectSerializerService() { return (XmlObjectSerializerService) getService(XML_OBJECT_SERIALIZER_SERVICE); } public static final String DOCUMENT_SERVICE = "documentService"; public static DocumentService getDocumentService() { return (DocumentService) getService(DOCUMENT_SERVICE); } public static final String DOCUMENT_HEADER_SERVICE = "documentHeaderService"; public static DocumentHeaderService getDocumentHeaderService() { return (DocumentHeaderService) getService(DOCUMENT_HEADER_SERVICE); } public static final String POST_PROCESSOR_SERVICE = "postProcessorService"; public static PostProcessorService getPostProcessorService() { return (PostProcessorService) getService(POST_PROCESSOR_SERVICE); } public static final String DATETIME_SERVICE = "dateTimeService"; public static DateTimeService getDateTimeService() { return (DateTimeService) getService(DATETIME_SERVICE); } public static final String LOOKUP_SERVICE = "lookupService"; public static LookupService getLookupService() { return (LookupService) getService(LOOKUP_SERVICE); } public static final String LOOKUP_RESULTS_SERVICE = "lookupResultsService"; public static LookupResultsService getLookupResultsService() { return (LookupResultsService) getService(LOOKUP_RESULTS_SERVICE); } public static final String KUALI_MODULE_SERVICE = "kualiModuleService"; public static KualiModuleService getKualiModuleService() { return (KualiModuleService) getService(KUALI_MODULE_SERVICE); } public static final String WORKFLOW_DOCUMENT_SERVICE = "workflowDocumentService"; public static WorkflowDocumentService getWorkflowDocumentService() { return (WorkflowDocumentService) getService(WORKFLOW_DOCUMENT_SERVICE); } public static final String WORKFLOW_INFO_SERVICE = "workflowInfoService"; public static KualiWorkflowInfo getWorkflowInfoService() { return (KualiWorkflowInfo) getService(WORKFLOW_INFO_SERVICE); } public static final String KUALI_CONFIGURATION_SERVICE = "kualiConfigurationService"; public static KualiConfigurationService getKualiConfigurationService() { return (KualiConfigurationService) getService(KUALI_CONFIGURATION_SERVICE); } public static final String BUSINESS_OBJECT_DICTIONARY_SERVICE = "businessObjectDictionaryService"; public static BusinessObjectDictionaryService getBusinessObjectDictionaryService() { return (BusinessObjectDictionaryService) getService(BUSINESS_OBJECT_DICTIONARY_SERVICE); } public static final String BUSINESS_OBJECT_METADATA_SERVICE = "businessObjectMetaDataService"; public static BusinessObjectMetaDataService getBusinessObjectMetaDataService() { return (BusinessObjectMetaDataService) getService(BUSINESS_OBJECT_METADATA_SERVICE); } public static final String TRANSACTIONAL_DOCUMENT_DICTIONARY_SERVICE = "transactionalDocumentDictionaryService"; public static TransactionalDocumentDictionaryService getTransactionalDocumentDictionaryService() { return (TransactionalDocumentDictionaryService) getService(TRANSACTIONAL_DOCUMENT_DICTIONARY_SERVICE); } public static final String MAINTENANCE_DOCUMENT_DICTIONARY_SERVICE = "maintenanceDocumentDictionaryService"; public static MaintenanceDocumentDictionaryService getMaintenanceDocumentDictionaryService() { return (MaintenanceDocumentDictionaryService) getService(MAINTENANCE_DOCUMENT_DICTIONARY_SERVICE); } public static final String DATA_DICTIONARY_SERVICE = "dataDictionaryService"; public static DataDictionaryService getDataDictionaryService() { return (DataDictionaryService) getService(DATA_DICTIONARY_SERVICE); } public static final String MAINTENANCE_DOCUMENT_SERVICE = "maintenanceDocumentService"; public static MaintenanceDocumentService getMaintenanceDocumentService() { return (MaintenanceDocumentService) getService(MAINTENANCE_DOCUMENT_SERVICE); } public static final String NOTE_SERVICE = "noteService"; public static NoteService getNoteService() { return (NoteService) getService(NOTE_SERVICE); } public static final String PERSISTENCE_SERVICE = "persistenceService"; public static PersistenceService getPersistenceService() { return (PersistenceService) getService(PERSISTENCE_SERVICE); } public static final String PERSISTENCE_STRUCTURE_SERVICE = "persistenceStructureService"; public static PersistenceStructureService getPersistenceStructureService() { return (PersistenceStructureService) getService(PERSISTENCE_STRUCTURE_SERVICE); } public static final String KUALI_RULE_SERVICE = "kualiRuleService"; public static KualiRuleService getKualiRuleService() { return (KualiRuleService) getService(KUALI_RULE_SERVICE); } public static final String BUSINESS_OBJECT_SERVICE = "businessObjectService"; public static BusinessObjectService getBusinessObjectService() { return (BusinessObjectService) getService(BUSINESS_OBJECT_SERVICE); } // special ones for Inquirable and Lookupable public static final String KUALI_INQUIRABLE = "kualiInquirable"; public static Inquirable getKualiInquirable() { return (Inquirable) getService(KUALI_INQUIRABLE); } public static final String KUALI_LOOKUPABLE = "kualiLookupable"; public static Lookupable getKualiLookupable() { return (Lookupable) getService(KUALI_LOOKUPABLE); } public static Lookupable getLookupable(String lookupableName) { return (Lookupable) getService(lookupableName); } // special one for QuestionPrompt public static Question getQuestion(String questionName) { return (Question) getService(questionName); } // DictionaryValidationService public static final String DICTIONARY_VALIDATION_SERVICE = "dictionaryValidationService"; public static DictionaryValidationService getDictionaryValidationService() { return (DictionaryValidationService) getService(DICTIONARY_VALIDATION_SERVICE); } // AttachmentService public static final String ATTACHMENT_SERVICE = "attachmentService"; public static AttachmentService getAttachmentService() { return (AttachmentService) getService(ATTACHMENT_SERVICE); } // SequenceAccessorService public static final String SEQUENCE_ACCESSOR_SERVICE = "sequenceAccessorService"; public static SequenceAccessorService getSequenceAccessorService() { return (SequenceAccessorService) getService(SEQUENCE_ACCESSOR_SERVICE); } // KeyValuesService public static final String KEY_VALUES_SERVICE = "keyValuesService"; public static KeyValuesService getKeyValuesService() { return (KeyValuesService) getService(KEY_VALUES_SERVICE); } public static final String OJB_COLLECTION_HELPER = "ojbCollectionHelper"; public static OjbCollectionHelper getOjbCollectionHelper() { return (OjbCollectionHelper) getService(OJB_COLLECTION_HELPER); } public static final String PERSISTENCE_CACHE_ADMINISTRATOR = "persistenceCacheAdministrator"; public static final GeneralCacheAdministrator getPersistenceCacheAdministrator() { return (GeneralCacheAdministrator) getService(PERSISTENCE_CACHE_ADMINISTRATOR); } public static final String TRANSACTION_MANAGER = "transactionManager"; public static PlatformTransactionManager getTransactionManager() { return (PlatformTransactionManager) getService(TRANSACTION_MANAGER); } public static final String TRANSACTION_TEMPLATE = "transactionTemplate"; public static TransactionTemplate getTransactionTemplate() { return (TransactionTemplate) getService(TRANSACTION_TEMPLATE); } public static final String PESSIMISTIC_LOCK_SERVICE = "pessimisticLockService"; public static PessimisticLockService getPessimisticLockService() { return (PessimisticLockService) getService(PESSIMISTIC_LOCK_SERVICE); } public static final String DOCUMENT_SERIALIZER_SERVICE = "documentSerializerService"; public static DocumentSerializerService getDocumentSerializerService() { return (DocumentSerializerService) getService(DOCUMENT_SERIALIZER_SERVICE); } public static final String ENTITY_MANAGER_FACTORY = "entityManagerFactory"; public static EntityManagerFactory getEntityManagerFactory() { return (EntityManagerFactory) getService(ENTITY_MANAGER_FACTORY); } public static final String PERSISTENCE_SERVICE_OJB = "persistenceServiceOjb"; public static PersistenceService getPersistenceServiceOjb() { return (PersistenceService) getService(PERSISTENCE_SERVICE_OJB); } public static final String SESSION_DOCUMENT_SERVICE = "sessionDocumentService"; public static SessionDocumentService getSessionDocumentService() { return (SessionDocumentService) getService(SESSION_DOCUMENT_SERVICE); } public static final String DEFAULT_INACTIVATION_BLOCKING_DETECTION_SERVICE = "inactivationBlockingDetectionService"; public static InactivationBlockingDetectionService getInactivationBlockingDetectionService(String serviceName) { return (InactivationBlockingDetectionService) getService(serviceName); } public static final String INACTIVATION_BLOCKING_DISPLAY_SERVICE = "inactivationBlockingDisplayService"; public static InactivationBlockingDisplayService getInactivationBlockingDisplayService() { return (InactivationBlockingDisplayService) getService(INACTIVATION_BLOCKING_DISPLAY_SERVICE); } public static final String SERIALIZER_SERVICE = "businessObjectSerializerService"; public static BusinessObjectSerializerService getBusinessObjectSerializerService() { return (BusinessObjectSerializerService) getService(SERIALIZER_SERVICE); } public static final String COUNTRY_SERVICE = "countryService"; public static CountryService getCountryService() { return (CountryService) getService(COUNTRY_SERVICE); } public static final String STATE_SERVICE = "stateService"; public static StateService getStateService() { return (StateService) getService(STATE_SERVICE); } public static final String DOCUMENT_DAO = "documentDao"; public static DocumentDao getDocumentDao() { return (DocumentDao) getService(DOCUMENT_DAO); } public static final String BUSINESS_OBJECT_DAO = "businessObjectDao"; public static BusinessObjectDao getBusinessObjectDao() { return (BusinessObjectDao) getService(BUSINESS_OBJECT_DAO); } public static final String DB_PLATFORM = "dbPlatform"; public static KualiDBPlatform getKualiDbPlatform() { return (KualiDBPlatform) getService(DB_PLATFORM); } public static final String MAINTENANCE_DOCUMENT_AUTHORIZATION_SERVICE = "maintenanceDocumentAuthorizationService"; public static BusinessObjectAuthorizationService getMaintenanceDocumentAuthorizationService() { return (BusinessObjectAuthorizationService) getService(MAINTENANCE_DOCUMENT_AUTHORIZATION_SERVICE); } public static final String DOCUMENT_HELPER_SERVICE = "documentHelperService"; public static DocumentHelperService getDocumentHelperService() { return (DocumentHelperService) getService(DOCUMENT_HELPER_SERVICE); } }
impl/src/main/java/org/kuali/rice/kns/service/KNSServiceLocator.java
/* * Copyright 2007 The Kuali Foundation. * * Licensed under the Educational Community License, Version 1.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/ecl1.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.kns.service; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.persistence.EntityManagerFactory; import org.kuali.rice.core.resourceloader.GlobalResourceLoader; import org.kuali.rice.core.resourceloader.RiceResourceLoaderFactory; import org.kuali.rice.core.resourceloader.SpringResourceLoader; import org.kuali.rice.core.service.EncryptionService; import org.kuali.rice.kns.dao.BusinessObjectDao; import org.kuali.rice.kns.dao.DocumentDao; import org.kuali.rice.kns.dbplatform.KualiDBPlatform; import org.kuali.rice.kns.inquiry.Inquirable; import org.kuali.rice.kns.lookup.LookupResultsService; import org.kuali.rice.kns.lookup.Lookupable; import org.kuali.rice.kns.question.Question; import org.kuali.rice.kns.util.OjbCollectionHelper; import org.kuali.rice.kns.util.cache.MethodCacheInterceptor; import org.kuali.rice.kns.util.spring.NamedOrderedListBean; import org.kuali.rice.kns.workflow.service.KualiWorkflowInfo; import org.kuali.rice.kns.workflow.service.WorkflowDocumentService; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.support.TransactionTemplate; import com.opensymphony.oscache.general.GeneralCacheAdministrator; public class KNSServiceLocator<T extends Object> { public static final String VALIDATION_COMPLETION_UTILS = "validationCompletionUtils"; public static Object getService(String serviceName) { return GlobalResourceLoader.getService(serviceName); } public static <T> T getNervousSystemContextBean(Class<T> type) { Collection<T> beansOfType = getBeansOfType(type).values(); if (beansOfType.isEmpty()) { throw new NoSuchBeanDefinitionException("No beans of this type in the KNS application context: " + type.getName()); } if (beansOfType.size() > 1) { return getNervousSystemContextBean(type, type.getSimpleName().substring(0, 1).toLowerCase() + type.getSimpleName().substring(1)); } return beansOfType.iterator().next(); } @SuppressWarnings("unchecked") public static <T> T getNervousSystemContextBean(Class<T> type, String name) { return (T) RiceResourceLoaderFactory.getSpringResourceLoader().getContext().getBean(name); } @SuppressWarnings("unchecked") public static <T> Map<String, T> getBeansOfType(Class<T> type) { SpringResourceLoader springResourceLoader = RiceResourceLoaderFactory.getSpringResourceLoader(); if ( springResourceLoader != null ) { return new HashMap((Map) springResourceLoader.getContext().getBeansOfType(type)); } else { return new HashMap(0); } } public static String[] getBeanNames() { return RiceResourceLoaderFactory.getSpringResourceLoader().getContext().getBeanDefinitionNames(); } public static Set<String> getSingletonNames() { Set<String> singletonNames = new HashSet<String>(); Collections.addAll(singletonNames, RiceResourceLoaderFactory.getSpringResourceLoader().getContext().getBeanFactory() .getSingletonNames()); return singletonNames; } public static Set<Class> getSingletonTypes() { Set<Class> singletonTypes = new HashSet<Class>(); for (String singletonName : getSingletonNames()) { singletonTypes.add(RiceResourceLoaderFactory.getSpringResourceLoader().getContext().getBeanFactory().getType( singletonName)); } return singletonTypes; } public static boolean isSingleton( String beanName ) { try { return RiceResourceLoaderFactory.getSpringResourceLoader().getContext().getBeanFactory().isSingleton(beanName); } catch ( NoSuchBeanDefinitionException ex ) { // service is not in Spring so we can't assume return false; } } public static List<NamedOrderedListBean> getNamedOrderedListBeans(String listName) { List<NamedOrderedListBean> namedOrderedListBeans = new ArrayList<NamedOrderedListBean>(); for (Object namedOrderedListBean : RiceResourceLoaderFactory.getSpringResourceLoader().getContext().getBeansOfType( NamedOrderedListBean.class).values()) { if (((NamedOrderedListBean) namedOrderedListBean).getName().equals(listName)) { namedOrderedListBeans.add((NamedOrderedListBean) namedOrderedListBean); } } return namedOrderedListBeans; } public static final String ENCRYPTION_SERVICE = "encryptionService"; public static final EncryptionService getEncryptionService() { return (EncryptionService) getService(ENCRYPTION_SERVICE); } public static final String EXCEPTION_INCIDENT_REPORT_SERVICE = "knsExceptionIncidentService"; public static final KualiExceptionIncidentService getKualiExceptionIncidentService() { return (KualiExceptionIncidentService) getService(EXCEPTION_INCIDENT_REPORT_SERVICE); } public static final String MAIL_SERVICE = "mailService"; public static final MailService getMailService() { return (MailService) getService(MAIL_SERVICE); } public static final String METHOD_CACHE_INTERCEPTOR = "methodCacheInterceptor"; public static MethodCacheInterceptor getMethodCacheInterceptor() { return (MethodCacheInterceptor) getService(METHOD_CACHE_INTERCEPTOR); } public static final String BUSINESS_OBJECT_AUTHORIZATION_SERVICE = "businessObjectAuthorizationService"; public static BusinessObjectAuthorizationService getBusinessObjectAuthorizationService() { return (BusinessObjectAuthorizationService) getService(BUSINESS_OBJECT_AUTHORIZATION_SERVICE); } public static final String XML_OBJECT_SERIALIZER_SERVICE = "xmlObjectSerializerService"; public static XmlObjectSerializerService getXmlObjectSerializerService() { return (XmlObjectSerializerService) getService(XML_OBJECT_SERIALIZER_SERVICE); } public static final String DOCUMENT_SERVICE = "documentService"; public static DocumentService getDocumentService() { return (DocumentService) getService(DOCUMENT_SERVICE); } public static final String DOCUMENT_HEADER_SERVICE = "documentHeaderService"; public static DocumentHeaderService getDocumentHeaderService() { return (DocumentHeaderService) getService(DOCUMENT_HEADER_SERVICE); } public static final String POST_PROCESSOR_SERVICE = "postProcessorService"; public static PostProcessorService getPostProcessorService() { return (PostProcessorService) getService(POST_PROCESSOR_SERVICE); } public static final String DATETIME_SERVICE = "dateTimeService"; public static DateTimeService getDateTimeService() { return (DateTimeService) getService(DATETIME_SERVICE); } public static final String LOOKUP_SERVICE = "lookupService"; public static LookupService getLookupService() { return (LookupService) getService(LOOKUP_SERVICE); } public static final String LOOKUP_RESULTS_SERVICE = "lookupResultsService"; public static LookupResultsService getLookupResultsService() { return (LookupResultsService) getService(LOOKUP_RESULTS_SERVICE); } public static final String KUALI_MODULE_SERVICE = "kualiModuleService"; public static KualiModuleService getKualiModuleService() { return (KualiModuleService) getService(KUALI_MODULE_SERVICE); } public static final String WORKFLOW_DOCUMENT_SERVICE = "workflowDocumentService"; public static WorkflowDocumentService getWorkflowDocumentService() { return (WorkflowDocumentService) getService(WORKFLOW_DOCUMENT_SERVICE); } public static final String WORKFLOW_INFO_SERVICE = "workflowInfoService"; public static KualiWorkflowInfo getWorkflowInfoService() { return (KualiWorkflowInfo) getService(WORKFLOW_INFO_SERVICE); } public static final String KUALI_CONFIGURATION_SERVICE = "kualiConfigurationService"; public static KualiConfigurationService getKualiConfigurationService() { return (KualiConfigurationService) getService(KUALI_CONFIGURATION_SERVICE); } public static final String BUSINESS_OBJECT_DICTIONARY_SERVICE = "businessObjectDictionaryService"; public static BusinessObjectDictionaryService getBusinessObjectDictionaryService() { return (BusinessObjectDictionaryService) getService(BUSINESS_OBJECT_DICTIONARY_SERVICE); } public static final String BUSINESS_OBJECT_METADATA_SERVICE = "businessObjectMetaDataService"; public static BusinessObjectMetaDataService getBusinessObjectMetaDataService() { return (BusinessObjectMetaDataService) getService(BUSINESS_OBJECT_METADATA_SERVICE); } public static final String TRANSACTIONAL_DOCUMENT_DICTIONARY_SERVICE = "transactionalDocumentDictionaryService"; public static TransactionalDocumentDictionaryService getTransactionalDocumentDictionaryService() { return (TransactionalDocumentDictionaryService) getService(TRANSACTIONAL_DOCUMENT_DICTIONARY_SERVICE); } public static final String MAINTENANCE_DOCUMENT_DICTIONARY_SERVICE = "maintenanceDocumentDictionaryService"; public static MaintenanceDocumentDictionaryService getMaintenanceDocumentDictionaryService() { return (MaintenanceDocumentDictionaryService) getService(MAINTENANCE_DOCUMENT_DICTIONARY_SERVICE); } public static final String DATA_DICTIONARY_SERVICE = "dataDictionaryService"; public static DataDictionaryService getDataDictionaryService() { return (DataDictionaryService) getService(DATA_DICTIONARY_SERVICE); } public static final String MAINTENANCE_DOCUMENT_SERVICE = "maintenanceDocumentService"; public static MaintenanceDocumentService getMaintenanceDocumentService() { return (MaintenanceDocumentService) getService(MAINTENANCE_DOCUMENT_SERVICE); } public static final String NOTE_SERVICE = "noteService"; public static NoteService getNoteService() { return (NoteService) getService(NOTE_SERVICE); } public static final String PERSISTENCE_SERVICE = "persistenceService"; public static PersistenceService getPersistenceService() { return (PersistenceService) getService(PERSISTENCE_SERVICE); } public static final String PERSISTENCE_STRUCTURE_SERVICE = "persistenceStructureService"; public static PersistenceStructureService getPersistenceStructureService() { return (PersistenceStructureService) getService(PERSISTENCE_STRUCTURE_SERVICE); } public static final String KUALI_RULE_SERVICE = "kualiRuleService"; public static KualiRuleService getKualiRuleService() { return (KualiRuleService) getService(KUALI_RULE_SERVICE); } public static final String BUSINESS_OBJECT_SERVICE = "businessObjectService"; public static BusinessObjectService getBusinessObjectService() { return (BusinessObjectService) getService(BUSINESS_OBJECT_SERVICE); } // special ones for Inquirable and Lookupable public static final String KUALI_INQUIRABLE = "kualiInquirable"; public static Inquirable getKualiInquirable() { return (Inquirable) getService(KUALI_INQUIRABLE); } public static final String KUALI_LOOKUPABLE = "kualiLookupable"; public static Lookupable getKualiLookupable() { return (Lookupable) getService(KUALI_LOOKUPABLE); } public static final String GL_LOOKUPABLE = "glLookupable"; public static Lookupable getGLLookupable() { return (Lookupable) getService(GL_LOOKUPABLE); } public static Lookupable getLookupable(String lookupableName) { return (Lookupable) getService(lookupableName); } // special one for QuestionPrompt public static Question getQuestion(String questionName) { return (Question) getService(questionName); } // DictionaryValidationService public static final String DICTIONARY_VALIDATION_SERVICE = "dictionaryValidationService"; public static DictionaryValidationService getDictionaryValidationService() { return (DictionaryValidationService) getService(DICTIONARY_VALIDATION_SERVICE); } // AttachmentService public static final String ATTACHMENT_SERVICE = "attachmentService"; public static AttachmentService getAttachmentService() { return (AttachmentService) getService(ATTACHMENT_SERVICE); } // SequenceAccessorService public static final String SEQUENCE_ACCESSOR_SERVICE = "sequenceAccessorService"; public static SequenceAccessorService getSequenceAccessorService() { return (SequenceAccessorService) getService(SEQUENCE_ACCESSOR_SERVICE); } // KeyValuesService public static final String KEY_VALUES_SERVICE = "keyValuesService"; public static KeyValuesService getKeyValuesService() { return (KeyValuesService) getService(KEY_VALUES_SERVICE); } public static final String OJB_COLLECTION_HELPER = "ojbCollectionHelper"; public static OjbCollectionHelper getOjbCollectionHelper() { return (OjbCollectionHelper) getService(OJB_COLLECTION_HELPER); } public static final String PERSISTENCE_CACHE_ADMINISTRATOR = "persistenceCacheAdministrator"; public static final GeneralCacheAdministrator getPersistenceCacheAdministrator() { return (GeneralCacheAdministrator) getService(PERSISTENCE_CACHE_ADMINISTRATOR); } public static final String TRANSACTION_MANAGER = "transactionManager"; public static PlatformTransactionManager getTransactionManager() { return (PlatformTransactionManager) getService(TRANSACTION_MANAGER); } public static final String TRANSACTION_TEMPLATE = "transactionTemplate"; public static TransactionTemplate getTransactionTemplate() { return (TransactionTemplate) getService(TRANSACTION_TEMPLATE); } public static final String PESSIMISTIC_LOCK_SERVICE = "pessimisticLockService"; public static PessimisticLockService getPessimisticLockService() { return (PessimisticLockService) getService(PESSIMISTIC_LOCK_SERVICE); } public static final String DOCUMENT_SERIALIZER_SERVICE = "documentSerializerService"; public static DocumentSerializerService getDocumentSerializerService() { return (DocumentSerializerService) getService(DOCUMENT_SERIALIZER_SERVICE); } public static final String ENTITY_MANAGER_FACTORY = "entityManagerFactory"; public static EntityManagerFactory getEntityManagerFactory() { return (EntityManagerFactory) getService(ENTITY_MANAGER_FACTORY); } public static final String PERSISTENCE_SERVICE_OJB = "persistenceServiceOjb"; public static PersistenceService getPersistenceServiceOjb() { return (PersistenceService) getService(PERSISTENCE_SERVICE_OJB); } public static final String SESSION_DOCUMENT_SERVICE = "sessionDocumentService"; public static SessionDocumentService getSessionDocumentService() { return (SessionDocumentService) getService(SESSION_DOCUMENT_SERVICE); } public static final String DEFAULT_INACTIVATION_BLOCKING_DETECTION_SERVICE = "inactivationBlockingDetectionService"; public static InactivationBlockingDetectionService getInactivationBlockingDetectionService(String serviceName) { return (InactivationBlockingDetectionService) getService(serviceName); } public static final String INACTIVATION_BLOCKING_DISPLAY_SERVICE = "inactivationBlockingDisplayService"; public static InactivationBlockingDisplayService getInactivationBlockingDisplayService() { return (InactivationBlockingDisplayService) getService(INACTIVATION_BLOCKING_DISPLAY_SERVICE); } public static final String SERIALIZER_SERVICE = "businessObjectSerializerService"; public static BusinessObjectSerializerService getBusinessObjectSerializerService() { return (BusinessObjectSerializerService) getService(SERIALIZER_SERVICE); } public static final String COUNTRY_SERVICE = "countryService"; public static CountryService getCountryService() { return (CountryService) getService(COUNTRY_SERVICE); } public static final String STATE_SERVICE = "stateService"; public static StateService getStateService() { return (StateService) getService(STATE_SERVICE); } public static final String DOCUMENT_DAO = "documentDao"; public static DocumentDao getDocumentDao() { return (DocumentDao) getService(DOCUMENT_DAO); } public static final String BUSINESS_OBJECT_DAO = "businessObjectDao"; public static BusinessObjectDao getBusinessObjectDao() { return (BusinessObjectDao) getService(BUSINESS_OBJECT_DAO); } public static final String DB_PLATFORM = "dbPlatform"; public static KualiDBPlatform getKualiDbPlatform() { return (KualiDBPlatform) getService(DB_PLATFORM); } public static final String MAINTENANCE_DOCUMENT_AUTHORIZATION_SERVICE = "maintenanceDocumentAuthorizationService"; public static BusinessObjectAuthorizationService getMaintenanceDocumentAuthorizationService() { return (BusinessObjectAuthorizationService) getService(MAINTENANCE_DOCUMENT_AUTHORIZATION_SERVICE); } public static final String DOCUMENT_HELPER_SERVICE = "documentHelperService"; public static DocumentHelperService getDocumentHelperService() { return (DocumentHelperService) getService(DOCUMENT_HELPER_SERVICE); } }
Removed KFS GLLookupable reference from the KNSServiceLocator.
impl/src/main/java/org/kuali/rice/kns/service/KNSServiceLocator.java
Removed KFS GLLookupable reference from the KNSServiceLocator.
Java
apache-2.0
19de811cafeb55fb519965cd89427416798e3040
0
jankill/commons-collections,mohanaraosv/commons-collections,MuShiiii/commons-collections,sandrineBeauche/commons-collections,apache/commons-collections,sandrineBeauche/commons-collections,jankill/commons-collections,MuShiiii/commons-collections,sandrineBeauche/commons-collections,apache/commons-collections,MuShiiii/commons-collections,gonmarques/commons-collections,mohanaraosv/commons-collections,apache/commons-collections,mohanaraosv/commons-collections,gonmarques/commons-collections,jankill/commons-collections
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.set; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Set; import org.apache.commons.collections.OrderedIterator; import org.apache.commons.collections.iterators.AbstractIteratorDecorator; import org.apache.commons.collections.list.UnmodifiableList; /** * Decorates another <code>Set</code> to ensure that the order of addition * is retained and used by the iterator. * <p> * If an object is added to the set for a second time, it will remain in the * original position in the iteration. * The order can be observed from the set via the iterator or toArray methods. * <p> * The ListOrderedSet also has various useful direct methods. These include many * from <code>List</code>, such as <code>get(int)</code>, <code>remove(int)</code> * and <code>indexOf(int)</code>. An unmodifiable <code>List</code> view of * the set can be obtained via <code>asList()</code>. * <p> * This class cannot implement the <code>List</code> interface directly as * various interface methods (notably equals/hashCode) are incompatible with a set. * <p> * This class is Serializable from Commons Collections 3.1. * * @since Commons Collections 3.0 * @version $Revision$ * * @author Stephen Colebourne * @author Henning P. Schmiedehausen */ public class ListOrderedSet<E> extends AbstractSerializableSetDecorator<E> implements Set<E> { /** Serialization version */ private static final long serialVersionUID = -228664372470420141L; /** Internal list to hold the sequence of objects */ protected final List<E> setOrder; /** * Factory method to create an ordered set specifying the list and set to use. * <p> * The list and set must both be empty. * * @param set the set to decorate, must be empty and not null * @param list the list to decorate, must be empty and not null * @throws IllegalArgumentException if set or list is null * @throws IllegalArgumentException if either the set or list is not empty * @since Commons Collections 3.1 */ public static <E> ListOrderedSet<E> listOrderedSet(Set<E> set, List<E> list) { if (set == null) { throw new IllegalArgumentException("Set must not be null"); } if (list == null) { throw new IllegalArgumentException("List must not be null"); } if (set.size() > 0 || list.size() > 0) { throw new IllegalArgumentException("Set and List must be empty"); } return new ListOrderedSet<E>(set, list); } /** * Factory method to create an ordered set. * <p> * An <code>ArrayList</code> is used to retain order. * * @param set the set to decorate, must not be null * @throws IllegalArgumentException if set is null */ public static <E> ListOrderedSet<E> listOrderedSet(Set<E> set) { return new ListOrderedSet<E>(set); } /** * Factory method to create an ordered set using the supplied list to retain order. * <p> * A <code>HashSet</code> is used for the set behaviour. * <p> * NOTE: If the list contains duplicates, the duplicates are removed, * altering the specified list. * * @param list the list to decorate, must not be null * @throws IllegalArgumentException if list is null */ public static <E> ListOrderedSet<E> listOrderedSet(List<E> list) { if (list == null) { throw new IllegalArgumentException("List must not be null"); } Set<E> set = new HashSet<E>(list); list.retainAll(set); return new ListOrderedSet<E>(set, list); } //----------------------------------------------------------------------- /** * Constructs a new empty <code>ListOrderedSet</code> using * a <code>HashSet</code> and an <code>ArrayList</code> internally. * * @since Commons Collections 3.1 */ public ListOrderedSet() { super(new HashSet<E>()); setOrder = new ArrayList<E>(); } /** * Constructor that wraps (not copies). * * @param set the set to decorate, must not be null * @throws IllegalArgumentException if set is null */ protected ListOrderedSet(Set<E> set) { super(set); setOrder = new ArrayList<E>(set); } /** * Constructor that wraps (not copies) the Set and specifies the list to use. * <p> * The set and list must both be correctly initialised to the same elements. * * @param set the set to decorate, must not be null * @param list the list to decorate, must not be null * @throws IllegalArgumentException if set or list is null */ protected ListOrderedSet(Set<E> set, List<E> list) { super(set); if (list == null) { throw new IllegalArgumentException("List must not be null"); } setOrder = list; } //----------------------------------------------------------------------- /** * Gets an unmodifiable view of the order of the Set. * * @return an unmodifiable list view */ public List<E> asList() { return UnmodifiableList.unmodifiableList(setOrder); } //----------------------------------------------------------------------- @Override public void clear() { collection.clear(); setOrder.clear(); } @Override public OrderedIterator<E> iterator() { return new OrderedSetIterator<E>(setOrder.listIterator(), collection); } @Override public boolean add(E object) { if (collection.add(object)) { setOrder.add(object); return true; } return false; } @Override public boolean addAll(Collection<? extends E> coll) { boolean result = false; for (E e : coll) { result |= add(e); } return result; } @Override public boolean remove(Object object) { boolean result = collection.remove(object); if (result) { setOrder.remove(object); } return result; } @Override public boolean removeAll(Collection<?> coll) { boolean result = false; for (Iterator<?> it = coll.iterator(); it.hasNext();) { result |= remove(it.next()); } return result; } @Override public boolean retainAll(Collection<?> coll) { boolean result = collection.retainAll(coll); if (result == false) { return false; } if (collection.size() == 0) { setOrder.clear(); } else { for (Iterator<E> it = setOrder.iterator(); it.hasNext();) { if (!collection.contains(it.next())) { it.remove(); } } } return result; } @Override public Object[] toArray() { return setOrder.toArray(); } @Override public <T> T[] toArray(T a[]) { return setOrder.toArray(a); } //----------------------------------------------------------------------- public E get(int index) { return setOrder.get(index); } public int indexOf(Object object) { return setOrder.indexOf(object); } public void add(int index, E object) { if (!contains(object)) { collection.add(object); setOrder.add(index, object); } } public boolean addAll(int index, Collection<? extends E> coll) { boolean changed = false; for (E e : coll) { if (contains(e)) { continue; } collection.add(e); setOrder.add(index++, e); changed = true; } return changed; } public Object remove(int index) { Object obj = setOrder.remove(index); remove(obj); return obj; } /** * Uses the underlying List's toString so that order is achieved. * This means that the decorated Set's toString is not used, so * any custom toStrings will be ignored. */ // Fortunately List.toString and Set.toString look the same @Override public String toString() { return setOrder.toString(); } //----------------------------------------------------------------------- /** * Internal iterator handle remove. */ static class OrderedSetIterator<E> extends AbstractIteratorDecorator<E> implements OrderedIterator<E> { /** Object we iterate on */ protected final Collection<E> set; /** Last object retrieved */ protected E last; private OrderedSetIterator(ListIterator<E> iterator, Collection<E> set) { super(iterator); this.set = set; } @Override public E next() { last = iterator.next(); return last; } @Override public void remove() { set.remove(last); iterator.remove(); last = null; } public boolean hasPrevious() { return ((ListIterator<E>) iterator).hasPrevious(); } public E previous() { last = ((ListIterator<E>) iterator).previous(); return last; } } }
src/main/java/org/apache/commons/collections/set/ListOrderedSet.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.set; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Set; import org.apache.commons.collections.OrderedIterator; import org.apache.commons.collections.iterators.AbstractIteratorDecorator; import org.apache.commons.collections.list.UnmodifiableList; /** * Decorates another <code>Set</code> to ensure that the order of addition * is retained and used by the iterator. * <p> * If an object is added to the set for a second time, it will remain in the * original position in the iteration. * The order can be observed from the set via the iterator or toArray methods. * <p> * The ListOrderedSet also has various useful direct methods. These include many * from <code>List</code>, such as <code>get(int)</code>, <code>remove(int)</code> * and <code>indexOf(int)</code>. An unmodifiable <code>List</code> view of * the set can be obtained via <code>asList()</code>. * <p> * This class cannot implement the <code>List</code> interface directly as * various interface methods (notably equals/hashCode) are incompatable with a set. * <p> * This class is Serializable from Commons Collections 3.1. * * @since Commons Collections 3.0 * @version $Revision$ * * @author Stephen Colebourne * @author Henning P. Schmiedehausen */ public class ListOrderedSet<E> extends AbstractSerializableSetDecorator<E> implements Set<E> { /** Serialization version */ private static final long serialVersionUID = -228664372470420141L; /** Internal list to hold the sequence of objects */ protected final List<E> setOrder; /** * Factory method to create an ordered set specifying the list and set to use. * <p> * The list and set must both be empty. * * @param set the set to decorate, must be empty and not null * @param list the list to decorate, must be empty and not null * @throws IllegalArgumentException if set or list is null * @throws IllegalArgumentException if either the set or list is not empty * @since Commons Collections 3.1 */ public static <E> ListOrderedSet<E> listOrderedSet(Set<E> set, List<E> list) { if (set == null) { throw new IllegalArgumentException("Set must not be null"); } if (list == null) { throw new IllegalArgumentException("List must not be null"); } if (set.size() > 0 || list.size() > 0) { throw new IllegalArgumentException("Set and List must be empty"); } return new ListOrderedSet<E>(set, list); } /** * Factory method to create an ordered set. * <p> * An <code>ArrayList</code> is used to retain order. * * @param set the set to decorate, must not be null * @throws IllegalArgumentException if set is null */ public static <E> ListOrderedSet<E> listOrderedSet(Set<E> set) { return new ListOrderedSet<E>(set); } /** * Factory method to create an ordered set using the supplied list to retain order. * <p> * A <code>HashSet</code> is used for the set behaviour. * <p> * NOTE: If the list contains duplicates, the duplicates are removed, * altering the specified list. * * @param list the list to decorate, must not be null * @throws IllegalArgumentException if list is null */ public static <E> ListOrderedSet<E> listOrderedSet(List<E> list) { if (list == null) { throw new IllegalArgumentException("List must not be null"); } Set<E> set = new HashSet<E>(list); list.retainAll(set); return new ListOrderedSet<E>(set, list); } //----------------------------------------------------------------------- /** * Constructs a new empty <code>ListOrderedSet</code> using * a <code>HashSet</code> and an <code>ArrayList</code> internally. * * @since Commons Collections 3.1 */ public ListOrderedSet() { super(new HashSet<E>()); setOrder = new ArrayList<E>(); } /** * Constructor that wraps (not copies). * * @param set the set to decorate, must not be null * @throws IllegalArgumentException if set is null */ protected ListOrderedSet(Set<E> set) { super(set); setOrder = new ArrayList<E>(set); } /** * Constructor that wraps (not copies) the Set and specifies the list to use. * <p> * The set and list must both be correctly initialised to the same elements. * * @param set the set to decorate, must not be null * @param list the list to decorate, must not be null * @throws IllegalArgumentException if set or list is null */ protected ListOrderedSet(Set<E> set, List<E> list) { super(set); if (list == null) { throw new IllegalArgumentException("List must not be null"); } setOrder = list; } //----------------------------------------------------------------------- /** * Gets an unmodifiable view of the order of the Set. * * @return an unmodifiable list view */ public List<E> asList() { return UnmodifiableList.unmodifiableList(setOrder); } //----------------------------------------------------------------------- @Override public void clear() { collection.clear(); setOrder.clear(); } @Override public OrderedIterator<E> iterator() { return new OrderedSetIterator<E>(setOrder.listIterator(), collection); } @Override public boolean add(E object) { if (collection.add(object)) { setOrder.add(object); return true; } return false; } @Override public boolean addAll(Collection<? extends E> coll) { boolean result = false; for (E e : coll) { result |= add(e); } return result; } @Override public boolean remove(Object object) { boolean result = collection.remove(object); setOrder.remove(object); return result; } @Override public boolean removeAll(Collection<?> coll) { boolean result = false; for (Iterator<?> it = coll.iterator(); it.hasNext();) { result |= remove(it.next()); } return result; } @Override public boolean retainAll(Collection<?> coll) { boolean result = collection.retainAll(coll); if (result == false) { return false; } if (collection.size() == 0) { setOrder.clear(); } else { for (Iterator<E> it = setOrder.iterator(); it.hasNext();) { if (!collection.contains(it.next())) { it.remove(); } } } return result; } @Override public Object[] toArray() { return setOrder.toArray(); } @Override public <T> T[] toArray(T a[]) { return setOrder.toArray(a); } //----------------------------------------------------------------------- public E get(int index) { return setOrder.get(index); } public int indexOf(Object object) { return setOrder.indexOf(object); } public void add(int index, E object) { if (!contains(object)) { collection.add(object); setOrder.add(index, object); } } public boolean addAll(int index, Collection<? extends E> coll) { boolean changed = false; for (E e : coll) { if (contains(e)) { continue; } collection.add(e); setOrder.add(index++, e); changed = true; } return changed; } public Object remove(int index) { Object obj = setOrder.remove(index); remove(obj); return obj; } /** * Uses the underlying List's toString so that order is achieved. * This means that the decorated Set's toString is not used, so * any custom toStrings will be ignored. */ // Fortunately List.toString and Set.toString look the same @Override public String toString() { return setOrder.toString(); } //----------------------------------------------------------------------- /** * Internal iterator handle remove. */ static class OrderedSetIterator<E> extends AbstractIteratorDecorator<E> implements OrderedIterator<E> { /** Object we iterate on */ protected final Collection<E> set; /** Last object retrieved */ protected E last; private OrderedSetIterator(ListIterator<E> iterator, Collection<E> set) { super(iterator); this.set = set; } @Override public E next() { last = iterator.next(); return last; } @Override public void remove() { set.remove(last); iterator.remove(); last = null; } public boolean hasPrevious() { return ((ListIterator<E>) iterator).hasPrevious(); } public E previous() { last = ((ListIterator<E>) iterator).previous(); return last; } } }
[COLLECTIONS-407] improve performance of remove method by taking method result from underlying collection into account. Thanks to Adrian Nistor for reporting and providing a patch. git-svn-id: 53f0c1087cb9b05f99ff63ab1f4d1687a227fef1@1351800 13f79535-47bb-0310-9956-ffa450edef68
src/main/java/org/apache/commons/collections/set/ListOrderedSet.java
[COLLECTIONS-407] improve performance of remove method by taking method result from underlying collection into account. Thanks to Adrian Nistor for reporting and providing a patch.
Java
apache-2.0
0de1fcea03077f5ec6768373c15da7b8b531107b
0
PennState/directory-fortress-core-1,PennState/directory-fortress-core-1,PennState/directory-fortress-core-1
/* * 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.directory.fortress.core.rbac; import java.util.Set; import java.util.TreeSet; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import org.apache.directory.fortress.core.util.attr.VUtil; import org.apache.directory.fortress.core.util.time.CUtil; import org.apache.directory.fortress.core.util.time.Constraint; /** * All entities ({@link AdminRole}, {@link org.apache.directory.fortress.core.rbac.OrgUnit}, * {@link org.apache.directory.fortress.core.rbac.SDSet} etc...) are used to carry data between three Fortress * layers.starting with the (1) Manager layer down thru middle (2) Process layer and it's processing rules into * (3) DAO layer where persistence with the OpenLDAP server occurs. * <h4>Fortress Processing Layers</h4> * <ol> * <li>Manager layer: {@link DelAdminMgrImpl}, {@link DelAccessMgrImpl}, {@link DelReviewMgrImpl},...</li> * <li>Process layer: {@link AdminRoleP}, {@link org.apache.directory.fortress.core.rbac.OrgUnitP},...</li> * <li>DAO layer: {@link AdminRoleDAO}, {@link OrgUnitDAO},...</li> * </ol> * Fortress clients first instantiate and populate a data entity before invoking any of the Manager APIs. The caller must * provide enough information to uniquely identity the entity target within ldap.<br /> * For example, this entity requires {@link #name} set before passing into {@link DelAdminMgrImpl} or {@link DelReviewMgrImpl} APIs. * Create methods usually require more attributes (than Read) due to constraints enforced between entities. * <p/> * This entity extends the {@link org.apache.directory.fortress.core.rbac.Role} entity and is used to store the ARBAC AdminRole assignments that comprise the many-to-many relationships between Users and Administrative Permissions. * In addition it is used to store the ARBAC {@link org.apache.directory.fortress.core.rbac.OrgUnit.Type#PERM} and {@link org.apache.directory.fortress.core.rbac.OrgUnit.Type#USER} OU information that adheres to the AdminRole entity in the ARBAC02 model. * <br />The unique key to locate AdminRole entity (which is subsequently assigned both to Users and administrative Permissions) is {@link AdminRole#name}.<br /> * <p/> * There is a many-to-many relationship between User's, Administrative Roles and Administrative Permissions. * <h3>{@link org.apache.directory.fortress.core.rbac.User}*<->*{@link AdminRole}*<->*{@link Permission}</h3> * Example to create new ARBAC AdminRole: * <p/> * <code>AdminRole myRole = new AdminRole("MyRoleName");</code><br /> * <code>myRole.setDescription("This is a test admin role");</code><br /> * <code>DelAdminMgr delAdminMgr = DelAdminMgrFactory.createInstance();</code><br /> * <code>delAdminMgr.addRole(myRole);</code><br /> * <p/> * This will create a AdminRole name that can be used as a target for User-AdminRole assignments and AdminRole-AdminPermission grants. * <p/> * <p/> * <h4>Administrative Role Schema</h4> * The Fortress AdminRole entity is a composite of the following other Fortress structural and aux object classes: * <p/> * 1. organizationalRole Structural Object Class is used to store basic attributes like cn and description. * <pre> * ------------------------------------------ * objectclass ( 2.5.6.8 NAME 'organizationalRole' * DESC 'RFC2256: an organizational role' * SUP top STRUCTURAL * MUST cn * MAY ( * x121Address $ registeredAddress $ destinationIndicator $ * preferredDeliveryMethod $ telexNumber $ teletexTerminalIdentifier $ * telephoneNumber $ internationaliSDNNumber $ facsimileTelephoneNumber $ * seeAlso $ roleOccupant $ preferredDeliveryMethod $ street $ * postOfficeBox $ postalCode $ postalAddress $ * physicalDeliveryOfficeName $ ou $ st $ l $ description * ) * ) * ------------------------------------------ * </pre> * <p/> * 2. ftRls Structural objectclass is used to store the AdminRole information like name, and temporal constraints. * <pre> * ------------------------------------------ * Fortress Roles Structural Object Class * objectclass ( 1.3.6.1.4.1.38088.2.1 * NAME 'ftRls' * DESC 'Fortress Role Structural Object Class' * SUP organizationalrole * STRUCTURAL * MUST ( * ftId $ * ftRoleName * ) * MAY ( * description $ * ftCstr $ * ftParents * ) * ) * ------------------------------------------ * </pre> * <p/> * 3. ftProperties AUXILIARY Object Class is used to store client specific name/value pairs on target entity.<br /> * <code># This aux object class can be used to store custom attributes.</code><br /> * <code># The properties collections consist of name/value pairs and are not constrainted by Fortress.</code><br /> * <pre> * ------------------------------------------ * AC2: Fortress Properties Auxiliary Object Class * objectclass ( 1.3.6.1.4.1.38088.3.2 * NAME 'ftProperties' * DESC 'Fortress Properties AUX Object Class' * AUXILIARY * MAY ( * ftProps * ) * ) * ------------------------------------------ * </pre> * <p/> * 4. ftPools Auxiliary object class store the ARBAC Perm and User OU assignments on AdminRole entity. * <pre> * ------------------------------------------ * Fortress Organizational Pools Auxiliary Object Class * objectclass ( 1.3.6.1.4.1.38088.3.3 * NAME 'ftPools' * DESC 'Fortress Pools AUX Object Class' * AUXILIARY * MAY ( * ftOSU $ * ftOSP $ * ftRange * ) * ) * ------------------------------------------ * </pre> * <p/> * 5. ftMods AUXILIARY Object Class is used to store Fortress audit variables on target entity. * <pre> * ------------------------------------------ * Fortress Audit Modification Auxiliary Object Class * objectclass ( 1.3.6.1.4.1.38088.3.4 * NAME 'ftMods' * DESC 'Fortress Modifiers AUX Object Class' * AUXILIARY * MAY ( * ftModifier $ * ftModCode $ * ftModId * ) * ) * ------------------------------------------ * </pre> * <p/> * * @author Shawn McKinney */ @XmlRootElement(name = "fortAdminRole") @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "adminRole", propOrder = { "osPs", "osUs", "beginRange", "endRange", "beginInclusive", "endInclusive" }) public class AdminRole extends Role implements Administrator { private Set<String> osPs; private Set<String> osUs; private String beginRange; private String endRange; private boolean beginInclusive; private boolean endInclusive; /** * Default constructor is used by internal Fortress classes. */ public AdminRole() { } /** * Construct an Admin Role with a given temporal constraint. * * @param con maps to 'OamRC' attribute for 'ftTemporal' aux object classes. */ public AdminRole( Constraint con ) { CUtil.copy( con, this ); } /** * Construct an AdminRole entity with a given name. * */ public AdminRole( String name ) { this.setName( name ); } /** * Load the role range attributes given a raw format. This method is used internal to Fortress and is not intended * to be used by external callers. * * @param szRaw maps to 'ftRange' attribute on 'ftPools' aux object class. */ @Override public void setRoleRangeRaw( String szRaw ) { if ( VUtil.isNotNullOrEmpty( szRaw ) ) { int bindx = szRaw.indexOf( "(" ); if ( bindx > -1 ) { this.setBeginInclusive( false ); } else { bindx = szRaw.indexOf( "[" ); this.setBeginInclusive( true ); } int eindx = szRaw.indexOf( ")" ); if ( eindx > -1 ) { this.setEndInclusive( false ); } else { eindx = szRaw.indexOf( "]" ); this.setEndInclusive( true ); } int cindx = szRaw.indexOf( ":" ); if ( cindx > -1 ) { String szBeginRange = szRaw.substring( bindx + 1, cindx ); String szEndRange = szRaw.substring( cindx + 1, eindx ); this.setBeginRange( szBeginRange ); this.setEndRange( szEndRange ); } } } /** * * Get the raw format for role range using current AdminRole entity attributes. This method is used internal to Fortress and is not intended * to be used by external callers. * * @return String maps to 'ftRange' attribute on 'ftPools' aux object class. */ @Override public String getRoleRangeRaw() { String szRaw = ""; if ( this.beginRange != null ) { if ( this.isBeginInclusive() ) szRaw += "["; else szRaw += "("; szRaw += this.getBeginRange(); szRaw += ":"; szRaw += this.getEndRange(); if ( this.isEndInclusive() ) szRaw += "]"; else szRaw += ")"; } return szRaw; } /** * Get a collection of optional Perm OU attributes that were stored on the AdminRole entity. * * @return List of type String containing Perm OU. This maps to 'ftOSP' attribute on 'ftPools' aux object class. */ @Override public Set<String> getOsP() { return osPs; } /** * Set a collection of optional Perm OU attributes to be stored on the AdminRole entity. * * @param osPs is a List of type String containing Perm OU. This maps to 'ftOSP' attribute on 'ftPools' aux object class. */ @Override public void setOsP( Set<String> osPs ) { this.osPs = osPs; } /** * Set a Perm OU attribute to be stored on the AdminRole entity. * * @param osP is a Perm OU that maps to 'ftOSP' attribute on 'ftPools' aux object class. */ @Override public void setOsP( String osP ) { if ( this.osPs == null ) { // create Set with case insensitive comparator: osPs = new TreeSet<>( String.CASE_INSENSITIVE_ORDER ); } osPs.add( osP ); } /** * Get a collection of optional User OU attributes that were stored on the AdminRole entity. * * @return List of type String containing User OU. This maps to 'ftOSU' attribute on 'ftPools' aux object class. */ @Override public Set<String> getOsU() { return osUs; } /** * Set a collection of optional User OU attributes to be stored on the AdminRole entity. * * @param osUs is a List of type String containing User OU. This maps to 'ftOSU' attribute on 'ftPools' aux object class. */ @Override public void setOsU( Set<String> osUs ) { this.osUs = osUs; } /** * Set a User OU attribute to be stored on the AdminRole entity. * * @param osU is a User OU that maps to 'ftOSU' attribute on 'ftPools' aux object class. */ @Override public void setOsU( String osU ) { if ( this.osUs == null ) { // create Set with case insensitive comparator: osUs = new TreeSet<>( String.CASE_INSENSITIVE_ORDER ); } osUs.add( osU ); } /** * Return the begin Role range attribute for AdminRole entity which corresponds to lowest descendant. * * @return String that maps to 'ftRange' attribute on 'ftPools' aux object class. */ @Override public String getBeginRange() { return beginRange; } /** * Set the begin Role range attribute for AdminRole entity which corresponds to lowest descendant. * * @param beginRange maps to 'ftRange' attribute on 'ftPools' aux object class. */ @Override public void setBeginRange( String beginRange ) { this.beginRange = beginRange; } /** * Return the end Role range attribute for AdminRole entity which corresponds to highest ascendant. * * @return String that maps to 'ftRange' attribute on 'ftPools' aux object class. */ @Override public String getEndRange() { return endRange; } /** * Set the end Role range attribute for AdminRole entity which corresponds to highest ascendant. * * @param endRange maps to 'ftRange' attribute on 'ftPools' aux object class. */ @Override public void setEndRange( String endRange ) { this.endRange = endRange; } /** * Get the begin inclusive which specifies if role range includes or excludes the 'beginRange' attribute. * * @return String that maps to 'ftRange' attribute on 'ftPools' aux object class. */ @Override public boolean isBeginInclusive() { return beginInclusive; } /** * Set the begin inclusive which specifies if role range includes or excludes the 'beginRange' attribute. * * @param beginInclusive maps to 'ftRange' attribute on 'ftPools' aux object class. */ @Override public void setBeginInclusive( boolean beginInclusive ) { this.beginInclusive = beginInclusive; } /** * Get the end inclusive which specifies if role range includes or excludes the 'endRange' attribute. * * @return String that maps to 'ftRange' attribute on 'ftPools' aux object class. */ @Override public boolean isEndInclusive() { return endInclusive; } /** * Set the end inclusive which specifies if role range includes or excludes the 'endRange' attribute. * * @param endInclusive maps to 'ftRange' attribute on 'ftPools' aux object class. */ @Override public void setEndInclusive( boolean endInclusive ) { this.endInclusive = endInclusive; } /** * Matches the name from two AdminRole entities. * * @param thatObj contains an AdminRole entity. * @return boolean indicating both objects contain matching AdminRole names. */ public boolean equals( Object thatObj ) { if ( this == thatObj ) { return true; } if ( this.getName() == null ) { return false; } if ( !( thatObj instanceof AdminRole ) ) { return false; } Role thatRole = ( Role ) thatObj; if ( thatRole.getName() == null ) { return false; } return thatRole.getName().equalsIgnoreCase( this.getName() ); } /** * @see Object#toString() */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append( "AdminRole object: \n" ); if ( beginRange != null ) { sb.append( " beginRange :" ).append( beginRange ).append( '\n' ); } if ( endRange != null ) { sb.append( " endRange :" ).append( endRange ).append( '\n' ); } sb.append( " beginInclusive :" ).append( beginInclusive ).append( '\n' ); sb.append( " endInclusive :" ).append( endInclusive ).append( '\n' ); if ( osPs != null ) { sb.append( " osPs : " ); boolean isFirst = true; for ( String osP : osPs ) { if ( isFirst ) { isFirst = false; } else { sb.append( ", " ); } sb.append( osP ); } sb.append( '\n' ); } if ( osUs != null ) { sb.append( " osUs : " ); boolean isFirst = true; for ( String osU : osUs ) { if ( isFirst ) { isFirst = false; } else { sb.append( ", " ); } sb.append( osU ); } sb.append( '\n' ); } return sb.toString(); } }
src/main/java/org/apache/directory/fortress/core/rbac/AdminRole.java
/* * 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.directory.fortress.core.rbac; import java.util.Set; import java.util.TreeSet; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import org.apache.directory.fortress.core.util.attr.VUtil; import org.apache.directory.fortress.core.util.time.CUtil; import org.apache.directory.fortress.core.util.time.Constraint; /** * All entities ({@link AdminRole}, {@link org.apache.directory.fortress.core.rbac.OrgUnit}, * {@link org.apache.directory.fortress.core.rbac.SDSet} etc...) are used to carry data between three Fortress * layers.starting with the (1) Manager layer down thru middle (2) Process layer and it's processing rules into * (3) DAO layer where persistence with the OpenLDAP server occurs. * <h4>Fortress Processing Layers</h4> * <ol> * <li>Manager layer: {@link DelAdminMgrImpl}, {@link DelAccessMgrImpl}, {@link DelReviewMgrImpl},...</li> * <li>Process layer: {@link AdminRoleP}, {@link org.apache.directory.fortress.core.rbac.OrgUnitP},...</li> * <li>DAO layer: {@link AdminRoleDAO}, {@link OrgUnitDAO},...</li> * </ol> * Fortress clients first instantiate and populate a data entity before invoking any of the Manager APIs. The caller must * provide enough information to uniquely identity the entity target within ldap.<br /> * For example, this entity requires {@link #name} set before passing into {@link DelAdminMgrImpl} or {@link DelReviewMgrImpl} APIs. * Create methods usually require more attributes (than Read) due to constraints enforced between entities. * <p/> * This entity extends the {@link org.apache.directory.fortress.core.rbac.Role} entity and is used to store the ARBAC AdminRole assignments that comprise the many-to-many relationships between Users and Administrative Permissions. * In addition it is used to store the ARBAC {@link org.apache.directory.fortress.core.rbac.OrgUnit.Type#PERM} and {@link org.apache.directory.fortress.core.rbac.OrgUnit.Type#USER} OU information that adheres to the AdminRole entity in the ARBAC02 model. * <br />The unique key to locate AdminRole entity (which is subsequently assigned both to Users and administrative Permissions) is {@link AdminRole#name}.<br /> * <p/> * There is a many-to-many relationship between User's, Administrative Roles and Administrative Permissions. * <h3>{@link org.apache.directory.fortress.core.rbac.User}*<->*{@link AdminRole}*<->*{@link Permission}</h3> * Example to create new ARBAC AdminRole: * <p/> * <code>AdminRole myRole = new AdminRole("MyRoleName");</code><br /> * <code>myRole.setDescription("This is a test admin role");</code><br /> * <code>DelAdminMgr delAdminMgr = DelAdminMgrFactory.createInstance();</code><br /> * <code>delAdminMgr.addRole(myRole);</code><br /> * <p/> * This will create a AdminRole name that can be used as a target for User-AdminRole assignments and AdminRole-AdminPermission grants. * <p/> * <p/> * <h4>Administrative Role Schema</h4> * The Fortress AdminRole entity is a composite of the following other Fortress structural and aux object classes: * <p/> * 1. organizationalRole Structural Object Class is used to store basic attributes like cn and description. * <pre> * ------------------------------------------ * objectclass ( 2.5.6.8 NAME 'organizationalRole' * DESC 'RFC2256: an organizational role' * SUP top STRUCTURAL * MUST cn * MAY ( * x121Address $ registeredAddress $ destinationIndicator $ * preferredDeliveryMethod $ telexNumber $ teletexTerminalIdentifier $ * telephoneNumber $ internationaliSDNNumber $ facsimileTelephoneNumber $ * seeAlso $ roleOccupant $ preferredDeliveryMethod $ street $ * postOfficeBox $ postalCode $ postalAddress $ * physicalDeliveryOfficeName $ ou $ st $ l $ description * ) * ) * ------------------------------------------ * </pre> * <p/> * 2. ftRls Structural objectclass is used to store the AdminRole information like name, and temporal constraints. * <pre> * ------------------------------------------ * Fortress Roles Structural Object Class * objectclass ( 1.3.6.1.4.1.38088.2.1 * NAME 'ftRls' * DESC 'Fortress Role Structural Object Class' * SUP organizationalrole * STRUCTURAL * MUST ( * ftId $ * ftRoleName * ) * MAY ( * description $ * ftCstr $ * ftParents * ) * ) * ------------------------------------------ * </pre> * <p/> * 3. ftProperties AUXILIARY Object Class is used to store client specific name/value pairs on target entity.<br /> * <code># This aux object class can be used to store custom attributes.</code><br /> * <code># The properties collections consist of name/value pairs and are not constrainted by Fortress.</code><br /> * <pre> * ------------------------------------------ * AC2: Fortress Properties Auxiliary Object Class * objectclass ( 1.3.6.1.4.1.38088.3.2 * NAME 'ftProperties' * DESC 'Fortress Properties AUX Object Class' * AUXILIARY * MAY ( * ftProps * ) * ) * ------------------------------------------ * </pre> * <p/> * 4. ftPools Auxiliary object class store the ARBAC Perm and User OU assignments on AdminRole entity. * <pre> * ------------------------------------------ * Fortress Organizational Pools Auxiliary Object Class * objectclass ( 1.3.6.1.4.1.38088.3.3 * NAME 'ftPools' * DESC 'Fortress Pools AUX Object Class' * AUXILIARY * MAY ( * ftOSU $ * ftOSP $ * ftRange * ) * ) * ------------------------------------------ * </pre> * <p/> * 5. ftMods AUXILIARY Object Class is used to store Fortress audit variables on target entity. * <pre> * ------------------------------------------ * Fortress Audit Modification Auxiliary Object Class * objectclass ( 1.3.6.1.4.1.38088.3.4 * NAME 'ftMods' * DESC 'Fortress Modifiers AUX Object Class' * AUXILIARY * MAY ( * ftModifier $ * ftModCode $ * ftModId * ) * ) * ------------------------------------------ * </pre> * <p/> * * @author Shawn McKinney */ @XmlRootElement(name = "fortAdminRole") @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "adminRole", propOrder = { "osPs", "osUs", "beginRange", "endRange", "beginInclusive", "endInclusive" }) public class AdminRole extends Role implements Administrator { private Set<String> osPs; private Set<String> osUs; private String beginRange; private String endRange; private boolean beginInclusive; private boolean endInclusive; /** * Default constructor is used by internal Fortress classes. */ public AdminRole() { } /** * Construct an Admin Role with a given temporal constraint. * * @param con maps to 'OamRC' attribute for 'ftTemporal' aux object classes. */ public AdminRole( Constraint con ) { CUtil.copy( con, this ); } /** * Construct an AdminRole entity with a given name. * */ public AdminRole( String name ) { this.setName( name ); } /** * Load the role range attributes given a raw format. This method is used internal to Fortress and is not intended * to be used by external callers. * * @param szRaw maps to 'ftRange' attribute on 'ftPools' aux object class. */ @Override public void setRoleRangeRaw( String szRaw ) { if ( VUtil.isNotNullOrEmpty( szRaw ) ) { int bindx = szRaw.indexOf( "(" ); if ( bindx > -1 ) { this.setBeginInclusive( false ); } else { bindx = szRaw.indexOf( "[" ); this.setBeginInclusive( true ); } int eindx = szRaw.indexOf( ")" ); if ( eindx > -1 ) { this.setEndInclusive( false ); } else { eindx = szRaw.indexOf( "]" ); this.setEndInclusive( true ); } int cindx = szRaw.indexOf( ":" ); if ( cindx > -1 ) { String szBeginRange = szRaw.substring( bindx + 1, cindx ); String szEndRange = szRaw.substring( cindx + 1, eindx ); this.setBeginRange( szBeginRange ); this.setEndRange( szEndRange ); } } } /** * * Get the raw format for role range using current AdminRole entity attributes. This method is used internal to Fortress and is not intended * to be used by external callers. * * @return String maps to 'ftRange' attribute on 'ftPools' aux object class. */ @Override public String getRoleRangeRaw() { String szRaw = ""; if ( this.beginRange != null ) { if ( this.isBeginInclusive() ) szRaw += "["; else szRaw += "("; szRaw += this.getBeginRange(); szRaw += ":"; szRaw += this.getEndRange(); if ( this.isEndInclusive() ) szRaw += "]"; else szRaw += ")"; } return szRaw; } /** * Get a collection of optional Perm OU attributes that were stored on the AdminRole entity. * * @return List of type String containing Perm OU. This maps to 'ftOSP' attribute on 'ftPools' aux object class. */ @Override public Set<String> getOsP() { return osPs; } /** * Set a collection of optional Perm OU attributes to be stored on the AdminRole entity. * * @param osPs is a List of type String containing Perm OU. This maps to 'ftOSP' attribute on 'ftPools' aux object class. */ @Override public void setOsP( Set<String> osPs ) { this.osPs = osPs; } /** * Set a Perm OU attribute to be stored on the AdminRole entity. * * @param osP is a Perm OU that maps to 'ftOSP' attribute on 'ftPools' aux object class. */ @Override public void setOsP( String osP ) { if ( this.osPs == null ) { // create Set with case insensitive comparator: osPs = new TreeSet<>( String.CASE_INSENSITIVE_ORDER ); } osPs.add( osP ); } /** * Get a collection of optional User OU attributes that were stored on the AdminRole entity. * * @return List of type String containing User OU. This maps to 'ftOSU' attribute on 'ftPools' aux object class. */ @Override public Set<String> getOsU() { return osUs; } /** * Set a collection of optional User OU attributes to be stored on the AdminRole entity. * * @param osUs is a List of type String containing User OU. This maps to 'ftOSU' attribute on 'ftPools' aux object class. */ @Override public void setOsU( Set<String> osUs ) { this.osUs = osUs; } /** * Set a User OU attribute to be stored on the AdminRole entity. * * @param osU is a User OU that maps to 'ftOSU' attribute on 'ftPools' aux object class. */ @Override public void setOsU( String osU ) { if ( this.osUs == null ) { // create Set with case insensitive comparator: osUs = new TreeSet<>( String.CASE_INSENSITIVE_ORDER ); } osUs.add( osU ); } /** * Return the begin Role range attribute for AdminRole entity which corresponds to lowest descendant. * * @return String that maps to 'ftRange' attribute on 'ftPools' aux object class. */ @Override public String getBeginRange() { return beginRange; } /** * Set the begin Role range attribute for AdminRole entity which corresponds to lowest descendant. * * @param beginRange maps to 'ftRange' attribute on 'ftPools' aux object class. */ @Override public void setBeginRange( String beginRange ) { this.beginRange = beginRange; } /** * Return the end Role range attribute for AdminRole entity which corresponds to highest ascendant. * * @return String that maps to 'ftRange' attribute on 'ftPools' aux object class. */ @Override public String getEndRange() { return endRange; } /** * Set the end Role range attribute for AdminRole entity which corresponds to highest ascendant. * * @param endRange maps to 'ftRange' attribute on 'ftPools' aux object class. */ @Override public void setEndRange( String endRange ) { this.endRange = endRange; } /** * Get the begin inclusive which specifies if role range includes or excludes the 'beginRange' attribute. * * @return String that maps to 'ftRange' attribute on 'ftPools' aux object class. */ @Override public boolean isBeginInclusive() { return beginInclusive; } /** * Set the begin inclusive which specifies if role range includes or excludes the 'beginRange' attribute. * * @param beginInclusive maps to 'ftRange' attribute on 'ftPools' aux object class. */ @Override public void setBeginInclusive( boolean beginInclusive ) { this.beginInclusive = beginInclusive; } /** * Get the end inclusive which specifies if role range includes or excludes the 'endRange' attribute. * * @return String that maps to 'ftRange' attribute on 'ftPools' aux object class. */ @Override public boolean isEndInclusive() { return endInclusive; } /** * Set the end inclusive which specifies if role range includes or excludes the 'endRange' attribute. * * @param endInclusive maps to 'ftRange' attribute on 'ftPools' aux object class. */ @Override public void setEndInclusive( boolean endInclusive ) { this.endInclusive = endInclusive; } /** * Matches the name from two AdminRole entities. * * @param thatObj contains an AdminRole entity. * @return boolean indicating both objects contain matching AdminRole names. */ public boolean equals( Object thatObj ) { if ( this == thatObj ) return true; if ( this.getName() == null ) return false; if ( !( thatObj instanceof AdminRole ) ) return false; Role thatRole = ( Role ) thatObj; if ( thatRole.getName() == null ) return false; return thatRole.getName().equalsIgnoreCase( this.getName() ); } }
Added a toString() method
src/main/java/org/apache/directory/fortress/core/rbac/AdminRole.java
Added a toString() method
Java
apache-2.0
95b5b4d2935fba3d43d0a33fbcbc8573aae520ad
0
Netflix/servo,brharrington/servo,brharrington/servo
/* * Copyright 2014 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.servo.stats; import com.netflix.servo.util.Preconditions; import java.util.Arrays; import java.util.concurrent.atomic.AtomicBoolean; /** * A simple circular buffer that records values, and computes useful stats. * This implementation is not thread safe. */ public class StatsBuffer { private int pos; private int curSize; private double mean; private double variance; private double stddev; private long min; private long max; private long total; private final double[] percentiles; private final double[] percentileValues; private final int size; private final long[] values; private final AtomicBoolean statsComputed = new AtomicBoolean(false); /** * Create a circular buffer that will be used to record values and compute useful stats. * * @param size The capacity of the buffer * @param percentiles Array of percentiles to compute. For example { 95.0, 99.0 }. * If no percentileValues are required pass a 0-sized array. */ public StatsBuffer(int size, double[] percentiles) { Preconditions.checkArgument(size > 0, "Size of the buffer must be greater than 0"); Preconditions.checkArgument(percentiles != null, "Percents array must be non-null. Pass a 0-sized array " + "if you don't want any percentileValues to be computed."); Preconditions.checkArgument(validPercentiles(percentiles), "All percentiles should be in the interval (0.0, 100.0]"); values = new long[size]; this.size = size; this.percentiles = Arrays.copyOf(percentiles, percentiles.length); this.percentileValues = new double[percentiles.length]; reset(); } private static boolean validPercentiles(double[] percentiles) { for (double percentile : percentiles) { if (percentile <= 0.0 || percentile > 100.0) { return false; } } return true; } /** * Reset our local state: All values are set to 0. */ public void reset() { statsComputed.set(false); pos = 0; curSize = 0; total = 0L; mean = 0.0; variance = 0.0; stddev = 0.0; min = 0L; max = 0L; for (int i = 0; i < percentileValues.length; ++i) { percentileValues[i] = 0.0; } } /** * Record a new value for this buffer. */ public void record(long n) { values[Integer.remainderUnsigned(pos++, size)] = n; if (curSize < size) { ++curSize; } } /** * Compute stats for the current set of values. */ public void computeStats() { if (statsComputed.getAndSet(true)) { return; } if (curSize == 0) { return; } Arrays.sort(values, 0, curSize); // to compute percentileValues min = values[0]; max = values[curSize - 1]; // TODO: This should probably be changed to use Welford's method to // compute the variance. total = 0L; double sumSquares = 0.0; for (int i = 0; i < curSize; ++i) { total += values[i]; sumSquares += values[i] * values[i]; } mean = (double) total / curSize; variance = (sumSquares / curSize) - (mean * mean); stddev = Math.sqrt(variance); computePercentiles(curSize); } private void computePercentiles(int curSize) { for (int i = 0; i < percentiles.length; ++i) { percentileValues[i] = calcPercentile(curSize, percentiles[i]); } } private double calcPercentile(int curSize, double percent) { if (curSize == 0) { return 0.0; } if (curSize == 1) { return values[0]; } /* * We use the definition from http://cnx.org/content/m10805/latest * modified for 0-indexed arrays. */ final double rank = percent * curSize / 100.0; // SUPPRESS CHECKSTYLE MagicNumber final int ir = (int) Math.floor(rank); final int irNext = ir + 1; final double fr = rank - ir; if (irNext >= curSize) { return values[curSize - 1]; } else if (fr == 0.0) { return values[ir]; } else { // Interpolate between the two bounding values final double lower = values[ir]; final double upper = values[irNext]; return fr * (upper - lower) + lower; } } /** * Get the number of entries recorded up to the size of the buffer. */ public int getCount() { return curSize; } /** * Get the average of the values recorded. * * @return The average of the values recorded, or 0.0 if no values were recorded. */ public double getMean() { return mean; } /** * Get the variance for the population of the recorded values present in our buffer. * * @return The variance.p of the values recorded, or 0.0 if no values were recorded. */ public double getVariance() { return variance; } /** * Get the standard deviation for the population of the recorded values present in our buffer. * * @return The stddev.p of the values recorded, or 0.0 if no values were recorded. */ public double getStdDev() { return stddev; } /** * Get the minimum of the values currently in our buffer. * * @return The min of the values recorded, or 0.0 if no values were recorded. */ public long getMin() { return min; } /** * Get the max of the values currently in our buffer. * * @return The max of the values recorded, or 0.0 if no values were recorded. */ public long getMax() { return max; } /** * Get the total sum of the values recorded. * * @return The sum of the values recorded, or 0.0 if no values were recorded. */ public long getTotalTime() { return total; } /** * Get the computed percentileValues. See {@link StatsConfig} for how to request different * percentileValues. Note that for efficiency reasons we return the actual array of * computed values. * Users must NOT modify this array. * * @return An array of computed percentileValues. */ public double[] getPercentileValues() { return Arrays.copyOf(percentileValues, percentileValues.length); } /** * Return the percentiles we will compute: For example: 95.0, 99.0. */ public double[] getPercentiles() { return Arrays.copyOf(percentiles, percentiles.length); } /** * Return the value for the percentile given an index. * @param index If percentiles are [ 95.0, 99.0 ] index must be 0 or 1 to get the 95th * or 99th percentile respectively. * * @return The value for the percentile requested. */ public double getPercentileValueForIdx(int index) { return percentileValues[index]; } }
servo-core/src/main/java/com/netflix/servo/stats/StatsBuffer.java
/* * Copyright 2014 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.servo.stats; import com.netflix.servo.util.Preconditions; import java.util.Arrays; import java.util.concurrent.atomic.AtomicBoolean; /** * A simple circular buffer that records values, and computes useful stats. * This implementation is not thread safe. */ public class StatsBuffer { private int pos; private int curSize; private double mean; private double variance; private double stddev; private long min; private long max; private long total; private final double[] percentiles; private final double[] percentileValues; private final int size; private final long[] values; private final AtomicBoolean statsComputed = new AtomicBoolean(false); /** * Create a circular buffer that will be used to record values and compute useful stats. * * @param size The capacity of the buffer * @param percentiles Array of percentiles to compute. For example { 95.0, 99.0 }. * If no percentileValues are required pass a 0-sized array. */ public StatsBuffer(int size, double[] percentiles) { Preconditions.checkArgument(size > 0, "Size of the buffer must be greater than 0"); Preconditions.checkArgument(percentiles != null, "Percents array must be non-null. Pass a 0-sized array " + "if you don't want any percentileValues to be computed."); Preconditions.checkArgument(validPercentiles(percentiles), "All percentiles should be in the interval (0.0, 100.0]"); values = new long[size]; this.size = size; this.percentiles = Arrays.copyOf(percentiles, percentiles.length); this.percentileValues = new double[percentiles.length]; reset(); } private static boolean validPercentiles(double[] percentiles) { for (double percentile : percentiles) { if (percentile <= 0.0 || percentile > 100.0) { return false; } } return true; } /** * Reset our local state: All values are set to 0. */ public void reset() { statsComputed.set(false); pos = 0; curSize = 0; total = 0L; mean = 0.0; variance = 0.0; stddev = 0.0; min = 0L; max = 0L; for (int i = 0; i < percentileValues.length; ++i) { percentileValues[i] = 0.0; } } /** * Record a new value for this buffer. */ public void record(long n) { values[Integer.remainderUnsigned(pos++, size)] = n; if (curSize < size) ++curSize; } /** * Compute stats for the current set of values. */ public void computeStats() { if (statsComputed.getAndSet(true)) { return; } if (curSize == 0) { return; } Arrays.sort(values, 0, curSize); // to compute percentileValues min = values[0]; max = values[curSize - 1]; // TODO: This should probably be changed to use Welford's method to // compute the variance. total = 0L; double sumSquares = 0.0; for (int i = 0; i < curSize; ++i) { total += values[i]; sumSquares += values[i] * values[i]; } mean = (double) total / curSize; variance = (sumSquares / curSize) - (mean * mean); stddev = Math.sqrt(variance); computePercentiles(curSize); } private void computePercentiles(int curSize) { for (int i = 0; i < percentiles.length; ++i) { percentileValues[i] = calcPercentile(curSize, percentiles[i]); } } private double calcPercentile(int curSize, double percent) { if (curSize == 0) { return 0.0; } if (curSize == 1) { return values[0]; } /* * We use the definition from http://cnx.org/content/m10805/latest * modified for 0-indexed arrays. */ final double rank = percent * curSize / 100.0; // SUPPRESS CHECKSTYLE MagicNumber final int ir = (int) Math.floor(rank); final int irNext = ir + 1; final double fr = rank - ir; if (irNext >= curSize) { return values[curSize - 1]; } else if (fr == 0.0) { return values[ir]; } else { // Interpolate between the two bounding values final double lower = values[ir]; final double upper = values[irNext]; return fr * (upper - lower) + lower; } } /** * Get the number of entries recorded up to the size of the buffer. */ public int getCount() { return curSize; } /** * Get the average of the values recorded. * * @return The average of the values recorded, or 0.0 if no values were recorded. */ public double getMean() { return mean; } /** * Get the variance for the population of the recorded values present in our buffer. * * @return The variance.p of the values recorded, or 0.0 if no values were recorded. */ public double getVariance() { return variance; } /** * Get the standard deviation for the population of the recorded values present in our buffer. * * @return The stddev.p of the values recorded, or 0.0 if no values were recorded. */ public double getStdDev() { return stddev; } /** * Get the minimum of the values currently in our buffer. * * @return The min of the values recorded, or 0.0 if no values were recorded. */ public long getMin() { return min; } /** * Get the max of the values currently in our buffer. * * @return The max of the values recorded, or 0.0 if no values were recorded. */ public long getMax() { return max; } /** * Get the total sum of the values recorded. * * @return The sum of the values recorded, or 0.0 if no values were recorded. */ public long getTotalTime() { return total; } /** * Get the computed percentileValues. See {@link StatsConfig} for how to request different * percentileValues. Note that for efficiency reasons we return the actual array of * computed values. * Users must NOT modify this array. * * @return An array of computed percentileValues. */ public double[] getPercentileValues() { return Arrays.copyOf(percentileValues, percentileValues.length); } /** * Return the percentiles we will compute: For example: 95.0, 99.0. */ public double[] getPercentiles() { return Arrays.copyOf(percentiles, percentiles.length); } /** * Return the value for the percentile given an index. * @param index If percentiles are [ 95.0, 99.0 ] index must be 0 or 1 to get the 95th * or 99th percentile respectively. * * @return The value for the percentile requested. */ public double getPercentileValueForIdx(int index) { return percentileValues[index]; } }
fix checkstyle warning
servo-core/src/main/java/com/netflix/servo/stats/StatsBuffer.java
fix checkstyle warning
Java
apache-2.0
f0c69227c6523023ea19dbe6d26281bc2b6640da
0
liuyuanyuan/dbeaver,AndrewKhitrin/dbeaver,AndrewKhitrin/dbeaver,liuyuanyuan/dbeaver,AndrewKhitrin/dbeaver,liuyuanyuan/dbeaver,liuyuanyuan/dbeaver,liuyuanyuan/dbeaver,AndrewKhitrin/dbeaver
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2017 Serge Rider ([email protected]) * Copyright (C) 2011-2012 Eugene Fradkin ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.ui.preferences; import org.eclipse.jface.fieldassist.SimpleContentProposalProvider; import org.eclipse.jface.fieldassist.TextContentAdapter; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.*; import org.eclipse.ui.IEditorSite; import org.jkiss.dbeaver.ModelPreferences; import org.jkiss.dbeaver.core.CoreMessages; import org.jkiss.dbeaver.model.DBPDataSource; import org.jkiss.dbeaver.model.DBPDataSourceContainer; import org.jkiss.dbeaver.model.DBPIdentifierCase; import org.jkiss.dbeaver.model.exec.DBCExecutionContext; import org.jkiss.dbeaver.model.preferences.DBPPreferenceStore; import org.jkiss.dbeaver.model.sql.format.external.SQLFormatterExternal; import org.jkiss.dbeaver.ui.UIUtils; import org.jkiss.dbeaver.ui.editors.StringEditorInput; import org.jkiss.dbeaver.ui.editors.SubEditorSite; import org.jkiss.dbeaver.ui.editors.sql.SQLEditorBase; import org.jkiss.dbeaver.ui.editors.sql.SQLPreferenceConstants; import org.jkiss.dbeaver.ui.editors.sql.registry.SQLFormatterConfigurationRegistry; import org.jkiss.dbeaver.ui.editors.sql.registry.SQLFormatterDescriptor; import org.jkiss.dbeaver.utils.ContentUtils; import org.jkiss.dbeaver.utils.GeneralUtils; import org.jkiss.dbeaver.utils.PrefUtils; import org.jkiss.utils.CommonUtils; import java.io.InputStream; import java.util.List; import java.util.Locale; /** * PrefPageSQLFormat */ public class PrefPageSQLFormat extends TargetPrefPage { public static final String PAGE_ID = "org.jkiss.dbeaver.preferences.main.sql.format"; //$NON-NLS-1$ private final static String FORMAT_FILE_NAME = "format_preview.sql"; private Button styleBoldKeywords; // Formatter private Combo formatterSelector; private Combo keywordCaseCombo; private Text externalCmdText; private Button externalUseFile; private Spinner externalTimeout; private SQLEditorBase sqlViewer; private Composite externalGroup; private List<SQLFormatterDescriptor> formatters; public PrefPageSQLFormat() { super(); } @Override protected boolean hasDataSourceSpecificOptions(DBPDataSourceContainer dataSourceDescriptor) { DBPPreferenceStore store = dataSourceDescriptor.getPreferenceStore(); return store.contains(SQLPreferenceConstants.SQL_FORMAT_BOLD_KEYWORDS) || store.contains(ModelPreferences.SQL_FORMAT_FORMATTER) || store.contains(ModelPreferences.SQL_FORMAT_KEYWORD_CASE) || store.contains(ModelPreferences.SQL_FORMAT_EXTERNAL_CMD) || store.contains(ModelPreferences.SQL_FORMAT_EXTERNAL_FILE) || store.contains(ModelPreferences.SQL_FORMAT_EXTERNAL_TIMEOUT) ; } @Override protected boolean supportsDataSourceSpecificOptions() { return true; } @Override protected Control createPreferenceContent(Composite parent) { Composite composite = UIUtils.createPlaceholder(parent, 2, 5); { // Styles Composite afGroup = UIUtils.createControlGroup(composite, CoreMessages.pref_page_sql_format_group_style, 1, GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING, 0); ((GridData)afGroup.getLayoutData()).horizontalSpan = 2; styleBoldKeywords = UIUtils.createCheckbox( afGroup, CoreMessages.pref_page_sql_format_label_bold_keywords, CoreMessages.pref_page_sql_format_label_bold_keywords_tip, false, 1); styleBoldKeywords.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { performApply(); } }); } formatterSelector = UIUtils.createLabelCombo(composite, CoreMessages.pref_page_sql_format_label_formatter, SWT.DROP_DOWN | SWT.READ_ONLY); formatterSelector.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); formatters = SQLFormatterConfigurationRegistry.getInstance().getFormatters(); for (SQLFormatterDescriptor formatterDesc : formatters) { formatterSelector.add(DBPIdentifierCase.capitalizeCaseName(formatterDesc.getLabel())); } formatterSelector.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { showFormatterSettings(); performApply(); } }); formatterSelector.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); Composite formatterGroup = UIUtils.createPlaceholder(composite, 1, 5); formatterGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); ((GridData)formatterGroup.getLayoutData()).horizontalSpan = 2; { Composite formatterPanel = UIUtils.createPlaceholder(formatterGroup, 4, 5); formatterPanel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); keywordCaseCombo = UIUtils.createLabelCombo(formatterPanel, CoreMessages.pref_page_sql_format_label_keyword_case, SWT.DROP_DOWN | SWT.READ_ONLY); keywordCaseCombo.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); keywordCaseCombo.add("Database"); for (DBPIdentifierCase c :DBPIdentifierCase.values()) { keywordCaseCombo.add(DBPIdentifierCase.capitalizeCaseName(c.name())); } keywordCaseCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { performApply(); } }); } // External formatter { externalGroup = UIUtils.createPlaceholder(formatterGroup, 2, 5); externalGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.HORIZONTAL_ALIGN_BEGINNING)); externalCmdText = UIUtils.createLabelText(externalGroup, CoreMessages.pref_page_sql_format_label_external_command_line, ""); externalCmdText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); UIUtils.installContentProposal( externalCmdText, new TextContentAdapter(), new SimpleContentProposalProvider(new String[] { GeneralUtils.variablePattern(SQLFormatterExternal.VAR_FILE) })); UIUtils.setContentProposalToolTip(externalCmdText, CoreMessages.pref_page_sql_format_label_external_set_content_tool_tip, SQLFormatterExternal.VAR_FILE); externalUseFile = UIUtils.createLabelCheckbox(externalGroup, CoreMessages.pref_page_sql_format_label_external_use_temp_file, CoreMessages.pref_page_sql_format_label_external_use_temp_file_tip + GeneralUtils.variablePattern(SQLFormatterExternal.VAR_FILE), false); externalTimeout = UIUtils.createLabelSpinner(externalGroup, CoreMessages.pref_page_sql_format_label_external_exec_timeout, CoreMessages.pref_page_sql_format_label_external_exec_timeout_tip, 100, 100, 10000); } { // SQL preview Composite previewGroup = new Composite(composite, SWT.BORDER); GridData gd = new GridData(GridData.FILL_BOTH); gd.horizontalSpan = 2; previewGroup.setLayoutData(gd); previewGroup.setLayout(new FillLayout()); sqlViewer = new SQLEditorBase() { @Override public DBCExecutionContext getExecutionContext() { final DBPDataSourceContainer container = getDataSourceContainer(); if (container != null) { final DBPDataSource dataSource = container.getDataSource(); if (dataSource != null) { return dataSource.getDefaultInstance().getDefaultContext(false); } } return null; } }; try { try (final InputStream sqlStream = getClass().getResourceAsStream(FORMAT_FILE_NAME)) { final String sqlText = ContentUtils.readToString(sqlStream, GeneralUtils.DEFAULT_ENCODING); IEditorSite subSite = new SubEditorSite(UIUtils.getActiveWorkbenchWindow().getActivePage().getActivePart().getSite()); StringEditorInput sqlInput = new StringEditorInput("SQL preview", sqlText, true, GeneralUtils.getDefaultFileEncoding()); sqlViewer.init(subSite, sqlInput); } } catch (Exception e) { log.error(e); } sqlViewer.createPartControl(previewGroup); Object text = sqlViewer.getAdapter(Control.class); if (text instanceof StyledText) { ((StyledText) text).setWordWrap(true); } sqlViewer.reloadSyntaxRules(); previewGroup.addDisposeListener(e -> sqlViewer.dispose()); } return composite; } @Override protected void loadPreferences(DBPPreferenceStore store) { styleBoldKeywords.setSelection(store.getBoolean(SQLPreferenceConstants.SQL_FORMAT_BOLD_KEYWORDS)); String formatterId = store.getString(ModelPreferences.SQL_FORMAT_FORMATTER); for (int i = 0; i < formatters.size(); i++) { if (formatters.get(i).getId().equalsIgnoreCase(formatterId)) { formatterSelector.select(i); break; } } if (formatterSelector.getSelectionIndex() < 0) formatterSelector.select(0); final String caseName = store.getString(ModelPreferences.SQL_FORMAT_KEYWORD_CASE); if (CommonUtils.isEmpty(caseName)) { keywordCaseCombo.select(0); } else { UIUtils.setComboSelection(keywordCaseCombo, DBPIdentifierCase.capitalizeCaseName(caseName)); } externalCmdText.setText(store.getString(ModelPreferences.SQL_FORMAT_EXTERNAL_CMD)); externalUseFile.setSelection(store.getBoolean(ModelPreferences.SQL_FORMAT_EXTERNAL_FILE)); externalTimeout.setSelection(store.getInt(ModelPreferences.SQL_FORMAT_EXTERNAL_TIMEOUT)); formatSQL(); showFormatterSettings(); } @Override protected void savePreferences(DBPPreferenceStore store) { store.setValue(SQLPreferenceConstants.SQL_FORMAT_BOLD_KEYWORDS, styleBoldKeywords.getSelection()); store.setValue(ModelPreferences.SQL_FORMAT_FORMATTER, formatters.get(formatterSelector.getSelectionIndex()).getId().toUpperCase(Locale.ENGLISH)); final String caseName; if (keywordCaseCombo.getSelectionIndex() == 0) { caseName = ""; } else { caseName = keywordCaseCombo.getText().toUpperCase(Locale.ENGLISH); } store.setValue(ModelPreferences.SQL_FORMAT_KEYWORD_CASE, caseName); store.setValue(ModelPreferences.SQL_FORMAT_EXTERNAL_CMD, externalCmdText.getText()); store.setValue(ModelPreferences.SQL_FORMAT_EXTERNAL_FILE, externalUseFile.getSelection()); store.setValue(ModelPreferences.SQL_FORMAT_EXTERNAL_TIMEOUT, externalTimeout.getSelection()); PrefUtils.savePreferenceStore(store); } @Override protected void clearPreferences(DBPPreferenceStore store) { store.setToDefault(SQLPreferenceConstants.SQL_FORMAT_BOLD_KEYWORDS); store.setToDefault(ModelPreferences.SQL_FORMAT_FORMATTER); store.setToDefault(ModelPreferences.SQL_FORMAT_KEYWORD_CASE); store.setToDefault(ModelPreferences.SQL_FORMAT_EXTERNAL_CMD); } @Override protected void performApply() { super.performApply(); formatSQL(); } @Override protected String getPropertyPageID() { return PAGE_ID; } private void showFormatterSettings() { SQLFormatterDescriptor selFormatter = formatters.get(formatterSelector.getSelectionIndex()); boolean isExternal = selFormatter.getId().equalsIgnoreCase(SQLFormatterExternal.FORMATTER_ID); externalGroup.setVisible(isExternal); ((GridData)externalGroup.getLayoutData()).exclude = !isExternal; externalGroup.getParent().getParent().layout(); } private void formatSQL() { try { try (final InputStream sqlStream = getClass().getResourceAsStream(FORMAT_FILE_NAME)) { final String sqlText = ContentUtils.readToString(sqlStream, GeneralUtils.DEFAULT_ENCODING); sqlViewer.setInput(new StringEditorInput("SQL preview", sqlText, true, GeneralUtils.getDefaultFileEncoding())); } } catch (Exception e) { log.error(e); } sqlViewer.getTextViewer().doOperation(ISourceViewer.FORMAT); sqlViewer.reloadSyntaxRules(); } }
plugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/ui/preferences/PrefPageSQLFormat.java
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2017 Serge Rider ([email protected]) * Copyright (C) 2011-2012 Eugene Fradkin ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.ui.preferences; import org.eclipse.jface.fieldassist.SimpleContentProposalProvider; import org.eclipse.jface.fieldassist.TextContentAdapter; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.*; import org.eclipse.ui.IEditorSite; import org.jkiss.dbeaver.ModelPreferences; import org.jkiss.dbeaver.core.CoreMessages; import org.jkiss.dbeaver.model.DBPDataSource; import org.jkiss.dbeaver.model.DBPDataSourceContainer; import org.jkiss.dbeaver.model.DBPIdentifierCase; import org.jkiss.dbeaver.model.exec.DBCExecutionContext; import org.jkiss.dbeaver.model.preferences.DBPPreferenceStore; import org.jkiss.dbeaver.model.sql.format.external.SQLFormatterExternal; import org.jkiss.dbeaver.ui.editors.sql.registry.SQLFormatterConfigurationRegistry; import org.jkiss.dbeaver.ui.editors.sql.registry.SQLFormatterDescriptor; import org.jkiss.dbeaver.ui.UIUtils; import org.jkiss.dbeaver.ui.editors.StringEditorInput; import org.jkiss.dbeaver.ui.editors.SubEditorSite; import org.jkiss.dbeaver.ui.editors.sql.SQLEditorBase; import org.jkiss.dbeaver.ui.editors.sql.SQLPreferenceConstants; import org.jkiss.dbeaver.utils.ContentUtils; import org.jkiss.dbeaver.utils.GeneralUtils; import org.jkiss.dbeaver.utils.PrefUtils; import org.jkiss.utils.CommonUtils; import java.io.InputStream; import java.util.List; import java.util.Locale; /** * PrefPageSQLFormat */ public class PrefPageSQLFormat extends TargetPrefPage { public static final String PAGE_ID = "org.jkiss.dbeaver.preferences.main.sql.format"; //$NON-NLS-1$ private final static String FORMAT_FILE_NAME = "format_preview.sql"; private Button styleBoldKeywords; // Formatter private Combo formatterSelector; private Combo keywordCaseCombo; private Text externalCmdText; private Button externalUseFile; private Spinner externalTimeout; private SQLEditorBase sqlViewer; private Composite externalGroup; private List<SQLFormatterDescriptor> formatters; public PrefPageSQLFormat() { super(); } @Override protected boolean hasDataSourceSpecificOptions(DBPDataSourceContainer dataSourceDescriptor) { DBPPreferenceStore store = dataSourceDescriptor.getPreferenceStore(); return store.contains(SQLPreferenceConstants.SQL_FORMAT_BOLD_KEYWORDS) || store.contains(ModelPreferences.SQL_FORMAT_FORMATTER) || store.contains(ModelPreferences.SQL_FORMAT_KEYWORD_CASE) || store.contains(ModelPreferences.SQL_FORMAT_EXTERNAL_CMD) || store.contains(ModelPreferences.SQL_FORMAT_EXTERNAL_FILE) || store.contains(ModelPreferences.SQL_FORMAT_EXTERNAL_TIMEOUT) ; } @Override protected boolean supportsDataSourceSpecificOptions() { return true; } @Override protected Control createPreferenceContent(Composite parent) { Composite composite = UIUtils.createPlaceholder(parent, 2, 5); { // Styles Composite afGroup = UIUtils.createControlGroup(composite, CoreMessages.pref_page_sql_format_group_style, 1, GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING, 0); ((GridData)afGroup.getLayoutData()).horizontalSpan = 2; styleBoldKeywords = UIUtils.createCheckbox( afGroup, CoreMessages.pref_page_sql_format_label_bold_keywords, CoreMessages.pref_page_sql_format_label_bold_keywords_tip, false, 1); styleBoldKeywords.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { performApply(); } }); } Composite formatterGroup = UIUtils.createControlGroup(composite, CoreMessages.pref_page_sql_format_group_formatter, 1, GridData.FILL_BOTH, 0); ((GridData)formatterGroup.getLayoutData()).horizontalSpan = 2; { Composite formatterPanel = UIUtils.createPlaceholder(formatterGroup, 4, 5); formatterPanel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); formatterSelector = UIUtils.createLabelCombo(formatterPanel, CoreMessages.pref_page_sql_format_label_formatter, SWT.DROP_DOWN | SWT.READ_ONLY); formatters = SQLFormatterConfigurationRegistry.getInstance().getFormatters(); for (SQLFormatterDescriptor formatterDesc : formatters) { formatterSelector.add(DBPIdentifierCase.capitalizeCaseName(formatterDesc.getLabel())); } formatterSelector.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { showFormatterSettings(); performApply(); } }); formatterSelector.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); keywordCaseCombo = UIUtils.createLabelCombo(formatterPanel, CoreMessages.pref_page_sql_format_label_keyword_case, SWT.DROP_DOWN | SWT.READ_ONLY); keywordCaseCombo.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); keywordCaseCombo.add("Database"); for (DBPIdentifierCase c :DBPIdentifierCase.values()) { keywordCaseCombo.add(DBPIdentifierCase.capitalizeCaseName(c.name())); } keywordCaseCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { performApply(); } }); } // External formatter { externalGroup = UIUtils.createPlaceholder(formatterGroup, 2, 5); externalGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.HORIZONTAL_ALIGN_BEGINNING)); externalCmdText = UIUtils.createLabelText(externalGroup, CoreMessages.pref_page_sql_format_label_external_command_line, ""); externalCmdText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); UIUtils.installContentProposal( externalCmdText, new TextContentAdapter(), new SimpleContentProposalProvider(new String[] { GeneralUtils.variablePattern(SQLFormatterExternal.VAR_FILE) })); UIUtils.setContentProposalToolTip(externalCmdText, CoreMessages.pref_page_sql_format_label_external_set_content_tool_tip, SQLFormatterExternal.VAR_FILE); externalUseFile = UIUtils.createLabelCheckbox(externalGroup, CoreMessages.pref_page_sql_format_label_external_use_temp_file, CoreMessages.pref_page_sql_format_label_external_use_temp_file_tip + GeneralUtils.variablePattern(SQLFormatterExternal.VAR_FILE), false); externalTimeout = UIUtils.createLabelSpinner(externalGroup, CoreMessages.pref_page_sql_format_label_external_exec_timeout, CoreMessages.pref_page_sql_format_label_external_exec_timeout_tip, 100, 100, 10000); } { // SQL preview Composite previewGroup = new Composite(formatterGroup, SWT.BORDER); previewGroup.setLayoutData(new GridData(GridData.FILL_BOTH)); previewGroup.setLayout(new FillLayout()); sqlViewer = new SQLEditorBase() { @Override public DBCExecutionContext getExecutionContext() { final DBPDataSourceContainer container = getDataSourceContainer(); if (container != null) { final DBPDataSource dataSource = container.getDataSource(); if (dataSource != null) { return dataSource.getDefaultInstance().getDefaultContext(false); } } return null; } }; try { try (final InputStream sqlStream = getClass().getResourceAsStream(FORMAT_FILE_NAME)) { final String sqlText = ContentUtils.readToString(sqlStream, GeneralUtils.DEFAULT_ENCODING); IEditorSite subSite = new SubEditorSite(UIUtils.getActiveWorkbenchWindow().getActivePage().getActivePart().getSite()); StringEditorInput sqlInput = new StringEditorInput("SQL preview", sqlText, true, GeneralUtils.getDefaultFileEncoding()); sqlViewer.init(subSite, sqlInput); } } catch (Exception e) { log.error(e); } sqlViewer.createPartControl(previewGroup); Object text = sqlViewer.getAdapter(Control.class); if (text instanceof StyledText) { ((StyledText) text).setWordWrap(true); } sqlViewer.reloadSyntaxRules(); previewGroup.addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { sqlViewer.dispose(); } }); } return composite; } @Override protected void loadPreferences(DBPPreferenceStore store) { styleBoldKeywords.setSelection(store.getBoolean(SQLPreferenceConstants.SQL_FORMAT_BOLD_KEYWORDS)); String formatterId = store.getString(ModelPreferences.SQL_FORMAT_FORMATTER); for (int i = 0; i < formatters.size(); i++) { if (formatters.get(i).getId().equalsIgnoreCase(formatterId)) { formatterSelector.select(i); break; } } if (formatterSelector.getSelectionIndex() < 0) formatterSelector.select(0); final String caseName = store.getString(ModelPreferences.SQL_FORMAT_KEYWORD_CASE); if (CommonUtils.isEmpty(caseName)) { keywordCaseCombo.select(0); } else { UIUtils.setComboSelection(keywordCaseCombo, DBPIdentifierCase.capitalizeCaseName(caseName)); } externalCmdText.setText(store.getString(ModelPreferences.SQL_FORMAT_EXTERNAL_CMD)); externalUseFile.setSelection(store.getBoolean(ModelPreferences.SQL_FORMAT_EXTERNAL_FILE)); externalTimeout.setSelection(store.getInt(ModelPreferences.SQL_FORMAT_EXTERNAL_TIMEOUT)); formatSQL(); showFormatterSettings(); } @Override protected void savePreferences(DBPPreferenceStore store) { store.setValue(SQLPreferenceConstants.SQL_FORMAT_BOLD_KEYWORDS, styleBoldKeywords.getSelection()); store.setValue(ModelPreferences.SQL_FORMAT_FORMATTER, formatters.get(formatterSelector.getSelectionIndex()).getId().toUpperCase(Locale.ENGLISH)); final String caseName; if (keywordCaseCombo.getSelectionIndex() == 0) { caseName = ""; } else { caseName = keywordCaseCombo.getText().toUpperCase(Locale.ENGLISH); } store.setValue(ModelPreferences.SQL_FORMAT_KEYWORD_CASE, caseName); store.setValue(ModelPreferences.SQL_FORMAT_EXTERNAL_CMD, externalCmdText.getText()); store.setValue(ModelPreferences.SQL_FORMAT_EXTERNAL_FILE, externalUseFile.getSelection()); store.setValue(ModelPreferences.SQL_FORMAT_EXTERNAL_TIMEOUT, externalTimeout.getSelection()); PrefUtils.savePreferenceStore(store); } @Override protected void clearPreferences(DBPPreferenceStore store) { store.setToDefault(SQLPreferenceConstants.SQL_FORMAT_BOLD_KEYWORDS); store.setToDefault(ModelPreferences.SQL_FORMAT_FORMATTER); store.setToDefault(ModelPreferences.SQL_FORMAT_KEYWORD_CASE); store.setToDefault(ModelPreferences.SQL_FORMAT_EXTERNAL_CMD); } @Override protected void performApply() { super.performApply(); formatSQL(); } @Override protected String getPropertyPageID() { return PAGE_ID; } private void showFormatterSettings() { SQLFormatterDescriptor selFormatter = formatters.get(formatterSelector.getSelectionIndex()); boolean isExternal = selFormatter.getId().equalsIgnoreCase(SQLFormatterExternal.FORMATTER_ID); externalGroup.setVisible(isExternal); ((GridData)externalGroup.getLayoutData()).exclude = !isExternal; externalGroup.getParent().layout(); } private void formatSQL() { try { try (final InputStream sqlStream = getClass().getResourceAsStream(FORMAT_FILE_NAME)) { final String sqlText = ContentUtils.readToString(sqlStream, GeneralUtils.DEFAULT_ENCODING); sqlViewer.setInput(new StringEditorInput("SQL preview", sqlText, true, GeneralUtils.getDefaultFileEncoding())); } } catch (Exception e) { log.error(e); } sqlViewer.getTextViewer().doOperation(ISourceViewer.FORMAT); sqlViewer.reloadSyntaxRules(); } }
SQL formatter preference page refactoring
plugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/ui/preferences/PrefPageSQLFormat.java
SQL formatter preference page refactoring
Java
apache-2.0
ba2d55068a0c4e19b29616c1265575da674a5170
0
gzsombor/ranger,gzsombor/ranger,gzsombor/ranger,gzsombor/ranger,gzsombor/ranger,gzsombor/ranger
/* * 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.ranger.unixusersync.process; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.UnknownHostException; import java.security.KeyStore; import java.security.PrivilegedAction; import java.security.SecureRandom; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.regex.Pattern; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.security.auth.Subject; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.core.Cookie; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.NewCookie; import org.apache.hadoop.security.SecureClientLogin; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.ranger.plugin.util.URLEncoderUtil; import org.apache.ranger.unixusersync.config.UserGroupSyncConfig; import org.apache.ranger.unixusersync.model.GetXGroupListResponse; import org.apache.ranger.unixusersync.model.GetXUserGroupListResponse; import org.apache.ranger.unixusersync.model.GetXUserListResponse; import org.apache.ranger.unixusersync.model.MUserInfo; import org.apache.ranger.unixusersync.model.UgsyncAuditInfo; import org.apache.ranger.unixusersync.model.UserGroupInfo; import org.apache.ranger.unixusersync.model.XGroupInfo; import org.apache.ranger.unixusersync.model.XUserGroupInfo; import org.apache.ranger.unixusersync.model.XUserInfo; import org.apache.ranger.usergroupsync.UserGroupSink; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import com.sun.jersey.client.urlconnection.HTTPSProperties; public class PolicyMgrUserGroupBuilder implements UserGroupSink { private static final Logger LOG = Logger.getLogger(PolicyMgrUserGroupBuilder.class); private static final String AUTHENTICATION_TYPE = "hadoop.security.authentication"; private String AUTH_KERBEROS = "kerberos"; private static final String PRINCIPAL = "ranger.usersync.kerberos.principal"; private static final String KEYTAB = "ranger.usersync.kerberos.keytab"; private static final String NAME_RULE = "hadoop.security.auth_to_local"; public static final String PM_USER_LIST_URI = "/service/xusers/users/"; // GET private static final String PM_ADD_USER_GROUP_INFO_URI = "/service/xusers/users/userinfo"; // POST public static final String PM_GROUP_LIST_URI = "/service/xusers/groups/"; // GET private static final String PM_ADD_GROUP_URI = "/service/xusers/groups/"; // POST public static final String PM_USER_GROUP_MAP_LIST_URI = "/service/xusers/groupusers/"; // GET private static final String PM_DEL_USER_GROUP_LINK_URI = "/service/xusers/group/${groupName}/user/${userName}"; // DELETE private static final String PM_ADD_LOGIN_USER_URI = "/service/users/default"; // POST private static final String PM_AUDIT_INFO_URI = "/service/xusers/ugsync/auditinfo/"; // POST private static final String GROUP_SOURCE_EXTERNAL ="1"; private static final String RANGER_ADMIN_COOKIE_NAME = "RANGERADMINSESSIONID"; private static String LOCAL_HOSTNAME = "unknown"; private String recordsToPullPerCall = "1000"; private boolean isMockRun = false; private String policyMgrBaseUrl; private Cookie sessionId=null; private boolean isValidRangerCookie=false; List<NewCookie> cookieList=new ArrayList<>(); private UserGroupSyncConfig config = UserGroupSyncConfig.getInstance(); private UserGroupInfo usergroupInfo = new UserGroupInfo(); private List<XGroupInfo> xgroupList; private List<XUserInfo> xuserList; private List<XUserGroupInfo> xusergroupList; private HashMap<String,XUserInfo> userId2XUserInfoMap; private HashMap<String,XUserInfo> userName2XUserInfoMap; private HashMap<String,XGroupInfo> groupName2XGroupInfoMap; private String keyStoreFile = null; private String keyStoreFilepwd = null; private String trustStoreFile = null; private String trustStoreFilepwd = null; private String keyStoreType = null; private String trustStoreType = null; private HostnameVerifier hv = null; private SSLContext sslContext = null; private String authenticationType = null; String principal; String keytab; String nameRules; Map<String, String> userMap; Map<String, String> groupMap; private int noOfNewUsers; private int noOfNewGroups; private int noOfModifiedUsers; private int noOfModifiedGroups; private HashSet<String> newUserList = new HashSet<String>(); private HashSet<String> modifiedUserList = new HashSet<String>(); private HashSet<String> newGroupList = new HashSet<String>(); private HashSet<String> modifiedGroupList = new HashSet<String>(); private boolean isRangerCookieEnabled; boolean isStartupFlag = false; private volatile Client client; static { try { LOCAL_HOSTNAME = java.net.InetAddress.getLocalHost().getCanonicalHostName(); } catch (UnknownHostException e) { LOCAL_HOSTNAME = "unknown"; } } public static void main(String[] args) throws Throwable { PolicyMgrUserGroupBuilder ugbuilder = new PolicyMgrUserGroupBuilder(); ugbuilder.init(); } synchronized public void init() throws Throwable { xgroupList = new ArrayList<XGroupInfo>(); xuserList = new ArrayList<XUserInfo>(); xusergroupList = new ArrayList<XUserGroupInfo>(); userId2XUserInfoMap = new HashMap<String,XUserInfo>(); userName2XUserInfoMap = new HashMap<String,XUserInfo>(); groupName2XGroupInfoMap = new HashMap<String,XGroupInfo>(); userMap = new LinkedHashMap<String, String>(); groupMap = new LinkedHashMap<String, String>(); recordsToPullPerCall = config.getMaxRecordsPerAPICall(); policyMgrBaseUrl = config.getPolicyManagerBaseURL(); isMockRun = config.isMockRunEnabled(); noOfNewUsers = 0; noOfModifiedUsers = 0; noOfNewGroups = 0; noOfModifiedGroups = 0; isStartupFlag = true; isRangerCookieEnabled = config.isUserSyncRangerCookieEnabled(); if (isMockRun) { LOG.setLevel(Level.DEBUG); } sessionId=null; keyStoreFile = config.getSSLKeyStorePath(); keyStoreFilepwd = config.getSSLKeyStorePathPassword(); trustStoreFile = config.getSSLTrustStorePath(); trustStoreFilepwd = config.getSSLTrustStorePathPassword(); keyStoreType = KeyStore.getDefaultType(); trustStoreType = KeyStore.getDefaultType(); authenticationType = config.getProperty(AUTHENTICATION_TYPE,"simple"); try { principal = SecureClientLogin.getPrincipal(config.getProperty(PRINCIPAL,""), LOCAL_HOSTNAME); } catch (IOException ignored) { // do nothing } keytab = config.getProperty(KEYTAB,""); nameRules = config.getProperty(NAME_RULE,"DEFAULT"); String userGroupRoles = config.getGroupRoleRules(); if (userGroupRoles != null && !userGroupRoles.isEmpty()) { getRoleForUserGroups(userGroupRoles); } buildUserGroupInfo(); } private void buildUserGroupInfo() throws Throwable { if(authenticationType != null && AUTH_KERBEROS.equalsIgnoreCase(authenticationType) && SecureClientLogin.isKerberosCredentialExists(principal, keytab)){ if(LOG.isDebugEnabled()) { LOG.debug("==> Kerberos Environment : Principal is " + principal + " and Keytab is " + keytab); } } if (authenticationType != null && AUTH_KERBEROS.equalsIgnoreCase(authenticationType) && SecureClientLogin.isKerberosCredentialExists(principal, keytab)) { try { LOG.info("Using principal = " + principal + " and keytab = " + keytab); Subject sub = SecureClientLogin.loginUserFromKeytab(principal, keytab, nameRules); Subject.doAs(sub, new PrivilegedAction<Void>() { @Override public Void run() { try { buildGroupList(); buildUserList(); buildUserGroupLinkList(); rebuildUserGroupMap(); } catch (Exception e) { LOG.error("Failed to build Group List : ", e); } return null; } }); } catch (Exception e) { LOG.error("Failed to Authenticate Using given Principal and Keytab : ",e); } } else { buildGroupList(); buildUserList(); buildUserGroupLinkList(); rebuildUserGroupMap(); if (LOG.isDebugEnabled()) { this.print(); } } } private String getURL(String uri) { String ret = null; ret = policyMgrBaseUrl + (uri.startsWith("/") ? uri : ("/" + uri)); return ret; } private void rebuildUserGroupMap() { for(XUserInfo user : xuserList) { addUserToList(user); } for(XGroupInfo group : xgroupList) { addGroupToList(group); } for(XUserGroupInfo ug : xusergroupList) { addUserGroupToList(ug); } } private void addUserToList(XUserInfo aUserInfo) { if (! xuserList.contains(aUserInfo)) { xuserList.add(aUserInfo); } String userId = aUserInfo.getId(); if (userId != null) { userId2XUserInfoMap.put(userId, aUserInfo); } String userName = aUserInfo.getName(); if (userName != null) { userName2XUserInfoMap.put(userName, aUserInfo); } if (LOG.isDebugEnabled()) { LOG.debug("PolicyMgrUserGroupBuilder:addUserToList() xuserList.size() = " + xuserList.size()); } } private void addGroupToList(XGroupInfo aGroupInfo) { if (! xgroupList.contains(aGroupInfo) ) { xgroupList.add(aGroupInfo); } if (aGroupInfo.getName() != null) { groupName2XGroupInfoMap.put(aGroupInfo.getName(), aGroupInfo); } if (LOG.isDebugEnabled()) { LOG.debug("PolicyMgrUserGroupBuilder:addGroupToList() xgroupList.size() = " + xgroupList.size()); } } private void addUserGroupToList(XUserGroupInfo ugInfo) { String userId = ugInfo.getUserId(); if (userId != null) { XUserInfo user = userId2XUserInfoMap.get(userId); if (user != null) { List<String> groups = user.getGroups(); if (! groups.contains(ugInfo.getGroupName())) { groups.add(ugInfo.getGroupName()); } } } } private void addUserGroupInfoToList(XUserInfo userInfo, XGroupInfo groupInfo) { String userId = userInfo.getId(); if (userId != null) { XUserInfo user = userId2XUserInfoMap.get(userId); if (user != null) { List<String> groups = user.getGroups(); if (! groups.contains(groupInfo.getName())) { groups.add(groupInfo.getName()); } } } } private void delUserGroupFromList(XUserInfo userInfo, XGroupInfo groupInfo) { List<String> groups = userInfo.getGroups(); if (groups.contains(groupInfo.getName())) { groups.remove(groupInfo.getName()); } } private void print() { LOG.debug("Number of users read [" + xuserList.size() + "]"); for(XUserInfo user : xuserList) { LOG.debug("USER: " + user.getName()); for(String group : user.getGroups()) { LOG.debug("\tGROUP: " + group); } } } @Override public void addOrUpdateUser(String userName, List<String> groups) throws Throwable { XUserInfo user = userName2XUserInfoMap.get(userName); if (groups == null) { groups = new ArrayList<String>(); } if (user == null) { // Does not exists //noOfNewUsers++; newUserList.add(userName); for (String group : groups) { if (groupName2XGroupInfoMap.containsKey(group) && !newGroupList.contains(group)) { modifiedGroupList.add(group); } else { //LOG.info("Adding new group " + group + " for user = " + userName); newGroupList.add(group); } } LOG.debug("INFO: addPMAccount(" + userName + ")" ); if (! isMockRun) { if (addMUser(userName) == null) { String msg = "Failed to add portal user"; LOG.error(msg); throw new Exception(msg); } } //* Build the user group info object and do the rest call if ( ! isMockRun ) { // If the rest call to ranger admin fails, // propagate the failure to the caller for retry in next sync cycle. if (addUserGroupInfo(userName,groups) == null ) { String msg = "Failed to add addorUpdate user group info"; LOG.error(msg); throw new Exception(msg); } } } else { // Validate group memberships List<String> oldGroups = user.getGroups(); List<String> addGroups = new ArrayList<String>(); List<String> delGroups = new ArrayList<String>(); List<String> updateGroups = new ArrayList<String>(); Set<String> cumulativeGroups = new HashSet<>(); XGroupInfo tempXGroupInfo=null; for(String group : groups) { if (! oldGroups.contains(group)) { addGroups.add(group); if (!groupName2XGroupInfoMap.containsKey(group)) { newGroupList.add(group); } else { modifiedGroupList.add(group); } }else{ tempXGroupInfo=groupName2XGroupInfoMap.get(group); if(tempXGroupInfo!=null && ! GROUP_SOURCE_EXTERNAL.equals(tempXGroupInfo.getGroupSource())){ updateGroups.add(group); } } } for(String group : oldGroups) { if (! groups.contains(group) ) { delGroups.add(group); } } for(String g : addGroups) { if (LOG.isDebugEnabled()) { LOG.debug("INFO: addPMXAGroupToUser(" + userName + "," + g + ")"); } } for(String g : delGroups) { if (LOG.isDebugEnabled()) { LOG.debug("INFO: delPMXAGroupFromUser(" + userName + "," + g + ")"); } } for(String g : updateGroups) { if (LOG.isDebugEnabled()) { LOG.debug("INFO: updatePMXAGroupToUser(" + userName + "," + g + ")"); } } if (isMockRun) { if (LOG.isDebugEnabled()) { LOG.debug("PolicyMgrUserGroupBuilder.addOrUpdateUser(): Mock Run enabled and hence not sending updates to Ranger admin!"); } return; } if (!delGroups.isEmpty()) { delXUserGroupInfo(user, delGroups); //Remove groups from user mapping user.deleteGroups(delGroups); if (LOG.isDebugEnabled()) { LOG.debug("PolicyMgrUserGroupBuilder.addUserGroupInfo(): groups for " + userName + " after delete = " + user.getGroups()); } } if (!delGroups.isEmpty() || !addGroups.isEmpty() || !updateGroups.isEmpty()) { cumulativeGroups = new HashSet<>(user.getGroups()); cumulativeGroups.addAll(addGroups); cumulativeGroups.addAll(updateGroups); if (LOG.isDebugEnabled()) { LOG.debug("PolicyMgrUserGroupBuilder.addUserGroupInfo(): cumulative groups for " + userName + " = " + cumulativeGroups); } UserGroupInfo ugInfo = new UserGroupInfo(); XUserInfo obj = addXUserInfo(userName); Set<String> userRoleList = new HashSet<>(); if (userMap.containsKey(userName)) { // Add the user role that is defined in user role assignments userRoleList.add(userMap.get(userName)); } for (String group : cumulativeGroups) { String value = groupMap.get(group); if (value != null) { userRoleList.add(value); } } if (!userRoleList.isEmpty()) { obj.setUserRoleList(new ArrayList<>(userRoleList)); } if (LOG.isDebugEnabled()) { LOG.debug("PolicyMgrUserGroupBuilder.addUserGroupInfo() user role list for " + userName + " = " + obj.getUserRoleList()); } ugInfo.setXuserInfo(obj); ugInfo.setXgroupInfo(getXGroupInfoList(new ArrayList<>(cumulativeGroups))); try { // If the rest call to ranger admin fails, // propagate the failure to the caller for retry in next // sync cycle. if (addUserGroupInfo(ugInfo) == null) { String msg = "Failed to add user group info"; LOG.error(msg); throw new Exception(msg); } } catch (Throwable t) { LOG.error("PolicyMgrUserGroupBuilder.addUserGroupInfo failed with exception: " + t.getMessage() + ", for user-group entry: " + ugInfo); } } if (isStartupFlag) { UserGroupInfo ugInfo = new UserGroupInfo(); XUserInfo obj = addXUserInfo(userName); if (obj != null && updateGroups.isEmpty() && addGroups.isEmpty() && delGroups.isEmpty()) { Set<String> userRoleList = new HashSet<>(); if (userMap.containsKey(userName)) { // Add the user role that is defined in user role assignments userRoleList.add(userMap.get(userName)); } for (String group : groups) { String value = groupMap.get(group); if (value != null) { userRoleList.add(value); } } obj.setUserRoleList(new ArrayList<>(userRoleList)); ugInfo.setXuserInfo(obj); ugInfo.setXgroupInfo(getXGroupInfoList(groups)); try { // If the rest call to ranger admin fails, // propagate the failure to the caller for retry in next // sync cycle. if (addUserGroupInfo(ugInfo) == null) { String msg = "Failed to add user group info"; LOG.error(msg); throw new Exception(msg); } } catch (Throwable t) { LOG.error("PolicyMgrUserGroupBuilder.addUserGroupInfo failed with exception: " + t.getMessage() + ", for user-group entry: " + ugInfo); } } modifiedGroupList.addAll(oldGroups); if (LOG.isDebugEnabled()) { LOG.debug("Adding user to modified user list: " + userName + ": " + oldGroups); } modifiedUserList.add(userName); } else { if (!addGroups.isEmpty() || !delGroups.isEmpty() || !updateGroups.isEmpty()) { modifiedUserList.add(userName); } modifiedGroupList.addAll(updateGroups); modifiedGroupList.addAll(delGroups); } } } private void buildGroupList() { if (LOG.isDebugEnabled()) { LOG.debug("==> PolicyMgrUserGroupBuilder.buildGroupList()"); } Client c = getClient(); int totalCount = 100; int retrievedCount = 0; while (retrievedCount < totalCount) { String response = null; Gson gson = new GsonBuilder().create(); if (isRangerCookieEnabled) { response = cookieBasedGetEntity(PM_GROUP_LIST_URI, retrievedCount); } else { WebResource r = c.resource(getURL(PM_GROUP_LIST_URI)).queryParam("pageSize", recordsToPullPerCall) .queryParam("startIndex", String.valueOf(retrievedCount)); response = r.accept(MediaType.APPLICATION_JSON_TYPE).get(String.class); } LOG.debug("RESPONSE: [" + response + "]"); GetXGroupListResponse groupList = gson.fromJson(response, GetXGroupListResponse.class); totalCount = groupList.getTotalCount(); if (groupList.getXgroupInfoList() != null) { xgroupList.addAll(groupList.getXgroupInfoList()); retrievedCount = xgroupList.size(); for (XGroupInfo g : groupList.getXgroupInfoList()) { LOG.debug("GROUP: Id:" + g.getId() + ", Name: " + g.getName() + ", Description: " + g.getDescription()); } } } if (LOG.isDebugEnabled()) { LOG.debug("<== PolicyMgrUserGroupBuilder.buildGroupList()"); } } private void buildUserList() { if (LOG.isDebugEnabled()) { LOG.debug("==> PolicyMgrUserGroupBuilder.buildUserList()"); } Client c = getClient(); int totalCount = 100; int retrievedCount = 0; while (retrievedCount < totalCount) { String response = null; Gson gson = new GsonBuilder().create(); if (isRangerCookieEnabled) { response = cookieBasedGetEntity(PM_USER_LIST_URI, retrievedCount); } else { WebResource r = c.resource(getURL(PM_USER_LIST_URI)).queryParam("pageSize", recordsToPullPerCall) .queryParam("startIndex", String.valueOf(retrievedCount)); response = r.accept(MediaType.APPLICATION_JSON_TYPE).get(String.class); } LOG.debug("RESPONSE: [" + response + "]"); GetXUserListResponse userList = gson.fromJson(response, GetXUserListResponse.class); totalCount = userList.getTotalCount(); if (userList.getXuserInfoList() != null) { xuserList.addAll(userList.getXuserInfoList()); retrievedCount = xuserList.size(); for (XUserInfo u : userList.getXuserInfoList()) { LOG.debug("USER: Id:" + u.getId() + ", Name: " + u.getName() + ", Description: " + u.getDescription()); } } } if (LOG.isDebugEnabled()) { LOG.debug("<== PolicyMgrUserGroupBuilder.buildUserList()"); } } private void buildUserGroupLinkList() { if (LOG.isDebugEnabled()) { LOG.debug("==> PolicyMgrUserGroupBuilder.buildUserGroupLinkList()"); } Client c = getClient(); int totalCount = 100; int retrievedCount = 0; while (retrievedCount < totalCount) { String response = null; Gson gson = new GsonBuilder().create(); if (isRangerCookieEnabled) { response = cookieBasedGetEntity(PM_USER_GROUP_MAP_LIST_URI, retrievedCount); } else { WebResource r = c.resource(getURL(PM_USER_GROUP_MAP_LIST_URI)) .queryParam("pageSize", recordsToPullPerCall) .queryParam("startIndex", String.valueOf(retrievedCount)); response = r.accept(MediaType.APPLICATION_JSON_TYPE).get(String.class); } LOG.debug("RESPONSE: [" + response + "]"); GetXUserGroupListResponse usergroupList = gson.fromJson(response, GetXUserGroupListResponse.class); totalCount = usergroupList.getTotalCount(); if (usergroupList.getXusergroupInfoList() != null) { xusergroupList.addAll(usergroupList.getXusergroupInfoList()); retrievedCount = xusergroupList.size(); for (XUserGroupInfo ug : usergroupList.getXusergroupInfoList()) { LOG.debug("USER_GROUP: UserId:" + ug.getUserId() + ", Name: " + ug.getGroupName()); } } } if (LOG.isDebugEnabled()) { LOG.debug("<== PolicyMgrUserGroupBuilder.buildUserGroupLinkList()"); } } private UserGroupInfo addUserGroupInfo(String userName, List<String> groups){ if(LOG.isDebugEnabled()) { LOG.debug("==> PolicyMgrUserGroupBuilder.addUserGroupInfo " + userName + " and groups"); } UserGroupInfo ret = null; XUserInfo user = null; LOG.debug("INFO: addPMXAUser(" + userName + ")" ); if (! isMockRun) { user = addXUserInfo(userName); if (!groups.isEmpty() && user != null) { for (String group : groups) { String value = groupMap.get(group); if (value != null) { List<String> userRoleList = new ArrayList<String>(); userRoleList.add(value); if (userMap.containsKey(user.getName())) { List<String> userRole = new ArrayList<String>(); userRole.add(userMap.get(user.getName())); user.setUserRoleList(userRole); } else { user.setUserRoleList(userRoleList); } } } } usergroupInfo.setXuserInfo(user); } for(String g : groups) { LOG.debug("INFO: addPMXAGroupToUser(" + userName + "," + g + ")" ); } if (! isMockRun ) { addXUserGroupInfo(user, groups); } if (authenticationType != null && AUTH_KERBEROS.equalsIgnoreCase(authenticationType) && SecureClientLogin.isKerberosCredentialExists(principal, keytab)){ try { Subject sub = SecureClientLogin.loginUserFromKeytab(principal, keytab, nameRules); final UserGroupInfo result = ret; ret = Subject.doAs(sub, new PrivilegedAction<UserGroupInfo>() { @Override public UserGroupInfo run() { try { return getUsergroupInfo(result); } catch (Exception e) { LOG.error("Failed to add User Group Info : ", e); } return null; } }); return ret; } catch (Exception e) { LOG.error("Failed to Authenticate Using given Principal and Keytab : " , e); } return null; }else{ return getUsergroupInfo(ret); } } private UserGroupInfo getUsergroupInfo(UserGroupInfo ret) { if(LOG.isDebugEnabled()){ LOG.debug("==> PolicyMgrUserGroupBuilder.getUsergroupInfo(UserGroupInfo ret)"); } String response = null; Gson gson = new GsonBuilder().create(); String jsonString = gson.toJson(usergroupInfo); if (LOG.isDebugEnabled()) { LOG.debug("USER GROUP MAPPING" + jsonString); } if(isRangerCookieEnabled){ response = cookieBasedUploadEntity(jsonString,PM_ADD_USER_GROUP_INFO_URI); } else{ Client c = getClient(); WebResource r = c.resource(getURL(PM_ADD_USER_GROUP_INFO_URI)); try{ response = r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).post(String.class, jsonString); } catch(Throwable t){ LOG.error("Failed to communicate Ranger Admin : ", t); } } if ( LOG.isDebugEnabled() ) { LOG.debug("RESPONSE: [" + response + "]"); } ret = gson.fromJson(response, UserGroupInfo.class); if ( ret != null) { XUserInfo xUserInfo = ret.getXuserInfo(); addUserToList(xUserInfo); for(XGroupInfo xGroupInfo : ret.getXgroupInfo()) { addGroupToList(xGroupInfo); addUserGroupInfoToList(xUserInfo,xGroupInfo); } } if(LOG.isDebugEnabled()){ LOG.debug("<== PolicyMgrUserGroupBuilder.getUsergroupInfo (UserGroupInfo ret)"); } return ret; } private UserGroupInfo getUserGroupInfo(UserGroupInfo usergroupInfo) { UserGroupInfo ret = null; if(LOG.isDebugEnabled()){ LOG.debug("==> PolicyMgrUserGroupBuilder.getUsergroupInfo(UserGroupInfo ret, UserGroupInfo usergroupInfo)"); } String response = null; Gson gson = new GsonBuilder().create(); String jsonString = gson.toJson(usergroupInfo); if (LOG.isDebugEnabled()) { LOG.debug("USER GROUP MAPPING" + jsonString); } if(isRangerCookieEnabled){ response = cookieBasedUploadEntity(jsonString,PM_ADD_USER_GROUP_INFO_URI); } else{ Client c = getClient(); WebResource r = c.resource(getURL(PM_ADD_USER_GROUP_INFO_URI)); try{ response=r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).post(String.class, jsonString); }catch(Throwable t){ LOG.error("Failed to communicate Ranger Admin : ", t); } } if (LOG.isDebugEnabled()) { LOG.debug("RESPONSE: [" + response + "]"); } ret = gson.fromJson(response, UserGroupInfo.class); if ( ret != null) { XUserInfo xUserInfo = ret.getXuserInfo(); addUserToList(xUserInfo); for (XGroupInfo xGroupInfo : ret.getXgroupInfo()) { addGroupToList(xGroupInfo); addUserGroupInfoToList(xUserInfo, xGroupInfo); } } if(LOG.isDebugEnabled()){ LOG.debug("<== PolicyMgrUserGroupBuilder.getUsergroupInfo(UserGroupInfo ret, UserGroupInfo usergroupInfo)"); } return ret; } private String tryUploadEntityWithCookie(String jsonString, String apiURL) { if (LOG.isDebugEnabled()) { LOG.debug("==> PolicyMgrUserGroupBuilder.tryUploadEntityWithCookie()"); } String response = null; ClientResponse clientResp = null; WebResource webResource = createWebResourceForCookieAuth(apiURL); WebResource.Builder br = webResource.getRequestBuilder().cookie(sessionId); try{ clientResp=br.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).post(ClientResponse.class, jsonString); } catch(Throwable t){ LOG.error("Failed to communicate Ranger Admin : ", t); } if (clientResp != null) { if (!(clientResp.toString().contains(apiURL))) { clientResp.setStatus(HttpServletResponse.SC_NOT_FOUND); sessionId = null; isValidRangerCookie = false; } else if (clientResp.getStatus() == HttpServletResponse.SC_UNAUTHORIZED) { sessionId = null; isValidRangerCookie = false; } else if (clientResp.getStatus() == HttpServletResponse.SC_NO_CONTENT || clientResp.getStatus() == HttpServletResponse.SC_OK) { cookieList = clientResp.getCookies(); for (NewCookie cookie : cookieList) { if (cookie.getName().equalsIgnoreCase(RANGER_ADMIN_COOKIE_NAME)) { sessionId = cookie.toCookie(); isValidRangerCookie = true; break; } } } if (clientResp.getStatus() != HttpServletResponse.SC_OK && clientResp.getStatus() != HttpServletResponse.SC_NO_CONTENT && clientResp.getStatus() != HttpServletResponse.SC_BAD_REQUEST) { sessionId = null; isValidRangerCookie = false; } clientResp.bufferEntity(); response = clientResp.getEntity(String.class); } if (LOG.isDebugEnabled()) { LOG.debug("<== PolicyMgrUserGroupBuilder.tryUploadEntityWithCookie()"); } return response; } private String tryUploadEntityWithCred(String jsonString,String apiURL){ if(LOG.isDebugEnabled()){ LOG.debug("==> PolicyMgrUserGroupBuilder.tryUploadEntityInfoWithCred()"); } String response = null; ClientResponse clientResp = null; Client c = getClient(); WebResource r = c.resource(getURL(apiURL)); if ( LOG.isDebugEnabled() ) { LOG.debug("USER GROUP MAPPING" + jsonString); } try{ clientResp=r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).post(ClientResponse.class, jsonString); } catch(Throwable t){ LOG.error("Failed to communicate Ranger Admin : ", t); } if (clientResp != null) { if (!(clientResp.toString().contains(apiURL))) { clientResp.setStatus(HttpServletResponse.SC_NOT_FOUND); } else if (clientResp.getStatus() == HttpServletResponse.SC_UNAUTHORIZED) { LOG.warn("Credentials response from ranger is 401."); } else if (clientResp.getStatus() == HttpServletResponse.SC_OK || clientResp.getStatus() == HttpServletResponse.SC_NO_CONTENT) { cookieList = clientResp.getCookies(); for (NewCookie cookie : cookieList) { if (cookie.getName().equalsIgnoreCase(RANGER_ADMIN_COOKIE_NAME)) { sessionId = cookie.toCookie(); isValidRangerCookie = true; LOG.info("valid cookie saved "); break; } } } if (clientResp.getStatus() != HttpServletResponse.SC_OK && clientResp.getStatus() != HttpServletResponse.SC_NO_CONTENT && clientResp.getStatus() != HttpServletResponse.SC_BAD_REQUEST) { sessionId = null; isValidRangerCookie = false; } clientResp.bufferEntity(); response = clientResp.getEntity(String.class); } if (LOG.isDebugEnabled()) { LOG.debug("<== PolicyMgrUserGroupBuilder.tryUploadEntityInfoWithCred()"); } return response; } private UserGroupInfo addUserGroupInfo(UserGroupInfo usergroupInfo){ if(LOG.isDebugEnabled()) { LOG.debug("==> PolicyMgrUserGroupBuilder.addUserGroupInfo"); } UserGroupInfo ret = null; if (authenticationType != null && AUTH_KERBEROS.equalsIgnoreCase(authenticationType) && SecureClientLogin.isKerberosCredentialExists(principal, keytab)) { try { Subject sub = SecureClientLogin.loginUserFromKeytab(principal, keytab, nameRules); final UserGroupInfo ugInfo = usergroupInfo; ret = Subject.doAs(sub, new PrivilegedAction<UserGroupInfo>() { @Override public UserGroupInfo run() { try { return getUserGroupInfo(ugInfo); } catch (Exception e) { LOG.error("Failed to add User Group Info : ", e); } return null; } }); return ret; } catch (Exception e) { LOG.error("Failed to Authenticate Using given Principal and Keytab : ",e); } } else { try { ret = getUserGroupInfo(usergroupInfo); } catch (Throwable t) { LOG.error("Failed to add User Group Info : ", t); } } if (LOG.isDebugEnabled()) { LOG.debug("<== PolicyMgrUserGroupBuilder.addUserGroupInfo"); } return ret; } private XUserInfo addXUserInfo(String aUserName) { XUserInfo xuserInfo = new XUserInfo(); xuserInfo.setName(aUserName); xuserInfo.setDescription(aUserName + " - add from Unix box"); List<String> userRole = new ArrayList<>(); userRole.add("ROLE_USER"); xuserInfo.setUserRoleList(userRole); usergroupInfo.setXuserInfo(xuserInfo); return xuserInfo; } private XGroupInfo addXGroupInfo(String aGroupName) { XGroupInfo addGroup = new XGroupInfo(); addGroup.setName(aGroupName); addGroup.setDescription(aGroupName + " - add from Unix box"); addGroup.setGroupType("1"); addGroup.setGroupSource(GROUP_SOURCE_EXTERNAL); return addGroup; } private void addXUserGroupInfo(XUserInfo aUserInfo, List<String> aGroupList) { List<XGroupInfo> xGroupInfoList = new ArrayList<XGroupInfo>(); for(String groupName : aGroupList) { XGroupInfo group = groupName2XGroupInfoMap.get(groupName); if (group == null) { group = addXGroupInfo(groupName); } xGroupInfoList.add(group); addXUserGroupInfo(aUserInfo, group); } usergroupInfo.setXgroupInfo(xGroupInfoList); } private List<XGroupInfo> getXGroupInfoList(List<String> aGroupList) { List<XGroupInfo> xGroupInfoList = new ArrayList<XGroupInfo>(); for(String groupName : aGroupList) { XGroupInfo group = groupName2XGroupInfoMap.get(groupName); if (group == null) { group = addXGroupInfo(groupName); }else if(!GROUP_SOURCE_EXTERNAL.equals(group.getGroupSource())){ group.setGroupSource(GROUP_SOURCE_EXTERNAL); } xGroupInfoList.add(group); } return xGroupInfoList; } private XUserGroupInfo addXUserGroupInfo(XUserInfo aUserInfo, XGroupInfo aGroupInfo) { XUserGroupInfo ugInfo = new XUserGroupInfo(); ugInfo.setUserId(aUserInfo.getId()); ugInfo.setGroupName(aGroupInfo.getName()); // ugInfo.setParentGroupId("1"); return ugInfo; } private void delXUserGroupInfo(final XUserInfo aUserInfo, List<String> aGroupList) { for(String groupName : aGroupList) { final XGroupInfo group = groupName2XGroupInfoMap.get(groupName); if (group != null) { if (authenticationType != null && AUTH_KERBEROS.equalsIgnoreCase(authenticationType) && SecureClientLogin.isKerberosCredentialExists(principal, keytab)) { try { LOG.debug("Using principal = " + principal + " and keytab = " + keytab); Subject sub = SecureClientLogin.loginUserFromKeytab(principal, keytab, nameRules); Subject.doAs(sub, new PrivilegedAction<Void>() { @Override public Void run() { try { delXUserGroupInfo(aUserInfo, group); } catch (Exception e) { LOG.error("Failed to build Group List : ", e); } return null; } }); } catch (Exception e) { LOG.error("Failed to Authenticate Using given Principal and Keytab : ",e); } } else { delXUserGroupInfo(aUserInfo, group); } } } } private void delXUserGroupInfo(XUserInfo aUserInfo, XGroupInfo aGroupInfo) { if (LOG.isDebugEnabled()) { LOG.debug("==> PolicyMgrUserGroupBuilder.delXUserGroupInfo()"); } String groupName = aGroupInfo.getName(); String userName = aUserInfo.getName(); try { ClientResponse response = null; String uri = PM_DEL_USER_GROUP_LINK_URI.replaceAll(Pattern.quote("${groupName}"), URLEncoderUtil.encodeURIParam(groupName)).replaceAll(Pattern.quote("${userName}"), URLEncoderUtil.encodeURIParam(userName)); if (isRangerCookieEnabled) { if (sessionId != null && isValidRangerCookie) { WebResource webResource = createWebResourceForCookieAuth(uri); WebResource.Builder br = webResource.getRequestBuilder().cookie(sessionId); response = br.delete(ClientResponse.class); if (response != null) { if (!(response.toString().contains(uri))) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); sessionId = null; isValidRangerCookie = false; } else if (response.getStatus() == HttpServletResponse.SC_UNAUTHORIZED) { LOG.warn("response from ranger is 401 unauthorized"); sessionId = null; isValidRangerCookie = false; } else if (response.getStatus() == HttpServletResponse.SC_NO_CONTENT || response.getStatus() == HttpServletResponse.SC_OK) { cookieList = response.getCookies(); for (NewCookie cookie : cookieList) { if (cookie.getName().equalsIgnoreCase(RANGER_ADMIN_COOKIE_NAME)) { sessionId = cookie.toCookie(); isValidRangerCookie = true; break; } } } if (response.getStatus() != HttpServletResponse.SC_OK && response.getStatus() != HttpServletResponse.SC_NO_CONTENT && response.getStatus() != HttpServletResponse.SC_BAD_REQUEST) { sessionId = null; isValidRangerCookie = false; } } } else { Client c = getClient(); WebResource r = c.resource(getURL(uri)); response = r.delete(ClientResponse.class); if (response != null) { if (!(response.toString().contains(uri))) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } else if (response.getStatus() == HttpServletResponse.SC_UNAUTHORIZED) { LOG.warn("Credentials response from ranger is 401."); } else if (response.getStatus() == HttpServletResponse.SC_OK || response.getStatus() == HttpServletResponse.SC_NO_CONTENT) { cookieList = response.getCookies(); for (NewCookie cookie : cookieList) { if (cookie.getName().equalsIgnoreCase(RANGER_ADMIN_COOKIE_NAME)) { sessionId = cookie.toCookie(); isValidRangerCookie = true; LOG.info("valid cookie saved "); break; } } } if (response.getStatus() != HttpServletResponse.SC_OK && response.getStatus() != HttpServletResponse.SC_NO_CONTENT && response.getStatus() != HttpServletResponse.SC_BAD_REQUEST) { sessionId = null; isValidRangerCookie = false; } } } } else { Client c = getClient(); WebResource r = c.resource(getURL(uri)); response = r.delete(ClientResponse.class); } if ( LOG.isDebugEnabled() ) { LOG.debug("RESPONSE: [" + response.toString() + "]"); } if (response.getStatus() == 200) { delUserGroupFromList(aUserInfo, aGroupInfo); } } catch (Exception e) { LOG.warn( "ERROR: Unable to delete GROUP: " + groupName + " from USER:" + userName , e); } if (LOG.isDebugEnabled()) { LOG.debug("<== PolicyMgrUserGroupBuilder.delXUserGroupInfo()"); } } private MUserInfo addMUser(String aUserName) { MUserInfo ret = null; MUserInfo userInfo = new MUserInfo(); userInfo.setLoginId(aUserName); userInfo.setFirstName(aUserName); userInfo.setLastName(aUserName); String str[] = new String[1]; if (userMap.containsKey(aUserName)) { str[0] = userMap.get(aUserName); } userInfo.setUserRoleList(str); if (authenticationType != null && AUTH_KERBEROS.equalsIgnoreCase(authenticationType) && SecureClientLogin.isKerberosCredentialExists(principal, keytab)) { try { Subject sub = SecureClientLogin.loginUserFromKeytab(principal, keytab, nameRules); final MUserInfo result = ret; final MUserInfo userInfoFinal = userInfo; ret = Subject.doAs(sub, new PrivilegedAction<MUserInfo>() { @Override public MUserInfo run() { try { return getMUser(userInfoFinal, result); } catch (Exception e) { LOG.error("Failed to add User : ", e); } return null; } }); return ret; } catch (Exception e) { LOG.error("Failed to Authenticate Using given Principal and Keytab : " , e); } return null; } else { return getMUser(userInfo, ret); } } private MUserInfo getMUser(MUserInfo userInfo, MUserInfo ret) { if(LOG.isDebugEnabled()){ LOG.debug("==> PolicyMgrUserGroupBuilder.getMUser()"); } String response = null; Gson gson = new GsonBuilder().create(); String jsonString = gson.toJson(userInfo); if (isRangerCookieEnabled) { response = cookieBasedUploadEntity(jsonString, PM_ADD_LOGIN_USER_URI); } else { Client c = getClient(); WebResource r = c.resource(getURL(PM_ADD_LOGIN_USER_URI)); response = r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE) .post(String.class, jsonString); } if (LOG.isDebugEnabled()) { LOG.debug("RESPONSE[" + response + "]"); } ret = gson.fromJson(response, MUserInfo.class); if (LOG.isDebugEnabled()) { LOG.debug("MUser Creation successful " + ret); LOG.debug("<== PolicyMgrUserGroupBuilder.getMUser()"); } return ret; } private String cookieBasedUploadEntity(String jsonString, String apiURL ) { if (LOG.isDebugEnabled()) { LOG.debug("==> PolicyMgrUserGroupBuilder.cookieBasedUploadEntity()"); } String response = null; if (sessionId != null && isValidRangerCookie) { response = tryUploadEntityWithCookie(jsonString,apiURL); } else{ response = tryUploadEntityWithCred(jsonString,apiURL); } if (LOG.isDebugEnabled()) { LOG.debug("<== PolicyMgrUserGroupBuilder.cookieBasedUploadEntity()"); } return response; } private String cookieBasedGetEntity(String apiURL ,int retrievedCount) { if (LOG.isDebugEnabled()) { LOG.debug("==> PolicyMgrUserGroupBuilder.cookieBasedGetEntity()"); } String response = null; if (sessionId != null && isValidRangerCookie) { response = tryGetEntityWithCookie(apiURL,retrievedCount); } else{ response = tryGetEntityWithCred(apiURL,retrievedCount); } if (LOG.isDebugEnabled()) { LOG.debug("<== PolicyMgrUserGroupBuilder.cookieBasedGetEntity()"); } return response; } private String tryGetEntityWithCred(String apiURL, int retrievedCount) { if(LOG.isDebugEnabled()){ LOG.debug("==> PolicyMgrUserGroupBuilder.tryGetEntityWithCred()"); } String response = null; ClientResponse clientResp = null; Client c = getClient(); WebResource r = c.resource(getURL(apiURL)) .queryParam("pageSize", recordsToPullPerCall) .queryParam("startIndex", String.valueOf(retrievedCount)); try{ clientResp=r.accept(MediaType.APPLICATION_JSON_TYPE).get(ClientResponse.class); } catch(Throwable t){ LOG.error("Failed to communicate Ranger Admin : ", t); } if (clientResp != null) { if (!(clientResp.toString().contains(apiURL))) { clientResp.setStatus(HttpServletResponse.SC_NOT_FOUND); } else if (clientResp.getStatus() == HttpServletResponse.SC_UNAUTHORIZED) { LOG.warn("Credentials response from ranger is 401."); } else if (clientResp.getStatus() == HttpServletResponse.SC_OK || clientResp.getStatus() == HttpServletResponse.SC_NO_CONTENT) { cookieList = clientResp.getCookies(); for (NewCookie cookie : cookieList) { if (cookie.getName().equalsIgnoreCase(RANGER_ADMIN_COOKIE_NAME)) { sessionId = cookie.toCookie(); isValidRangerCookie = true; LOG.info("valid cookie saved "); break; } } } if (clientResp.getStatus() != HttpServletResponse.SC_OK && clientResp.getStatus() != HttpServletResponse.SC_NO_CONTENT && clientResp.getStatus() != HttpServletResponse.SC_BAD_REQUEST) { sessionId = null; isValidRangerCookie = false; } clientResp.bufferEntity(); response = clientResp.getEntity(String.class); } if (LOG.isDebugEnabled()) { LOG.debug("<== PolicyMgrUserGroupBuilder.tryGetEntityWithCred()"); } return response; } private String tryGetEntityWithCookie(String apiURL, int retrievedCount) { if (LOG.isDebugEnabled()) { LOG.debug("==> PolicyMgrUserGroupBuilder.tryGetEntityWithCookie()"); } String response = null; ClientResponse clientResp = null; WebResource webResource = createWebResourceForCookieAuth(apiURL).queryParam("pageSize", recordsToPullPerCall).queryParam("startIndex", String.valueOf(retrievedCount)); WebResource.Builder br = webResource.getRequestBuilder().cookie(sessionId); try{ clientResp=br.accept(MediaType.APPLICATION_JSON_TYPE).get(ClientResponse.class); } catch(Throwable t){ LOG.error("Failed to communicate Ranger Admin : ", t); } if (clientResp != null) { if (!(clientResp.toString().contains(apiURL))) { clientResp.setStatus(HttpServletResponse.SC_NOT_FOUND); sessionId = null; isValidRangerCookie = false; } else if (clientResp.getStatus() == HttpServletResponse.SC_UNAUTHORIZED) { sessionId = null; isValidRangerCookie = false; } else if (clientResp.getStatus() == HttpServletResponse.SC_NO_CONTENT || clientResp.getStatus() == HttpServletResponse.SC_OK) { cookieList = clientResp.getCookies(); for (NewCookie cookie : cookieList) { if (cookie.getName().equalsIgnoreCase(RANGER_ADMIN_COOKIE_NAME)) { sessionId = cookie.toCookie(); isValidRangerCookie = true; break; } } } if (clientResp.getStatus() != HttpServletResponse.SC_OK && clientResp.getStatus() != HttpServletResponse.SC_NO_CONTENT && clientResp.getStatus() != HttpServletResponse.SC_BAD_REQUEST) { sessionId = null; isValidRangerCookie = false; } clientResp.bufferEntity(); response = clientResp.getEntity(String.class); } if (LOG.isDebugEnabled()) { LOG.debug("<== PolicyMgrUserGroupBuilder.tryGetEntityWithCookie()"); } return response; } public Client getClient() { // result saves on access time when client is built at the time of the call Client result = client; if(result == null) { synchronized(this) { result = client; if(result == null) { client = result = buildClient(); } } } return result; } private Client buildClient() { Client ret = null; if (policyMgrBaseUrl.startsWith("https://")) { ClientConfig config = new DefaultClientConfig(); if (sslContext == null) { try { KeyManager[] kmList = null; TrustManager[] tmList = null; if (keyStoreFile != null && keyStoreFilepwd != null) { KeyStore keyStore = KeyStore.getInstance(keyStoreType); InputStream in = null; try { in = getFileInputStream(keyStoreFile); if (in == null) { LOG.error("Unable to obtain keystore from file [" + keyStoreFile + "]"); return ret; } keyStore.load(in, keyStoreFilepwd.toCharArray()); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, keyStoreFilepwd.toCharArray()); kmList = keyManagerFactory.getKeyManagers(); } finally { if (in != null) { in.close(); } } } if (trustStoreFile != null && trustStoreFilepwd != null) { KeyStore trustStore = KeyStore.getInstance(trustStoreType); InputStream in = null; try { in = getFileInputStream(trustStoreFile); if (in == null) { LOG.error("Unable to obtain keystore from file [" + trustStoreFile + "]"); return ret; } trustStore.load(in, trustStoreFilepwd.toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); tmList = trustManagerFactory.getTrustManagers(); } finally { if (in != null) { in.close(); } } } sslContext = SSLContext.getInstance("TLS"); sslContext.init(kmList, tmList, new SecureRandom()); hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { return session.getPeerHost().equals(urlHostName); } }; } catch(Throwable t) { throw new RuntimeException("Unable to create SSLConext for communication to policy manager", t); } } config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(hv, sslContext)); ret = Client.create(config); } else { ClientConfig cc = new DefaultClientConfig(); cc.getProperties().put(ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true); ret = Client.create(cc); } if(!(authenticationType != null && AUTH_KERBEROS.equalsIgnoreCase(authenticationType) && SecureClientLogin.isKerberosCredentialExists(principal, keytab))){ if(ret!=null){ String username = config.getPolicyMgrUserName(); String password = config.getPolicyMgrPassword(); if(username!=null && !username.trim().isEmpty() && password!=null && !password.trim().isEmpty()){ ret.addFilter(new HTTPBasicAuthFilter(username, password)); } } } return ret; } private WebResource createWebResourceForCookieAuth(String url) { Client cookieClient = getClient(); cookieClient.removeAllFilters(); WebResource ret = cookieClient.resource(getURL(url)); return ret; } private InputStream getFileInputStream(String path) throws FileNotFoundException { InputStream ret = null; File f = new File(path); if (f.exists()) { ret = new FileInputStream(f); } else { ret = PolicyMgrUserGroupBuilder.class.getResourceAsStream(path); if (ret == null) { if (! path.startsWith("/")) { ret = getClass().getResourceAsStream("/" + path); } } if (ret == null) { ret = ClassLoader.getSystemClassLoader().getResourceAsStream(path); if (ret == null) { if (! path.startsWith("/")) { ret = ClassLoader.getSystemResourceAsStream("/" + path); } } } } return ret; } @Override public void addOrUpdateGroup(String groupName) throws Throwable{ XGroupInfo group = groupName2XGroupInfoMap.get(groupName); if (group == null) { // Does not exists //* Build the group info object and do the rest call if ( ! isMockRun ) { group = addGroupInfo(groupName); if ( group != null) { addGroupToList(group); } else { String msg = "Failed to add addorUpdate group info"; LOG.error(msg); throw new Exception(msg); } } } } private XGroupInfo addGroupInfo(final String groupName){ XGroupInfo ret = null; XGroupInfo group = null; LOG.debug("INFO: addPMXAGroup(" + groupName + ")" ); if (! isMockRun) { group = addXGroupInfo(groupName); } if (authenticationType != null && AUTH_KERBEROS.equalsIgnoreCase(authenticationType) && SecureClientLogin.isKerberosCredentialExists(principal,keytab)) { try { LOG.info("Using principal = " + principal + " and keytab = " + keytab); Subject sub = SecureClientLogin.loginUserFromKeytab(principal, keytab, nameRules); final XGroupInfo groupInfo = group; ret = Subject.doAs(sub, new PrivilegedAction<XGroupInfo>() { @Override public XGroupInfo run() { try { return getAddedGroupInfo(groupInfo); } catch (Exception e) { LOG.error("Failed to build Group List : ", e); } return null; } }); return ret; } catch (Exception e) { LOG.error("Failed to Authenticate Using given Principal and Keytab : ", e); } return null; } else { return getAddedGroupInfo(group); } } private XGroupInfo getAddedGroupInfo(XGroupInfo group){ XGroupInfo ret = null; String response = null; Gson gson = new GsonBuilder().create(); String jsonString = gson.toJson(group); if(isRangerCookieEnabled){ response = cookieBasedUploadEntity(jsonString,PM_ADD_GROUP_URI); } else{ Client c = getClient(); WebResource r = c.resource(getURL(PM_ADD_GROUP_URI)); if (LOG.isDebugEnabled()) { LOG.debug("Group" + jsonString); } try{ response = r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).post(String.class, jsonString); } catch(Throwable t){ LOG.error("Failed to communicate Ranger Admin : ", t); } } if ( LOG.isDebugEnabled() ) { LOG.debug("RESPONSE: [" + response + "]"); } ret = gson.fromJson(response, XGroupInfo.class); return ret; } @Override public void addOrUpdateUser(String user) throws Throwable { // TODO Auto-generated method stub } @Override public void addOrUpdateGroup(String groupName, List<String> users) throws Throwable { if (users == null || users.isEmpty()) { if (groupName2XGroupInfoMap.containsKey(groupName)) { modifiedGroupList.add(groupName); } else { newGroupList.add(groupName); } } addOrUpdateGroup(groupName); } @Override public void postUserGroupAuditInfo(UgsyncAuditInfo ugsyncAuditInfo) throws Throwable { if (! isMockRun) { addUserGroupAuditInfo(ugsyncAuditInfo); } noOfNewUsers = 0; noOfNewGroups = 0; noOfModifiedUsers = 0; noOfModifiedGroups = 0; isStartupFlag = false; newUserList.clear(); modifiedUserList.clear(); newGroupList.clear(); modifiedGroupList.clear(); } private UgsyncAuditInfo addUserGroupAuditInfo(UgsyncAuditInfo auditInfo) { UgsyncAuditInfo ret = null; if (auditInfo == null) { LOG.error("Failed to generate user group audit info"); return ret; } noOfNewUsers = newUserList.size(); noOfModifiedUsers = modifiedUserList.size(); noOfNewGroups = newGroupList.size(); noOfModifiedGroups = modifiedGroupList.size(); auditInfo.setNoOfNewUsers(Integer.toUnsignedLong(noOfNewUsers)); auditInfo.setNoOfNewGroups(Integer.toUnsignedLong(noOfNewGroups)); auditInfo.setNoOfModifiedUsers(Integer.toUnsignedLong(noOfModifiedUsers)); auditInfo.setNoOfModifiedGroups(Integer.toUnsignedLong(noOfModifiedGroups)); auditInfo.setSessionId(""); LOG.debug("INFO: addAuditInfo(" + auditInfo.getNoOfNewUsers() + ", " + auditInfo.getNoOfNewGroups() + ", " + auditInfo.getNoOfModifiedUsers() + ", " + auditInfo.getNoOfModifiedGroups() + ", " + auditInfo.getSyncSource() + ")"); if (authenticationType != null && AUTH_KERBEROS.equalsIgnoreCase(authenticationType) && SecureClientLogin.isKerberosCredentialExists(principal, keytab)) { try { Subject sub = SecureClientLogin.loginUserFromKeytab(principal, keytab, nameRules); final UgsyncAuditInfo auditInfoFinal = auditInfo; ret = Subject.doAs(sub, new PrivilegedAction<UgsyncAuditInfo>() { @Override public UgsyncAuditInfo run() { try { return getUserGroupAuditInfo(auditInfoFinal); } catch (Exception e) { LOG.error("Failed to add User : ", e); } return null; } }); return ret; } catch (Exception e) { LOG.error("Failed to Authenticate Using given Principal and Keytab : " , e); } return ret; } else { return getUserGroupAuditInfo(auditInfo); } } private UgsyncAuditInfo getUserGroupAuditInfo(UgsyncAuditInfo userInfo) { if(LOG.isDebugEnabled()){ LOG.debug("==> PolicyMgrUserGroupBuilder.getUserGroupAuditInfo()"); } String response = null; Gson gson = new GsonBuilder().create(); String jsonString = gson.toJson(userInfo); if(isRangerCookieEnabled){ response = cookieBasedUploadEntity(jsonString, PM_AUDIT_INFO_URI); } else{ Client c = getClient(); WebResource r = c.resource(getURL(PM_AUDIT_INFO_URI)); try{ response = r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).post(String.class, jsonString); } catch(Throwable t){ LOG.error("Failed to communicate Ranger Admin : ", t); } } if (LOG.isDebugEnabled()) { LOG.debug("RESPONSE[" + response + "]"); } UgsyncAuditInfo ret = gson.fromJson(response, UgsyncAuditInfo.class); LOG.debug("AuditInfo Creation successful "); if(LOG.isDebugEnabled()){ LOG.debug("<== PolicyMgrUserGroupBuilder.getUserGroupAuditInfo()"); } return ret; } private void getRoleForUserGroups(String userGroupRolesData) { String roleDelimiter = config.getRoleDelimiter(); String userGroupDelimiter = config.getUserGroupDelimiter(); String userNameDelimiter = config.getUserGroupNameDelimiter(); if (roleDelimiter == null || roleDelimiter.isEmpty()) { roleDelimiter = "&"; } if (userGroupDelimiter == null || userGroupDelimiter.isEmpty()) { userGroupDelimiter = ":"; } if (userNameDelimiter == null || userNameDelimiter.isEmpty()) { userNameDelimiter = ","; } StringTokenizer str = new StringTokenizer(userGroupRolesData, roleDelimiter); int flag = 0; String userGroupCheck = null; String roleName = null; while (str.hasMoreTokens()) { flag = 0; String tokens = str.nextToken(); if (tokens != null && !tokens.isEmpty()) { StringTokenizer userGroupRoles = new StringTokenizer(tokens, userGroupDelimiter); if (userGroupRoles != null) { while (userGroupRoles.hasMoreElements()) { String userGroupRolesTokens = userGroupRoles .nextToken(); if (userGroupRolesTokens != null && !userGroupRolesTokens.isEmpty()) { flag++; switch (flag) { case 1: roleName = userGroupRolesTokens; break; case 2: userGroupCheck = userGroupRolesTokens; break; case 3: StringTokenizer userGroupNames = new StringTokenizer( userGroupRolesTokens, userNameDelimiter); if (userGroupNames != null) { while (userGroupNames.hasMoreElements()) { String userGroup = userGroupNames .nextToken(); if (userGroup != null && !userGroup.isEmpty()) { if (userGroupCheck.trim().equalsIgnoreCase("u")) { userMap.put(userGroup.trim(), roleName.trim()); } else if (userGroupCheck.trim().equalsIgnoreCase("g")) { groupMap.put(userGroup.trim(), roleName.trim()); } } } } break; default: userMap.clear(); groupMap.clear(); break; } } } } } } } }
ugsync/src/main/java/org/apache/ranger/unixusersync/process/PolicyMgrUserGroupBuilder.java
/* * 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.ranger.unixusersync.process; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.UnknownHostException; import java.security.KeyStore; import java.security.PrivilegedAction; import java.security.SecureRandom; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.regex.Pattern; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.security.auth.Subject; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.core.Cookie; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.NewCookie; import org.apache.hadoop.security.SecureClientLogin; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.ranger.plugin.util.URLEncoderUtil; import org.apache.ranger.unixusersync.config.UserGroupSyncConfig; import org.apache.ranger.unixusersync.model.GetXGroupListResponse; import org.apache.ranger.unixusersync.model.GetXUserGroupListResponse; import org.apache.ranger.unixusersync.model.GetXUserListResponse; import org.apache.ranger.unixusersync.model.MUserInfo; import org.apache.ranger.unixusersync.model.UgsyncAuditInfo; import org.apache.ranger.unixusersync.model.UserGroupInfo; import org.apache.ranger.unixusersync.model.XGroupInfo; import org.apache.ranger.unixusersync.model.XUserGroupInfo; import org.apache.ranger.unixusersync.model.XUserInfo; import org.apache.ranger.usergroupsync.UserGroupSink; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import com.sun.jersey.client.urlconnection.HTTPSProperties; public class PolicyMgrUserGroupBuilder implements UserGroupSink { private static final Logger LOG = Logger.getLogger(PolicyMgrUserGroupBuilder.class); private static final String AUTHENTICATION_TYPE = "hadoop.security.authentication"; private String AUTH_KERBEROS = "kerberos"; private static final String PRINCIPAL = "ranger.usersync.kerberos.principal"; private static final String KEYTAB = "ranger.usersync.kerberos.keytab"; private static final String NAME_RULE = "hadoop.security.auth_to_local"; public static final String PM_USER_LIST_URI = "/service/xusers/users/"; // GET private static final String PM_ADD_USER_GROUP_INFO_URI = "/service/xusers/users/userinfo"; // POST public static final String PM_GROUP_LIST_URI = "/service/xusers/groups/"; // GET private static final String PM_ADD_GROUP_URI = "/service/xusers/groups/"; // POST public static final String PM_USER_GROUP_MAP_LIST_URI = "/service/xusers/groupusers/"; // GET private static final String PM_DEL_USER_GROUP_LINK_URI = "/service/xusers/group/${groupName}/user/${userName}"; // DELETE private static final String PM_ADD_LOGIN_USER_URI = "/service/users/default"; // POST private static final String PM_AUDIT_INFO_URI = "/service/xusers/ugsync/auditinfo/"; // POST private static final String GROUP_SOURCE_EXTERNAL ="1"; private static final String RANGER_ADMIN_COOKIE_NAME = "RANGERADMINSESSIONID"; private static String LOCAL_HOSTNAME = "unknown"; private String recordsToPullPerCall = "1000"; private boolean isMockRun = false; private String policyMgrBaseUrl; private Cookie sessionId=null; private boolean isValidRangerCookie=false; List<NewCookie> cookieList=new ArrayList<>(); private UserGroupSyncConfig config = UserGroupSyncConfig.getInstance(); private UserGroupInfo usergroupInfo = new UserGroupInfo(); private List<XGroupInfo> xgroupList; private List<XUserInfo> xuserList; private List<XUserGroupInfo> xusergroupList; private HashMap<String,XUserInfo> userId2XUserInfoMap; private HashMap<String,XUserInfo> userName2XUserInfoMap; private HashMap<String,XGroupInfo> groupName2XGroupInfoMap; private String keyStoreFile = null; private String keyStoreFilepwd = null; private String trustStoreFile = null; private String trustStoreFilepwd = null; private String keyStoreType = null; private String trustStoreType = null; private HostnameVerifier hv = null; private SSLContext sslContext = null; private String authenticationType = null; String principal; String keytab; String nameRules; Map<String, String> userMap; Map<String, String> groupMap; private int noOfNewUsers; private int noOfNewGroups; private int noOfModifiedUsers; private int noOfModifiedGroups; private HashSet<String> newUserList = new HashSet<String>(); private HashSet<String> modifiedUserList = new HashSet<String>(); private HashSet<String> newGroupList = new HashSet<String>(); private HashSet<String> modifiedGroupList = new HashSet<String>(); private boolean isRangerCookieEnabled; boolean isStartupFlag = false; private volatile Client client; static { try { LOCAL_HOSTNAME = java.net.InetAddress.getLocalHost().getCanonicalHostName(); } catch (UnknownHostException e) { LOCAL_HOSTNAME = "unknown"; } } public static void main(String[] args) throws Throwable { PolicyMgrUserGroupBuilder ugbuilder = new PolicyMgrUserGroupBuilder(); ugbuilder.init(); } synchronized public void init() throws Throwable { xgroupList = new ArrayList<XGroupInfo>(); xuserList = new ArrayList<XUserInfo>(); xusergroupList = new ArrayList<XUserGroupInfo>(); userId2XUserInfoMap = new HashMap<String,XUserInfo>(); userName2XUserInfoMap = new HashMap<String,XUserInfo>(); groupName2XGroupInfoMap = new HashMap<String,XGroupInfo>(); userMap = new LinkedHashMap<String, String>(); groupMap = new LinkedHashMap<String, String>(); recordsToPullPerCall = config.getMaxRecordsPerAPICall(); policyMgrBaseUrl = config.getPolicyManagerBaseURL(); isMockRun = config.isMockRunEnabled(); noOfNewUsers = 0; noOfModifiedUsers = 0; noOfNewGroups = 0; noOfModifiedGroups = 0; isStartupFlag = true; isRangerCookieEnabled = config.isUserSyncRangerCookieEnabled(); if (isMockRun) { LOG.setLevel(Level.DEBUG); } sessionId=null; keyStoreFile = config.getSSLKeyStorePath(); keyStoreFilepwd = config.getSSLKeyStorePathPassword(); trustStoreFile = config.getSSLTrustStorePath(); trustStoreFilepwd = config.getSSLTrustStorePathPassword(); keyStoreType = KeyStore.getDefaultType(); trustStoreType = KeyStore.getDefaultType(); authenticationType = config.getProperty(AUTHENTICATION_TYPE,"simple"); try { principal = SecureClientLogin.getPrincipal(config.getProperty(PRINCIPAL,""), LOCAL_HOSTNAME); } catch (IOException ignored) { // do nothing } keytab = config.getProperty(KEYTAB,""); nameRules = config.getProperty(NAME_RULE,"DEFAULT"); String userGroupRoles = config.getGroupRoleRules(); if (userGroupRoles != null && !userGroupRoles.isEmpty()) { getRoleForUserGroups(userGroupRoles); } buildUserGroupInfo(); } private void buildUserGroupInfo() throws Throwable { if(authenticationType != null && AUTH_KERBEROS.equalsIgnoreCase(authenticationType) && SecureClientLogin.isKerberosCredentialExists(principal, keytab)){ if(LOG.isDebugEnabled()) { LOG.debug("==> Kerberos Environment : Principal is " + principal + " and Keytab is " + keytab); } } if (authenticationType != null && AUTH_KERBEROS.equalsIgnoreCase(authenticationType) && SecureClientLogin.isKerberosCredentialExists(principal, keytab)) { try { LOG.info("Using principal = " + principal + " and keytab = " + keytab); Subject sub = SecureClientLogin.loginUserFromKeytab(principal, keytab, nameRules); Subject.doAs(sub, new PrivilegedAction<Void>() { @Override public Void run() { try { buildGroupList(); buildUserList(); buildUserGroupLinkList(); rebuildUserGroupMap(); } catch (Exception e) { LOG.error("Failed to build Group List : ", e); } return null; } }); } catch (Exception e) { LOG.error("Failed to Authenticate Using given Principal and Keytab : ",e); } } else { buildGroupList(); buildUserList(); buildUserGroupLinkList(); rebuildUserGroupMap(); if (LOG.isDebugEnabled()) { this.print(); } } } private String getURL(String uri) { String ret = null; ret = policyMgrBaseUrl + (uri.startsWith("/") ? uri : ("/" + uri)); return ret; } private void rebuildUserGroupMap() { for(XUserInfo user : xuserList) { addUserToList(user); } for(XGroupInfo group : xgroupList) { addGroupToList(group); } for(XUserGroupInfo ug : xusergroupList) { addUserGroupToList(ug); } } private void addUserToList(XUserInfo aUserInfo) { if (! xuserList.contains(aUserInfo)) { xuserList.add(aUserInfo); } String userId = aUserInfo.getId(); if (userId != null) { userId2XUserInfoMap.put(userId, aUserInfo); } String userName = aUserInfo.getName(); if (userName != null) { userName2XUserInfoMap.put(userName, aUserInfo); } if (LOG.isDebugEnabled()) { LOG.debug("PolicyMgrUserGroupBuilder:addUserToList() xuserList.size() = " + xuserList.size()); } } private void addGroupToList(XGroupInfo aGroupInfo) { if (! xgroupList.contains(aGroupInfo) ) { xgroupList.add(aGroupInfo); } if (aGroupInfo.getName() != null) { groupName2XGroupInfoMap.put(aGroupInfo.getName(), aGroupInfo); } if (LOG.isDebugEnabled()) { LOG.debug("PolicyMgrUserGroupBuilder:addGroupToList() xgroupList.size() = " + xgroupList.size()); } } private void addUserGroupToList(XUserGroupInfo ugInfo) { String userId = ugInfo.getUserId(); if (userId != null) { XUserInfo user = userId2XUserInfoMap.get(userId); if (user != null) { List<String> groups = user.getGroups(); if (! groups.contains(ugInfo.getGroupName())) { groups.add(ugInfo.getGroupName()); } } } } private void addUserGroupInfoToList(XUserInfo userInfo, XGroupInfo groupInfo) { String userId = userInfo.getId(); if (userId != null) { XUserInfo user = userId2XUserInfoMap.get(userId); if (user != null) { List<String> groups = user.getGroups(); if (! groups.contains(groupInfo.getName())) { groups.add(groupInfo.getName()); } } } } private void delUserGroupFromList(XUserInfo userInfo, XGroupInfo groupInfo) { List<String> groups = userInfo.getGroups(); if (groups.contains(groupInfo.getName())) { groups.remove(groupInfo.getName()); } } private void print() { LOG.debug("Number of users read [" + xuserList.size() + "]"); for(XUserInfo user : xuserList) { LOG.debug("USER: " + user.getName()); for(String group : user.getGroups()) { LOG.debug("\tGROUP: " + group); } } } @Override public void addOrUpdateUser(String userName, List<String> groups) throws Throwable { UserGroupInfo ugInfo = new UserGroupInfo(); XUserInfo user = userName2XUserInfoMap.get(userName); if (groups == null) { groups = new ArrayList<String>(); } if (user == null) { // Does not exists //noOfNewUsers++; newUserList.add(userName); for (String group : groups) { if (groupName2XGroupInfoMap.containsKey(group) && !newGroupList.contains(group)) { modifiedGroupList.add(group); } else { //LOG.info("Adding new group " + group + " for user = " + userName); newGroupList.add(group); } } LOG.debug("INFO: addPMAccount(" + userName + ")" ); if (! isMockRun) { if (addMUser(userName) == null) { String msg = "Failed to add portal user"; LOG.error(msg); throw new Exception(msg); } } //* Build the user group info object and do the rest call if ( ! isMockRun ) { // If the rest call to ranger admin fails, // propagate the failure to the caller for retry in next sync cycle. if (addUserGroupInfo(userName,groups) == null ) { String msg = "Failed to add addorUpdate user group info"; LOG.error(msg); throw new Exception(msg); } } } else { // Validate group memberships List<String> oldGroups = user.getGroups(); List<String> addGroups = new ArrayList<String>(); List<String> delGroups = new ArrayList<String>(); List<String> updateGroups = new ArrayList<String>(); XGroupInfo tempXGroupInfo=null; for(String group : groups) { if (! oldGroups.contains(group)) { addGroups.add(group); if (!groupName2XGroupInfoMap.containsKey(group)) { newGroupList.add(group); } else { modifiedGroupList.add(group); } }else{ tempXGroupInfo=groupName2XGroupInfoMap.get(group); if(tempXGroupInfo!=null && ! GROUP_SOURCE_EXTERNAL.equals(tempXGroupInfo.getGroupSource())){ updateGroups.add(group); } } } for(String group : oldGroups) { if (! groups.contains(group) ) { delGroups.add(group); } } for(String g : addGroups) { if (LOG.isDebugEnabled()) { LOG.debug("INFO: addPMXAGroupToUser(" + userName + "," + g + ")"); } } for(String g : delGroups) { if (LOG.isDebugEnabled()) { LOG.debug("INFO: delPMXAGroupFromUser(" + userName + "," + g + ")"); } } for(String g : updateGroups) { if (LOG.isDebugEnabled()) { LOG.debug("INFO: updatePMXAGroupToUser(" + userName + "," + g + ")"); } } if (isMockRun) { return; } if (!addGroups.isEmpty()) { XUserInfo obj = addXUserInfo(userName); if (obj != null) { for (String group : addGroups) { String value = groupMap.get(group); if (value != null) { List<String> userRoleList = new ArrayList<String>(); userRoleList.add(value); if (userMap.containsKey(obj.getName())) { List<String> userRole = new ArrayList<String>(); userRole.add(userMap.get(obj.getName())); if (!obj.getUserRoleList().equals(userRole)) { obj.setUserRoleList(userRole); } } else if (!obj.getUserRoleList().equals(userRoleList)) { obj.setUserRoleList(userRoleList); } } } } ugInfo.setXuserInfo(obj); ugInfo.setXgroupInfo(getXGroupInfoList(addGroups)); try { // If the rest call to ranger admin fails, // propagate the failure to the caller for retry in next // sync cycle. if (addUserGroupInfo(ugInfo) == null) { String msg = "Failed to add user group info"; LOG.error(msg); throw new Exception(msg); } } catch (Throwable t) { LOG.error("PolicyMgrUserGroupBuilder.addUserGroupInfo failed for user-group entry: " + ugInfo.toString() + " with exception: ", t); } addXUserGroupInfo(user, addGroups); } if (!delGroups.isEmpty()) { if (LOG.isDebugEnabled()) { LOG.debug("PolicyMgrUserGroupBuilder.addUserGroupInfo() user role list for " + userName + " after delete = " + user.getUserRoleList()); } delXUserGroupInfo(user, delGroups); //Remove groups from user mapping userName2XUserInfoMap.get(userName).deleteGroups(delGroups); List<String> groupList = userName2XUserInfoMap.get(userName).getGroups(); if (LOG.isDebugEnabled()) { LOG.debug("PolicyMgrUserGroupBuilder.addUserGroupInfo() groups for " + userName + " after delete = " + groupList); } if (!groupList.isEmpty()) { XUserInfo obj = addXUserInfo(userName); if (obj != null) { for (String group : updateGroups) { String value = groupMap.get(group); if (value != null) { List<String> userRoleList = new ArrayList<String>(); userRoleList.add(value); if (userMap.containsKey(obj.getName())) { List<String> userRole = new ArrayList<String>(); userRole.add(userMap.get(obj.getName())); if (!obj.getUserRoleList().equals(userRole)) { obj.setUserRoleList(userRole); } } else if (!obj.getUserRoleList().equals( userRoleList)) { obj.setUserRoleList(userRoleList); } } } } ugInfo.setXuserInfo(obj); ugInfo.setXgroupInfo(getXGroupInfoList(groupList)); try { // If the rest call to ranger admin fails, // propagate the failure to the caller for retry in next // sync cycle. if (addUserGroupInfo(ugInfo) == null) { String msg = "Failed to add user group info"; LOG.error(msg); throw new Exception(msg); } } catch (Throwable t) { LOG.error("PolicyMgrUserGroupBuilder.addUserGroupInfo failed with exception: " + t.getMessage() + ", for user-group entry: " + ugInfo); } } } if (!updateGroups.isEmpty()) { XUserInfo obj = addXUserInfo(userName); if (obj != null) { for (String group : updateGroups) { String value = groupMap.get(group); if (value != null) { List<String> userRoleList = new ArrayList<String>(); userRoleList.add(value); if (userMap.containsKey(obj.getName())) { List<String> userRole = new ArrayList<String>(); userRole.add(userMap.get(obj.getName())); if (!obj.getUserRoleList().equals(userRole)) { obj.setUserRoleList(userRole); } } else if (!obj.getUserRoleList().equals( userRoleList)) { obj.setUserRoleList(userRoleList); } } } } ugInfo.setXuserInfo(obj); ugInfo.setXgroupInfo(getXGroupInfoList(updateGroups)); try { // If the rest call to ranger admin fails, // propagate the failure to the caller for retry in next // sync cycle. if (addUserGroupInfo(ugInfo) == null) { String msg = "Failed to add user group info"; LOG.error(msg); throw new Exception(msg); } } catch (Throwable t) { LOG.error("PolicyMgrUserGroupBuilder.addUserGroupInfo failed with exception: " + t.getMessage() + ", for user-group entry: " + ugInfo); } } if (isStartupFlag) { XUserInfo obj = addXUserInfo(userName); if (obj != null && updateGroups.isEmpty() && addGroups.isEmpty() && delGroups.isEmpty()) { for (String group : groups) { String value = groupMap.get(group); if (value != null) { List<String> userRoleList = new ArrayList<String>(); userRoleList.add(value); if (userMap.containsKey(obj.getName())) { List<String> userRole = new ArrayList<String>(); userRole.add(userMap.get(obj.getName())); if (!obj.getUserRoleList().equals(userRole)) { obj.setUserRoleList(userRole); } } else if (!obj.getUserRoleList().equals( userRoleList)) { obj.setUserRoleList(userRoleList); } } } ugInfo.setXuserInfo(obj); ugInfo.setXgroupInfo(getXGroupInfoList(groups)); try { // If the rest call to ranger admin fails, // propagate the failure to the caller for retry in next // sync cycle. if (addUserGroupInfo(ugInfo) == null) { String msg = "Failed to add user group info"; LOG.error(msg); throw new Exception(msg); } } catch (Throwable t) { LOG.error("PolicyMgrUserGroupBuilder.addUserGroupInfo failed with exception: " + t.getMessage() + ", for user-group entry: " + ugInfo); } } modifiedGroupList.addAll(oldGroups); if (LOG.isDebugEnabled()) { LOG.debug("Adding user to modified user list: " + userName + ": " + oldGroups); } modifiedUserList.add(userName); } else { if (!addGroups.isEmpty() || !delGroups.isEmpty() || !updateGroups.isEmpty()) { modifiedUserList.add(userName); } modifiedGroupList.addAll(updateGroups); modifiedGroupList.addAll(delGroups); } } } private void buildGroupList() { if (LOG.isDebugEnabled()) { LOG.debug("==> PolicyMgrUserGroupBuilder.buildGroupList()"); } Client c = getClient(); int totalCount = 100; int retrievedCount = 0; while (retrievedCount < totalCount) { String response = null; Gson gson = new GsonBuilder().create(); if (isRangerCookieEnabled) { response = cookieBasedGetEntity(PM_GROUP_LIST_URI, retrievedCount); } else { WebResource r = c.resource(getURL(PM_GROUP_LIST_URI)).queryParam("pageSize", recordsToPullPerCall) .queryParam("startIndex", String.valueOf(retrievedCount)); response = r.accept(MediaType.APPLICATION_JSON_TYPE).get(String.class); } LOG.debug("RESPONSE: [" + response + "]"); GetXGroupListResponse groupList = gson.fromJson(response, GetXGroupListResponse.class); totalCount = groupList.getTotalCount(); if (groupList.getXgroupInfoList() != null) { xgroupList.addAll(groupList.getXgroupInfoList()); retrievedCount = xgroupList.size(); for (XGroupInfo g : groupList.getXgroupInfoList()) { LOG.debug("GROUP: Id:" + g.getId() + ", Name: " + g.getName() + ", Description: " + g.getDescription()); } } } if (LOG.isDebugEnabled()) { LOG.debug("<== PolicyMgrUserGroupBuilder.buildGroupList()"); } } private void buildUserList() { if (LOG.isDebugEnabled()) { LOG.debug("==> PolicyMgrUserGroupBuilder.buildUserList()"); } Client c = getClient(); int totalCount = 100; int retrievedCount = 0; while (retrievedCount < totalCount) { String response = null; Gson gson = new GsonBuilder().create(); if (isRangerCookieEnabled) { response = cookieBasedGetEntity(PM_USER_LIST_URI, retrievedCount); } else { WebResource r = c.resource(getURL(PM_USER_LIST_URI)).queryParam("pageSize", recordsToPullPerCall) .queryParam("startIndex", String.valueOf(retrievedCount)); response = r.accept(MediaType.APPLICATION_JSON_TYPE).get(String.class); } LOG.debug("RESPONSE: [" + response + "]"); GetXUserListResponse userList = gson.fromJson(response, GetXUserListResponse.class); totalCount = userList.getTotalCount(); if (userList.getXuserInfoList() != null) { xuserList.addAll(userList.getXuserInfoList()); retrievedCount = xuserList.size(); for (XUserInfo u : userList.getXuserInfoList()) { LOG.debug("USER: Id:" + u.getId() + ", Name: " + u.getName() + ", Description: " + u.getDescription()); } } } if (LOG.isDebugEnabled()) { LOG.debug("<== PolicyMgrUserGroupBuilder.buildUserList()"); } } private void buildUserGroupLinkList() { if (LOG.isDebugEnabled()) { LOG.debug("==> PolicyMgrUserGroupBuilder.buildUserGroupLinkList()"); } Client c = getClient(); int totalCount = 100; int retrievedCount = 0; while (retrievedCount < totalCount) { String response = null; Gson gson = new GsonBuilder().create(); if (isRangerCookieEnabled) { response = cookieBasedGetEntity(PM_USER_GROUP_MAP_LIST_URI, retrievedCount); } else { WebResource r = c.resource(getURL(PM_USER_GROUP_MAP_LIST_URI)) .queryParam("pageSize", recordsToPullPerCall) .queryParam("startIndex", String.valueOf(retrievedCount)); response = r.accept(MediaType.APPLICATION_JSON_TYPE).get(String.class); } LOG.debug("RESPONSE: [" + response + "]"); GetXUserGroupListResponse usergroupList = gson.fromJson(response, GetXUserGroupListResponse.class); totalCount = usergroupList.getTotalCount(); if (usergroupList.getXusergroupInfoList() != null) { xusergroupList.addAll(usergroupList.getXusergroupInfoList()); retrievedCount = xusergroupList.size(); for (XUserGroupInfo ug : usergroupList.getXusergroupInfoList()) { LOG.debug("USER_GROUP: UserId:" + ug.getUserId() + ", Name: " + ug.getGroupName()); } } } if (LOG.isDebugEnabled()) { LOG.debug("<== PolicyMgrUserGroupBuilder.buildUserGroupLinkList()"); } } private UserGroupInfo addUserGroupInfo(String userName, List<String> groups){ if(LOG.isDebugEnabled()) { LOG.debug("==> PolicyMgrUserGroupBuilder.addUserGroupInfo " + userName + " and groups"); } UserGroupInfo ret = null; XUserInfo user = null; LOG.debug("INFO: addPMXAUser(" + userName + ")" ); if (! isMockRun) { user = addXUserInfo(userName); if (!groups.isEmpty() && user != null) { for (String group : groups) { String value = groupMap.get(group); if (value != null) { List<String> userRoleList = new ArrayList<String>(); userRoleList.add(value); if (userMap.containsKey(user.getName())) { List<String> userRole = new ArrayList<String>(); userRole.add(userMap.get(user.getName())); user.setUserRoleList(userRole); } else { user.setUserRoleList(userRoleList); } } } } usergroupInfo.setXuserInfo(user); } for(String g : groups) { LOG.debug("INFO: addPMXAGroupToUser(" + userName + "," + g + ")" ); } if (! isMockRun ) { addXUserGroupInfo(user, groups); } if (authenticationType != null && AUTH_KERBEROS.equalsIgnoreCase(authenticationType) && SecureClientLogin.isKerberosCredentialExists(principal, keytab)){ try { Subject sub = SecureClientLogin.loginUserFromKeytab(principal, keytab, nameRules); final UserGroupInfo result = ret; ret = Subject.doAs(sub, new PrivilegedAction<UserGroupInfo>() { @Override public UserGroupInfo run() { try { return getUsergroupInfo(result); } catch (Exception e) { LOG.error("Failed to add User Group Info : ", e); } return null; } }); return ret; } catch (Exception e) { LOG.error("Failed to Authenticate Using given Principal and Keytab : " , e); } return null; }else{ return getUsergroupInfo(ret); } } private UserGroupInfo getUsergroupInfo(UserGroupInfo ret) { if(LOG.isDebugEnabled()){ LOG.debug("==> PolicyMgrUserGroupBuilder.getUsergroupInfo(UserGroupInfo ret)"); } String response = null; Gson gson = new GsonBuilder().create(); String jsonString = gson.toJson(usergroupInfo); if (LOG.isDebugEnabled()) { LOG.debug("USER GROUP MAPPING" + jsonString); } if(isRangerCookieEnabled){ response = cookieBasedUploadEntity(jsonString,PM_ADD_USER_GROUP_INFO_URI); } else{ Client c = getClient(); WebResource r = c.resource(getURL(PM_ADD_USER_GROUP_INFO_URI)); try{ response = r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).post(String.class, jsonString); } catch(Throwable t){ LOG.error("Failed to communicate Ranger Admin : ", t); } } if ( LOG.isDebugEnabled() ) { LOG.debug("RESPONSE: [" + response + "]"); } ret = gson.fromJson(response, UserGroupInfo.class); if ( ret != null) { XUserInfo xUserInfo = ret.getXuserInfo(); addUserToList(xUserInfo); for(XGroupInfo xGroupInfo : ret.getXgroupInfo()) { addGroupToList(xGroupInfo); addUserGroupInfoToList(xUserInfo,xGroupInfo); } } if(LOG.isDebugEnabled()){ LOG.debug("<== PolicyMgrUserGroupBuilder.getUsergroupInfo (UserGroupInfo ret)"); } return ret; } private UserGroupInfo getUserGroupInfo(UserGroupInfo usergroupInfo) { UserGroupInfo ret = null; if(LOG.isDebugEnabled()){ LOG.debug("==> PolicyMgrUserGroupBuilder.getUsergroupInfo(UserGroupInfo ret, UserGroupInfo usergroupInfo)"); } String response = null; Gson gson = new GsonBuilder().create(); String jsonString = gson.toJson(usergroupInfo); if (LOG.isDebugEnabled()) { LOG.debug("USER GROUP MAPPING" + jsonString); } if(isRangerCookieEnabled){ response = cookieBasedUploadEntity(jsonString,PM_ADD_USER_GROUP_INFO_URI); } else{ Client c = getClient(); WebResource r = c.resource(getURL(PM_ADD_USER_GROUP_INFO_URI)); try{ response=r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).post(String.class, jsonString); }catch(Throwable t){ LOG.error("Failed to communicate Ranger Admin : ", t); } } if (LOG.isDebugEnabled()) { LOG.debug("RESPONSE: [" + response + "]"); } ret = gson.fromJson(response, UserGroupInfo.class); if ( ret != null) { XUserInfo xUserInfo = ret.getXuserInfo(); addUserToList(xUserInfo); for (XGroupInfo xGroupInfo : ret.getXgroupInfo()) { addGroupToList(xGroupInfo); addUserGroupInfoToList(xUserInfo, xGroupInfo); } } if(LOG.isDebugEnabled()){ LOG.debug("<== PolicyMgrUserGroupBuilder.getUsergroupInfo(UserGroupInfo ret, UserGroupInfo usergroupInfo)"); } return ret; } private String tryUploadEntityWithCookie(String jsonString, String apiURL) { if (LOG.isDebugEnabled()) { LOG.debug("==> PolicyMgrUserGroupBuilder.tryUploadEntityWithCookie()"); } String response = null; ClientResponse clientResp = null; WebResource webResource = createWebResourceForCookieAuth(apiURL); WebResource.Builder br = webResource.getRequestBuilder().cookie(sessionId); try{ clientResp=br.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).post(ClientResponse.class, jsonString); } catch(Throwable t){ LOG.error("Failed to communicate Ranger Admin : ", t); } if (clientResp != null) { if (!(clientResp.toString().contains(apiURL))) { clientResp.setStatus(HttpServletResponse.SC_NOT_FOUND); sessionId = null; isValidRangerCookie = false; } else if (clientResp.getStatus() == HttpServletResponse.SC_UNAUTHORIZED) { sessionId = null; isValidRangerCookie = false; } else if (clientResp.getStatus() == HttpServletResponse.SC_NO_CONTENT || clientResp.getStatus() == HttpServletResponse.SC_OK) { cookieList = clientResp.getCookies(); for (NewCookie cookie : cookieList) { if (cookie.getName().equalsIgnoreCase(RANGER_ADMIN_COOKIE_NAME)) { sessionId = cookie.toCookie(); isValidRangerCookie = true; break; } } } if (clientResp.getStatus() != HttpServletResponse.SC_OK && clientResp.getStatus() != HttpServletResponse.SC_NO_CONTENT && clientResp.getStatus() != HttpServletResponse.SC_BAD_REQUEST) { sessionId = null; isValidRangerCookie = false; } clientResp.bufferEntity(); response = clientResp.getEntity(String.class); } if (LOG.isDebugEnabled()) { LOG.debug("<== PolicyMgrUserGroupBuilder.tryUploadEntityWithCookie()"); } return response; } private String tryUploadEntityWithCred(String jsonString,String apiURL){ if(LOG.isDebugEnabled()){ LOG.debug("==> PolicyMgrUserGroupBuilder.tryUploadEntityInfoWithCred()"); } String response = null; ClientResponse clientResp = null; Client c = getClient(); WebResource r = c.resource(getURL(apiURL)); if ( LOG.isDebugEnabled() ) { LOG.debug("USER GROUP MAPPING" + jsonString); } try{ clientResp=r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).post(ClientResponse.class, jsonString); } catch(Throwable t){ LOG.error("Failed to communicate Ranger Admin : ", t); } if (clientResp != null) { if (!(clientResp.toString().contains(apiURL))) { clientResp.setStatus(HttpServletResponse.SC_NOT_FOUND); } else if (clientResp.getStatus() == HttpServletResponse.SC_UNAUTHORIZED) { LOG.warn("Credentials response from ranger is 401."); } else if (clientResp.getStatus() == HttpServletResponse.SC_OK || clientResp.getStatus() == HttpServletResponse.SC_NO_CONTENT) { cookieList = clientResp.getCookies(); for (NewCookie cookie : cookieList) { if (cookie.getName().equalsIgnoreCase(RANGER_ADMIN_COOKIE_NAME)) { sessionId = cookie.toCookie(); isValidRangerCookie = true; LOG.info("valid cookie saved "); break; } } } if (clientResp.getStatus() != HttpServletResponse.SC_OK && clientResp.getStatus() != HttpServletResponse.SC_NO_CONTENT && clientResp.getStatus() != HttpServletResponse.SC_BAD_REQUEST) { sessionId = null; isValidRangerCookie = false; } clientResp.bufferEntity(); response = clientResp.getEntity(String.class); } if (LOG.isDebugEnabled()) { LOG.debug("<== PolicyMgrUserGroupBuilder.tryUploadEntityInfoWithCred()"); } return response; } private UserGroupInfo addUserGroupInfo(UserGroupInfo usergroupInfo){ if(LOG.isDebugEnabled()) { LOG.debug("==> PolicyMgrUserGroupBuilder.addUserGroupInfo"); } UserGroupInfo ret = null; if (authenticationType != null && AUTH_KERBEROS.equalsIgnoreCase(authenticationType) && SecureClientLogin.isKerberosCredentialExists(principal, keytab)) { try { Subject sub = SecureClientLogin.loginUserFromKeytab(principal, keytab, nameRules); final UserGroupInfo ugInfo = usergroupInfo; ret = Subject.doAs(sub, new PrivilegedAction<UserGroupInfo>() { @Override public UserGroupInfo run() { try { return getUserGroupInfo(ugInfo); } catch (Exception e) { LOG.error("Failed to add User Group Info : ", e); } return null; } }); return ret; } catch (Exception e) { LOG.error("Failed to Authenticate Using given Principal and Keytab : ",e); } } else { try { ret = getUserGroupInfo(usergroupInfo); } catch (Throwable t) { LOG.error("Failed to add User Group Info : ", t); } } if (LOG.isDebugEnabled()) { LOG.debug("<== PolicyMgrUserGroupBuilder.addUserGroupInfo"); } return ret; } private XUserInfo addXUserInfo(String aUserName) { XUserInfo xuserInfo = new XUserInfo(); xuserInfo.setName(aUserName); xuserInfo.setDescription(aUserName + " - add from Unix box"); List<String> userRole = new ArrayList<>(); userRole.add("ROLE_USER"); xuserInfo.setUserRoleList(userRole); usergroupInfo.setXuserInfo(xuserInfo); return xuserInfo; } private XGroupInfo addXGroupInfo(String aGroupName) { XGroupInfo addGroup = new XGroupInfo(); addGroup.setName(aGroupName); addGroup.setDescription(aGroupName + " - add from Unix box"); addGroup.setGroupType("1"); addGroup.setGroupSource(GROUP_SOURCE_EXTERNAL); return addGroup; } private void addXUserGroupInfo(XUserInfo aUserInfo, List<String> aGroupList) { List<XGroupInfo> xGroupInfoList = new ArrayList<XGroupInfo>(); for(String groupName : aGroupList) { XGroupInfo group = groupName2XGroupInfoMap.get(groupName); if (group == null) { group = addXGroupInfo(groupName); } xGroupInfoList.add(group); addXUserGroupInfo(aUserInfo, group); } usergroupInfo.setXgroupInfo(xGroupInfoList); } private List<XGroupInfo> getXGroupInfoList(List<String> aGroupList) { List<XGroupInfo> xGroupInfoList = new ArrayList<XGroupInfo>(); for(String groupName : aGroupList) { XGroupInfo group = groupName2XGroupInfoMap.get(groupName); if (group == null) { group = addXGroupInfo(groupName); }else if(!GROUP_SOURCE_EXTERNAL.equals(group.getGroupSource())){ group.setGroupSource(GROUP_SOURCE_EXTERNAL); } xGroupInfoList.add(group); } return xGroupInfoList; } private XUserGroupInfo addXUserGroupInfo(XUserInfo aUserInfo, XGroupInfo aGroupInfo) { XUserGroupInfo ugInfo = new XUserGroupInfo(); ugInfo.setUserId(aUserInfo.getId()); ugInfo.setGroupName(aGroupInfo.getName()); // ugInfo.setParentGroupId("1"); return ugInfo; } private void delXUserGroupInfo(final XUserInfo aUserInfo, List<String> aGroupList) { for(String groupName : aGroupList) { final XGroupInfo group = groupName2XGroupInfoMap.get(groupName); if (group != null) { if (authenticationType != null && AUTH_KERBEROS.equalsIgnoreCase(authenticationType) && SecureClientLogin.isKerberosCredentialExists(principal, keytab)) { try { LOG.debug("Using principal = " + principal + " and keytab = " + keytab); Subject sub = SecureClientLogin.loginUserFromKeytab(principal, keytab, nameRules); Subject.doAs(sub, new PrivilegedAction<Void>() { @Override public Void run() { try { delXUserGroupInfo(aUserInfo, group); } catch (Exception e) { LOG.error("Failed to build Group List : ", e); } return null; } }); } catch (Exception e) { LOG.error("Failed to Authenticate Using given Principal and Keytab : ",e); } } else { delXUserGroupInfo(aUserInfo, group); } } } } private void delXUserGroupInfo(XUserInfo aUserInfo, XGroupInfo aGroupInfo) { if (LOG.isDebugEnabled()) { LOG.debug("==> PolicyMgrUserGroupBuilder.delXUserGroupInfo()"); } String groupName = aGroupInfo.getName(); String userName = aUserInfo.getName(); try { ClientResponse response = null; String uri = PM_DEL_USER_GROUP_LINK_URI.replaceAll(Pattern.quote("${groupName}"), URLEncoderUtil.encodeURIParam(groupName)).replaceAll(Pattern.quote("${userName}"), URLEncoderUtil.encodeURIParam(userName)); if (isRangerCookieEnabled) { if (sessionId != null && isValidRangerCookie) { WebResource webResource = createWebResourceForCookieAuth(uri); WebResource.Builder br = webResource.getRequestBuilder().cookie(sessionId); response = br.delete(ClientResponse.class); if (response != null) { if (!(response.toString().contains(uri))) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); sessionId = null; isValidRangerCookie = false; } else if (response.getStatus() == HttpServletResponse.SC_UNAUTHORIZED) { LOG.warn("response from ranger is 401 unauthorized"); sessionId = null; isValidRangerCookie = false; } else if (response.getStatus() == HttpServletResponse.SC_NO_CONTENT || response.getStatus() == HttpServletResponse.SC_OK) { cookieList = response.getCookies(); for (NewCookie cookie : cookieList) { if (cookie.getName().equalsIgnoreCase(RANGER_ADMIN_COOKIE_NAME)) { sessionId = cookie.toCookie(); isValidRangerCookie = true; break; } } } if (response.getStatus() != HttpServletResponse.SC_OK && response.getStatus() != HttpServletResponse.SC_NO_CONTENT && response.getStatus() != HttpServletResponse.SC_BAD_REQUEST) { sessionId = null; isValidRangerCookie = false; } } } else { Client c = getClient(); WebResource r = c.resource(getURL(uri)); response = r.delete(ClientResponse.class); if (response != null) { if (!(response.toString().contains(uri))) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } else if (response.getStatus() == HttpServletResponse.SC_UNAUTHORIZED) { LOG.warn("Credentials response from ranger is 401."); } else if (response.getStatus() == HttpServletResponse.SC_OK || response.getStatus() == HttpServletResponse.SC_NO_CONTENT) { cookieList = response.getCookies(); for (NewCookie cookie : cookieList) { if (cookie.getName().equalsIgnoreCase(RANGER_ADMIN_COOKIE_NAME)) { sessionId = cookie.toCookie(); isValidRangerCookie = true; LOG.info("valid cookie saved "); break; } } } if (response.getStatus() != HttpServletResponse.SC_OK && response.getStatus() != HttpServletResponse.SC_NO_CONTENT && response.getStatus() != HttpServletResponse.SC_BAD_REQUEST) { sessionId = null; isValidRangerCookie = false; } } } } else { Client c = getClient(); WebResource r = c.resource(getURL(uri)); response = r.delete(ClientResponse.class); } if ( LOG.isDebugEnabled() ) { LOG.debug("RESPONSE: [" + response.toString() + "]"); } if (response.getStatus() == 200) { delUserGroupFromList(aUserInfo, aGroupInfo); } } catch (Exception e) { LOG.warn( "ERROR: Unable to delete GROUP: " + groupName + " from USER:" + userName , e); } if (LOG.isDebugEnabled()) { LOG.debug("<== PolicyMgrUserGroupBuilder.delXUserGroupInfo()"); } } private MUserInfo addMUser(String aUserName) { MUserInfo ret = null; MUserInfo userInfo = new MUserInfo(); userInfo.setLoginId(aUserName); userInfo.setFirstName(aUserName); userInfo.setLastName(aUserName); String str[] = new String[1]; if (userMap.containsKey(aUserName)) { str[0] = userMap.get(aUserName); } userInfo.setUserRoleList(str); if (authenticationType != null && AUTH_KERBEROS.equalsIgnoreCase(authenticationType) && SecureClientLogin.isKerberosCredentialExists(principal, keytab)) { try { Subject sub = SecureClientLogin.loginUserFromKeytab(principal, keytab, nameRules); final MUserInfo result = ret; final MUserInfo userInfoFinal = userInfo; ret = Subject.doAs(sub, new PrivilegedAction<MUserInfo>() { @Override public MUserInfo run() { try { return getMUser(userInfoFinal, result); } catch (Exception e) { LOG.error("Failed to add User : ", e); } return null; } }); return ret; } catch (Exception e) { LOG.error("Failed to Authenticate Using given Principal and Keytab : " , e); } return null; } else { return getMUser(userInfo, ret); } } private MUserInfo getMUser(MUserInfo userInfo, MUserInfo ret) { if(LOG.isDebugEnabled()){ LOG.debug("==> PolicyMgrUserGroupBuilder.getMUser()"); } String response = null; Gson gson = new GsonBuilder().create(); String jsonString = gson.toJson(userInfo); if (isRangerCookieEnabled) { response = cookieBasedUploadEntity(jsonString, PM_ADD_LOGIN_USER_URI); } else { Client c = getClient(); WebResource r = c.resource(getURL(PM_ADD_LOGIN_USER_URI)); response = r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE) .post(String.class, jsonString); } if (LOG.isDebugEnabled()) { LOG.debug("RESPONSE[" + response + "]"); } ret = gson.fromJson(response, MUserInfo.class); if (LOG.isDebugEnabled()) { LOG.debug("MUser Creation successful " + ret); LOG.debug("<== PolicyMgrUserGroupBuilder.getMUser()"); } return ret; } private String cookieBasedUploadEntity(String jsonString, String apiURL ) { if (LOG.isDebugEnabled()) { LOG.debug("==> PolicyMgrUserGroupBuilder.cookieBasedUploadEntity()"); } String response = null; if (sessionId != null && isValidRangerCookie) { response = tryUploadEntityWithCookie(jsonString,apiURL); } else{ response = tryUploadEntityWithCred(jsonString,apiURL); } if (LOG.isDebugEnabled()) { LOG.debug("<== PolicyMgrUserGroupBuilder.cookieBasedUploadEntity()"); } return response; } private String cookieBasedGetEntity(String apiURL ,int retrievedCount) { if (LOG.isDebugEnabled()) { LOG.debug("==> PolicyMgrUserGroupBuilder.cookieBasedGetEntity()"); } String response = null; if (sessionId != null && isValidRangerCookie) { response = tryGetEntityWithCookie(apiURL,retrievedCount); } else{ response = tryGetEntityWithCred(apiURL,retrievedCount); } if (LOG.isDebugEnabled()) { LOG.debug("<== PolicyMgrUserGroupBuilder.cookieBasedGetEntity()"); } return response; } private String tryGetEntityWithCred(String apiURL, int retrievedCount) { if(LOG.isDebugEnabled()){ LOG.debug("==> PolicyMgrUserGroupBuilder.tryGetEntityWithCred()"); } String response = null; ClientResponse clientResp = null; Client c = getClient(); WebResource r = c.resource(getURL(apiURL)) .queryParam("pageSize", recordsToPullPerCall) .queryParam("startIndex", String.valueOf(retrievedCount)); try{ clientResp=r.accept(MediaType.APPLICATION_JSON_TYPE).get(ClientResponse.class); } catch(Throwable t){ LOG.error("Failed to communicate Ranger Admin : ", t); } if (clientResp != null) { if (!(clientResp.toString().contains(apiURL))) { clientResp.setStatus(HttpServletResponse.SC_NOT_FOUND); } else if (clientResp.getStatus() == HttpServletResponse.SC_UNAUTHORIZED) { LOG.warn("Credentials response from ranger is 401."); } else if (clientResp.getStatus() == HttpServletResponse.SC_OK || clientResp.getStatus() == HttpServletResponse.SC_NO_CONTENT) { cookieList = clientResp.getCookies(); for (NewCookie cookie : cookieList) { if (cookie.getName().equalsIgnoreCase(RANGER_ADMIN_COOKIE_NAME)) { sessionId = cookie.toCookie(); isValidRangerCookie = true; LOG.info("valid cookie saved "); break; } } } if (clientResp.getStatus() != HttpServletResponse.SC_OK && clientResp.getStatus() != HttpServletResponse.SC_NO_CONTENT && clientResp.getStatus() != HttpServletResponse.SC_BAD_REQUEST) { sessionId = null; isValidRangerCookie = false; } clientResp.bufferEntity(); response = clientResp.getEntity(String.class); } if (LOG.isDebugEnabled()) { LOG.debug("<== PolicyMgrUserGroupBuilder.tryGetEntityWithCred()"); } return response; } private String tryGetEntityWithCookie(String apiURL, int retrievedCount) { if (LOG.isDebugEnabled()) { LOG.debug("==> PolicyMgrUserGroupBuilder.tryGetEntityWithCookie()"); } String response = null; ClientResponse clientResp = null; WebResource webResource = createWebResourceForCookieAuth(apiURL).queryParam("pageSize", recordsToPullPerCall).queryParam("startIndex", String.valueOf(retrievedCount)); WebResource.Builder br = webResource.getRequestBuilder().cookie(sessionId); try{ clientResp=br.accept(MediaType.APPLICATION_JSON_TYPE).get(ClientResponse.class); } catch(Throwable t){ LOG.error("Failed to communicate Ranger Admin : ", t); } if (clientResp != null) { if (!(clientResp.toString().contains(apiURL))) { clientResp.setStatus(HttpServletResponse.SC_NOT_FOUND); sessionId = null; isValidRangerCookie = false; } else if (clientResp.getStatus() == HttpServletResponse.SC_UNAUTHORIZED) { sessionId = null; isValidRangerCookie = false; } else if (clientResp.getStatus() == HttpServletResponse.SC_NO_CONTENT || clientResp.getStatus() == HttpServletResponse.SC_OK) { cookieList = clientResp.getCookies(); for (NewCookie cookie : cookieList) { if (cookie.getName().equalsIgnoreCase(RANGER_ADMIN_COOKIE_NAME)) { sessionId = cookie.toCookie(); isValidRangerCookie = true; break; } } } if (clientResp.getStatus() != HttpServletResponse.SC_OK && clientResp.getStatus() != HttpServletResponse.SC_NO_CONTENT && clientResp.getStatus() != HttpServletResponse.SC_BAD_REQUEST) { sessionId = null; isValidRangerCookie = false; } clientResp.bufferEntity(); response = clientResp.getEntity(String.class); } if (LOG.isDebugEnabled()) { LOG.debug("<== PolicyMgrUserGroupBuilder.tryGetEntityWithCookie()"); } return response; } public Client getClient() { // result saves on access time when client is built at the time of the call Client result = client; if(result == null) { synchronized(this) { result = client; if(result == null) { client = result = buildClient(); } } } return result; } private Client buildClient() { Client ret = null; if (policyMgrBaseUrl.startsWith("https://")) { ClientConfig config = new DefaultClientConfig(); if (sslContext == null) { try { KeyManager[] kmList = null; TrustManager[] tmList = null; if (keyStoreFile != null && keyStoreFilepwd != null) { KeyStore keyStore = KeyStore.getInstance(keyStoreType); InputStream in = null; try { in = getFileInputStream(keyStoreFile); if (in == null) { LOG.error("Unable to obtain keystore from file [" + keyStoreFile + "]"); return ret; } keyStore.load(in, keyStoreFilepwd.toCharArray()); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, keyStoreFilepwd.toCharArray()); kmList = keyManagerFactory.getKeyManagers(); } finally { if (in != null) { in.close(); } } } if (trustStoreFile != null && trustStoreFilepwd != null) { KeyStore trustStore = KeyStore.getInstance(trustStoreType); InputStream in = null; try { in = getFileInputStream(trustStoreFile); if (in == null) { LOG.error("Unable to obtain keystore from file [" + trustStoreFile + "]"); return ret; } trustStore.load(in, trustStoreFilepwd.toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); tmList = trustManagerFactory.getTrustManagers(); } finally { if (in != null) { in.close(); } } } sslContext = SSLContext.getInstance("TLS"); sslContext.init(kmList, tmList, new SecureRandom()); hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { return session.getPeerHost().equals(urlHostName); } }; } catch(Throwable t) { throw new RuntimeException("Unable to create SSLConext for communication to policy manager", t); } } config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(hv, sslContext)); ret = Client.create(config); } else { ClientConfig cc = new DefaultClientConfig(); cc.getProperties().put(ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true); ret = Client.create(cc); } if(!(authenticationType != null && AUTH_KERBEROS.equalsIgnoreCase(authenticationType) && SecureClientLogin.isKerberosCredentialExists(principal, keytab))){ if(ret!=null){ String username = config.getPolicyMgrUserName(); String password = config.getPolicyMgrPassword(); if(username!=null && !username.trim().isEmpty() && password!=null && !password.trim().isEmpty()){ ret.addFilter(new HTTPBasicAuthFilter(username, password)); } } } return ret; } private WebResource createWebResourceForCookieAuth(String url) { Client cookieClient = getClient(); cookieClient.removeAllFilters(); WebResource ret = cookieClient.resource(getURL(url)); return ret; } private InputStream getFileInputStream(String path) throws FileNotFoundException { InputStream ret = null; File f = new File(path); if (f.exists()) { ret = new FileInputStream(f); } else { ret = PolicyMgrUserGroupBuilder.class.getResourceAsStream(path); if (ret == null) { if (! path.startsWith("/")) { ret = getClass().getResourceAsStream("/" + path); } } if (ret == null) { ret = ClassLoader.getSystemClassLoader().getResourceAsStream(path); if (ret == null) { if (! path.startsWith("/")) { ret = ClassLoader.getSystemResourceAsStream("/" + path); } } } } return ret; } @Override public void addOrUpdateGroup(String groupName) throws Throwable{ XGroupInfo group = groupName2XGroupInfoMap.get(groupName); if (group == null) { // Does not exists //* Build the group info object and do the rest call if ( ! isMockRun ) { group = addGroupInfo(groupName); if ( group != null) { addGroupToList(group); } else { String msg = "Failed to add addorUpdate group info"; LOG.error(msg); throw new Exception(msg); } } } } private XGroupInfo addGroupInfo(final String groupName){ XGroupInfo ret = null; XGroupInfo group = null; LOG.debug("INFO: addPMXAGroup(" + groupName + ")" ); if (! isMockRun) { group = addXGroupInfo(groupName); } if (authenticationType != null && AUTH_KERBEROS.equalsIgnoreCase(authenticationType) && SecureClientLogin.isKerberosCredentialExists(principal,keytab)) { try { LOG.info("Using principal = " + principal + " and keytab = " + keytab); Subject sub = SecureClientLogin.loginUserFromKeytab(principal, keytab, nameRules); final XGroupInfo groupInfo = group; ret = Subject.doAs(sub, new PrivilegedAction<XGroupInfo>() { @Override public XGroupInfo run() { try { return getAddedGroupInfo(groupInfo); } catch (Exception e) { LOG.error("Failed to build Group List : ", e); } return null; } }); return ret; } catch (Exception e) { LOG.error("Failed to Authenticate Using given Principal and Keytab : ", e); } return null; } else { return getAddedGroupInfo(group); } } private XGroupInfo getAddedGroupInfo(XGroupInfo group){ XGroupInfo ret = null; String response = null; Gson gson = new GsonBuilder().create(); String jsonString = gson.toJson(group); if(isRangerCookieEnabled){ response = cookieBasedUploadEntity(jsonString,PM_ADD_GROUP_URI); } else{ Client c = getClient(); WebResource r = c.resource(getURL(PM_ADD_GROUP_URI)); if (LOG.isDebugEnabled()) { LOG.debug("Group" + jsonString); } try{ response = r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).post(String.class, jsonString); } catch(Throwable t){ LOG.error("Failed to communicate Ranger Admin : ", t); } } if ( LOG.isDebugEnabled() ) { LOG.debug("RESPONSE: [" + response + "]"); } ret = gson.fromJson(response, XGroupInfo.class); return ret; } @Override public void addOrUpdateUser(String user) throws Throwable { // TODO Auto-generated method stub } @Override public void addOrUpdateGroup(String groupName, List<String> users) throws Throwable { if (users == null || users.isEmpty()) { if (groupName2XGroupInfoMap.containsKey(groupName)) { modifiedGroupList.add(groupName); } else { newGroupList.add(groupName); } } addOrUpdateGroup(groupName); } @Override public void postUserGroupAuditInfo(UgsyncAuditInfo ugsyncAuditInfo) throws Throwable { if (! isMockRun) { addUserGroupAuditInfo(ugsyncAuditInfo); } noOfNewUsers = 0; noOfNewGroups = 0; noOfModifiedUsers = 0; noOfModifiedGroups = 0; isStartupFlag = false; newUserList.clear(); modifiedUserList.clear(); newGroupList.clear(); modifiedGroupList.clear(); } private UgsyncAuditInfo addUserGroupAuditInfo(UgsyncAuditInfo auditInfo) { UgsyncAuditInfo ret = null; if (auditInfo == null) { LOG.error("Failed to generate user group audit info"); return ret; } noOfNewUsers = newUserList.size(); noOfModifiedUsers = modifiedUserList.size(); noOfNewGroups = newGroupList.size(); noOfModifiedGroups = modifiedGroupList.size(); auditInfo.setNoOfNewUsers(Integer.toUnsignedLong(noOfNewUsers)); auditInfo.setNoOfNewGroups(Integer.toUnsignedLong(noOfNewGroups)); auditInfo.setNoOfModifiedUsers(Integer.toUnsignedLong(noOfModifiedUsers)); auditInfo.setNoOfModifiedGroups(Integer.toUnsignedLong(noOfModifiedGroups)); auditInfo.setSessionId(""); LOG.debug("INFO: addAuditInfo(" + auditInfo.getNoOfNewUsers() + ", " + auditInfo.getNoOfNewGroups() + ", " + auditInfo.getNoOfModifiedUsers() + ", " + auditInfo.getNoOfModifiedGroups() + ", " + auditInfo.getSyncSource() + ")"); if (authenticationType != null && AUTH_KERBEROS.equalsIgnoreCase(authenticationType) && SecureClientLogin.isKerberosCredentialExists(principal, keytab)) { try { Subject sub = SecureClientLogin.loginUserFromKeytab(principal, keytab, nameRules); final UgsyncAuditInfo auditInfoFinal = auditInfo; ret = Subject.doAs(sub, new PrivilegedAction<UgsyncAuditInfo>() { @Override public UgsyncAuditInfo run() { try { return getUserGroupAuditInfo(auditInfoFinal); } catch (Exception e) { LOG.error("Failed to add User : ", e); } return null; } }); return ret; } catch (Exception e) { LOG.error("Failed to Authenticate Using given Principal and Keytab : " , e); } return ret; } else { return getUserGroupAuditInfo(auditInfo); } } private UgsyncAuditInfo getUserGroupAuditInfo(UgsyncAuditInfo userInfo) { if(LOG.isDebugEnabled()){ LOG.debug("==> PolicyMgrUserGroupBuilder.getUserGroupAuditInfo()"); } String response = null; Gson gson = new GsonBuilder().create(); String jsonString = gson.toJson(userInfo); if(isRangerCookieEnabled){ response = cookieBasedUploadEntity(jsonString, PM_AUDIT_INFO_URI); } else{ Client c = getClient(); WebResource r = c.resource(getURL(PM_AUDIT_INFO_URI)); try{ response = r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).post(String.class, jsonString); } catch(Throwable t){ LOG.error("Failed to communicate Ranger Admin : ", t); } } if (LOG.isDebugEnabled()) { LOG.debug("RESPONSE[" + response + "]"); } UgsyncAuditInfo ret = gson.fromJson(response, UgsyncAuditInfo.class); LOG.debug("AuditInfo Creation successful "); if(LOG.isDebugEnabled()){ LOG.debug("<== PolicyMgrUserGroupBuilder.getUserGroupAuditInfo()"); } return ret; } private void getRoleForUserGroups(String userGroupRolesData) { String roleDelimiter = config.getRoleDelimiter(); String userGroupDelimiter = config.getUserGroupDelimiter(); String userNameDelimiter = config.getUserGroupNameDelimiter(); if (roleDelimiter == null || roleDelimiter.isEmpty()) { roleDelimiter = "&"; } if (userGroupDelimiter == null || userGroupDelimiter.isEmpty()) { userGroupDelimiter = ":"; } if (userNameDelimiter == null || userNameDelimiter.isEmpty()) { userNameDelimiter = ","; } StringTokenizer str = new StringTokenizer(userGroupRolesData, roleDelimiter); int flag = 0; String userGroupCheck = null; String roleName = null; while (str.hasMoreTokens()) { flag = 0; String tokens = str.nextToken(); if (tokens != null && !tokens.isEmpty()) { StringTokenizer userGroupRoles = new StringTokenizer(tokens, userGroupDelimiter); if (userGroupRoles != null) { while (userGroupRoles.hasMoreElements()) { String userGroupRolesTokens = userGroupRoles .nextToken(); if (userGroupRolesTokens != null && !userGroupRolesTokens.isEmpty()) { flag++; switch (flag) { case 1: roleName = userGroupRolesTokens; break; case 2: userGroupCheck = userGroupRolesTokens; break; case 3: StringTokenizer userGroupNames = new StringTokenizer( userGroupRolesTokens, userNameDelimiter); if (userGroupNames != null) { while (userGroupNames.hasMoreElements()) { String userGroup = userGroupNames .nextToken(); if (userGroup != null && !userGroup.isEmpty()) { if (userGroupCheck.trim().equalsIgnoreCase("u")) { userMap.put(userGroup.trim(), roleName.trim()); } else if (userGroupCheck.trim().equalsIgnoreCase("g")) { groupMap.put(userGroup.trim(), roleName.trim()); } } } } break; default: userMap.clear(); groupMap.clear(); break; } } } } } } } }
RANGER-2552: Fixed code to update the user role/permissions properly when group memberships are updated
ugsync/src/main/java/org/apache/ranger/unixusersync/process/PolicyMgrUserGroupBuilder.java
RANGER-2552: Fixed code to update the user role/permissions properly when group memberships are updated
Java
apache-2.0
bb9a1392473fe700e8a2e47894e61e2b9932ea3a
0
andreiciubotariu/contact-notifier,andreiciubotariu/led-notifier
package com.ciubotariu_levy.lednotifier.messages; import android.annotation.TargetApi; import android.app.Notification; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.ContactsContract; import android.provider.Telephony; import android.support.v4.app.NotificationCompat; import android.text.TextUtils; import android.util.Log; import com.ciubotariu_levy.lednotifier.constants.RequestCodes; import com.ciubotariu_levy.lednotifier.preferences.Keys; import com.ciubotariu_levy.lednotifier.preferences.Prefs; import com.ciubotariu_levy.lednotifier.receivers.NotificationDismissReceiver; import com.ciubotariu_levy.lednotifier.notifications.controller.NotificationController; import com.ciubotariu_levy.lednotifier.R; import com.ciubotariu_levy.lednotifier.providers.LedContactInfo; import com.googlesource.android.mms.ContentType; import com.makeramen.RoundedTransformationBuilder; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.LinkedHashMap; /** * Handles SMS and MMS receive intents */ public class MessageReceiver extends BroadcastReceiver { private static final String TAG = MessageReceiver.class.getName(); @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); if (bundle == null) { return; } LinkedHashMap<String, MessageInfo> receivedMessages = null; if (intent.getAction().equals(Telephony.Sms.Intents.WAP_PUSH_RECEIVED_ACTION) && ContentType.MMS_MESSAGE.equals(intent.getType())) { Log.v(TAG, "onReceive: received PUSH Intent: " + intent); receivedMessages = MessageUtils.createMessageInfosFromPushIntent(intent, context); } else if (intent.getAction().equals(Telephony.Sms.Intents.SMS_RECEIVED_ACTION)) { Log.v(TAG, "onReceive: received SMS: " + intent); receivedMessages = MessageUtils.createMessageInfosFromSmsIntent(intent, context); } if (receivedMessages == null || receivedMessages.isEmpty()) { Log.w(TAG, "onReceive: no messages extracted"); return; } processNewMessages(receivedMessages); Prefs prefs = Prefs.getInstance(context); boolean showAllNotifs = prefs.getBoolean(Keys.SHOW_ALL_NOTIFICATIONS, false); int defaultColor = prefs.getInt(Keys.DEFAULT_NOTIFICATION_COLOR, Color.GRAY); String defaultRingtoneUriString = null; if (prefs.getBoolean(Keys.NOTIFICATION_AND_SOUND, false)) { defaultRingtoneUriString = prefs.getString(Keys.NOTIFICATIONS_NEW_MESSAGE_RINGTONE, null); } boolean vibeForAllContacts = prefs.getBoolean(Keys.NOTIFICATIONS_NEW_MESSAGE_VIBRATE, false); Notification notification = generateNotificationIfNeeded(context, MessageHistory.getInstance(), showAllNotifs, defaultColor, defaultRingtoneUriString, vibeForAllContacts); postNotification(context, notification); } private void processNewMessages(LinkedHashMap<String, MessageInfo> newMessages) { MessageHistory.getInstance().addMessages(newMessages); } @TargetApi(Build.VERSION_CODES.KITKAT) private Notification generateNotificationIfNeeded(Context context, MessageHistory history, boolean showAllNotifications, int defColor, String defRingtone, boolean vibeForAllContacts) { if (history.getMessages().isEmpty() || (!history.containsCustomMessages() && !showAllNotifications)) { Log.i(TAG, "generateNotificationIfNeeded: no need to create notification"); return null; } Intent smsAppIntent = context.getPackageManager().getLaunchIntentForPackage(this.getClass().getPackage().getName()); String smsAppPackageName = Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT ? Prefs.getInstance(context).getString(Keys.SMS_APP_PACKAGE, this.getClass().getPackage().getName()) : Telephony.Sms.getDefaultSmsPackage(context); Intent betterSmsAppCandidateIntent = context.getPackageManager().getLaunchIntentForPackage(smsAppPackageName); if (betterSmsAppCandidateIntent != null) { smsAppIntent = betterSmsAppCandidateIntent; } if (smsAppIntent == null) { // fallback: launch our app smsAppIntent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName()); } PendingIntent pendingIntent = PendingIntent.getActivity(context, RequestCodes.SMS_APP.ordinal(), smsAppIntent, PendingIntent.FLAG_UPDATE_CURRENT); Bitmap contactPhoto = null; NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(context); NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); int counter = 0; StringBuilder notifBody = new StringBuilder(); StringBuilder notifSummaryText = new StringBuilder(); MessageInfo firstMessage = null; for (MessageInfo message : history.getMessages().values()) { if (message.isCustom() || (showAllNotifications && message.getNameOrAddress() != null)) { if (counter == 0) { firstMessage = message; } counter++; if (message.getContactUriString() != null) { notifBuilder.addPerson(message.getContactUriString()); } notifBody.append(message.getNameOrAddress()).append(": ").append(message.getContentString()).append(", "); inboxStyle.addLine(message.getNameOrAddress() + ": " + message.getContentString()); if (contactPhoto == null) { Bitmap b = loadContactPhotoThumbnail(context, message.getContactUriString()); if (b != null) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { b = new RoundedTransformationBuilder().oval(true).build().transform(b); } contactPhoto = b; } } } } String title = ""; if (counter == 1) { notifBody = new StringBuilder(firstMessage.getContentString()); title = firstMessage.getNameOrAddress(); } else { title = "Multiple Senders"; inboxStyle.setBigContentTitle(title); inboxStyle.setSummaryText(notifSummaryText.toString()); notifBuilder.setStyle(inboxStyle); } notifBuilder.setContentTitle(title) .setContentText(notifBody.toString()) .setContentIntent(pendingIntent) .setSmallIcon(R.drawable.ic_stat_new_msg) .setCategory(NotificationCompat.CATEGORY_MESSAGE) .setVisibility(NotificationCompat.VISIBILITY_PRIVATE) .setAutoCancel(true); if (contactPhoto != null) { notifBuilder.setLargeIcon(contactPhoto); } int customColor = history.getCustomColor() != Color.GRAY ? history.getCustomColor() : defColor; if (customColor != Color.GRAY) { notifBuilder.setLights(customColor, 1000, 1000); // flash } Prefs preferences = Prefs.getInstance(context); if (preferences.getBoolean(Keys.STATUS_BAR_PREVIEW, false)) { notifBuilder.setTicker(title + ": " + notifBuilder.toString()); } else { notifBuilder.setTicker("New message"); } String ringtone = history.getCustomRingtone() != null ? history.getCustomRingtone() : defRingtone; if (!TextUtils.isEmpty(ringtone)) { notifBuilder.setSound(Uri.parse(ringtone)); } if (!TextUtils.isEmpty(history.getCustomVibPattern())) { notifBuilder.setVibrate(LedContactInfo.getVibratePattern(history.getCustomVibPattern())); } Intent delIntent = new Intent(context, NotificationDismissReceiver.class); PendingIntent deletePendIntent = PendingIntent.getBroadcast(context, RequestCodes.NOTIFICATION_DISMISSED.ordinal(), delIntent, PendingIntent.FLAG_UPDATE_CURRENT); notifBuilder.setDeleteIntent(deletePendIntent); Notification notif = notifBuilder.build(); if (vibeForAllContacts) { notif.defaults |= Notification.DEFAULT_VIBRATE; } return notif; } public void postNotification(Context context, Notification notification) { // TODO when notif service enabled, do not use this. Make notif service mandatory too if (notification == null) { Log.i(TAG, "postNotification: null Notification"); return; } NotificationController.getInstance(context).postNotification(notification); } private Bitmap loadContactPhotoThumbnail(Context context, String contactUri) { if (contactUri == null) { return null; } Cursor mCursor = context.getContentResolver().query((Uri.parse(contactUri)), new String[]{ContactsContract.Contacts._ID, Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ? ContactsContract.Contacts.PHOTO_THUMBNAIL_URI : ContactsContract.Contacts._ID}, null, null, null); if (mCursor == null || !mCursor.moveToFirst()) { Log.e(TAG, "loadContactPhotoThumbnail: cursor error | " + mCursor); return null; } int mThumbnailColumn; int mIdColumn = mCursor.getColumnIndex(ContactsContract.Contacts._ID); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { mThumbnailColumn = mCursor.getColumnIndex(ContactsContract.Contacts.PHOTO_THUMBNAIL_URI); } else { mThumbnailColumn = mIdColumn; } String photoData = mCursor.getString(mThumbnailColumn); if (photoData == null) { return null; } Log.v(TAG, "loadContactPhotoThumbnail: photoData is " + photoData); InputStream is = null; try { try { Uri thumbUri; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { thumbUri = Uri.parse(photoData); } else { final Uri contactPhotoUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, photoData); thumbUri = Uri.withAppendedPath(contactPhotoUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY); } is = context.getContentResolver().openInputStream(thumbUri); if (is != null) { BitmapFactory.Options options = new BitmapFactory.Options(); int height = (int) context.getResources().getDimension(android.R.dimen.notification_large_icon_height); int width = (int) context.getResources().getDimension(android.R.dimen.notification_large_icon_width); Bitmap bm = BitmapFactory.decodeStream(is); return Bitmap.createScaledBitmap(bm, width, height, false); } } catch (FileNotFoundException e) { Log.e(TAG, "loadContactPhotoThumbnail: could not find file", e); } } finally { if (is != null) { try { is.close(); } catch (IOException e) { Log.e(TAG, "loadContactPhotoThumbnail: could not close input stream", e); } } if (mCursor != null) { mCursor.close(); } } return null; } }
contactNotifier/src/main/java/com/ciubotariu_levy/lednotifier/messages/MessageReceiver.java
package com.ciubotariu_levy.lednotifier.messages; import android.annotation.TargetApi; import android.app.Notification; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.ContactsContract; import android.provider.Telephony; import android.support.v4.app.NotificationCompat; import android.text.TextUtils; import android.util.Log; import com.ciubotariu_levy.lednotifier.constants.RequestCodes; import com.ciubotariu_levy.lednotifier.preferences.Keys; import com.ciubotariu_levy.lednotifier.preferences.Prefs; import com.ciubotariu_levy.lednotifier.receivers.NotificationDismissReceiver; import com.ciubotariu_levy.lednotifier.notifications.controller.NotificationController; import com.ciubotariu_levy.lednotifier.R; import com.ciubotariu_levy.lednotifier.providers.LedContactInfo; import com.googlesource.android.mms.ContentType; import com.makeramen.RoundedTransformationBuilder; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.LinkedHashMap; /** * Handles SMS and MMS receive intents */ public class MessageReceiver extends BroadcastReceiver { private static final String TAG = MessageReceiver.class.getName(); @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); if (bundle == null) { return; } LinkedHashMap<String, MessageInfo> receivedMessages = null; if (intent.getAction().equals(Telephony.Sms.Intents.WAP_PUSH_RECEIVED_ACTION) && ContentType.MMS_MESSAGE.equals(intent.getType())) { Log.v(TAG, "onReceive: received PUSH Intent: " + intent); receivedMessages = MessageUtils.createMessageInfosFromPushIntent(intent, context); } else if (intent.getAction().equals(Telephony.Sms.Intents.SMS_RECEIVED_ACTION)) { Log.v(TAG, "onReceive: received SMS: " + intent); receivedMessages = MessageUtils.createMessageInfosFromSmsIntent(intent, context); } if (receivedMessages == null || receivedMessages.isEmpty()) { Log.w(TAG, "onReceive: no messages extracted"); return; } processNewMessages(receivedMessages); Prefs prefs = Prefs.getInstance(context); boolean showAllNotifs = prefs.getBoolean(Keys.SHOW_ALL_NOTIFICATIONS, false); int defaultColor = prefs.getInt(Keys.DEFAULT_NOTIFICATION_COLOR, Color.GRAY); String defaultRingtoneUriString = null; if (prefs.getBoolean(Keys.NOTIFICATION_AND_SOUND, false)) { defaultRingtoneUriString = prefs.getString(Keys.NOTIFICATIONS_NEW_MESSAGE_RINGTONE, null); } boolean vibeForAllContacts = prefs.getBoolean(Keys.NOTIFICATIONS_NEW_MESSAGE_VIBRATE, false); Notification notification = generateNotificationIfNeeded(context, MessageHistory.getInstance(), showAllNotifs, defaultColor, defaultRingtoneUriString, vibeForAllContacts); postNotification(context, notification); } private void processNewMessages(LinkedHashMap<String, MessageInfo> newMessages) { MessageHistory.getInstance().addMessages(newMessages); } @TargetApi(Build.VERSION_CODES.KITKAT) private Notification generateNotificationIfNeeded(Context context, MessageHistory history, boolean showAllNotifications, int defColor, String defRingtone, boolean vibeForAllContacts) { if (history.getMessages().isEmpty() || (!history.containsCustomMessages() && !showAllNotifications)) { Log.i(TAG, "generateNotificationIfNeeded: no need to create notification"); return null; } Intent smsAppIntent = context.getPackageManager().getLaunchIntentForPackage(this.getClass().getPackage().getName()); String smsAppPackageName = Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT ? Prefs.getInstance(context).getString(Keys.SMS_APP_PACKAGE, this.getClass().getPackage().getName()) : Telephony.Sms.getDefaultSmsPackage(context); Intent betterSmsAppCandidateIntent = context.getPackageManager().getLaunchIntentForPackage(smsAppPackageName); if (betterSmsAppCandidateIntent != null) { smsAppIntent = betterSmsAppCandidateIntent; } PendingIntent pendingIntent = PendingIntent.getActivity(context, RequestCodes.SMS_APP.ordinal(), smsAppIntent, PendingIntent.FLAG_UPDATE_CURRENT); Bitmap contactPhoto = null; NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(context); NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); int counter = 0; StringBuilder notifBody = new StringBuilder(); StringBuilder notifSummaryText = new StringBuilder(); MessageInfo firstMessage = null; for (MessageInfo message : history.getMessages().values()) { if (message.isCustom() || (showAllNotifications && message.getNameOrAddress() != null)) { if (counter == 0) { firstMessage = message; } counter++; if (message.getContactUriString() != null) { notifBuilder.addPerson(message.getContactUriString()); } notifBody.append(message.getNameOrAddress()).append(": ").append(message.getContentString()).append(", "); inboxStyle.addLine(message.getNameOrAddress() + ": " + message.getContentString()); if (contactPhoto == null) { Bitmap b = loadContactPhotoThumbnail(context, message.getContactUriString()); if (b != null) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { b = new RoundedTransformationBuilder().oval(true).build().transform(b); } contactPhoto = b; } } } } String title = ""; if (counter == 1) { notifBody = new StringBuilder(firstMessage.getContentString()); title = firstMessage.getNameOrAddress(); } else { title = "Multiple Senders"; inboxStyle.setBigContentTitle(title); inboxStyle.setSummaryText(notifSummaryText.toString()); notifBuilder.setStyle(inboxStyle); } notifBuilder.setContentTitle(title) .setContentText(notifBody.toString()) .setContentIntent(pendingIntent) .setSmallIcon(R.drawable.ic_stat_new_msg) .setCategory(NotificationCompat.CATEGORY_MESSAGE) .setVisibility(NotificationCompat.VISIBILITY_PRIVATE) .setAutoCancel(true); if (contactPhoto != null) { notifBuilder.setLargeIcon(contactPhoto); } int customColor = history.getCustomColor() != Color.GRAY ? history.getCustomColor() : defColor; if (customColor != Color.GRAY) { notifBuilder.setLights(customColor, 1000, 1000); // flash } Prefs preferences = Prefs.getInstance(context); if (preferences.getBoolean(Keys.STATUS_BAR_PREVIEW, false)) { notifBuilder.setTicker(title + ": " + notifBuilder.toString()); } else { notifBuilder.setTicker("New message"); } String ringtone = history.getCustomRingtone() != null ? history.getCustomRingtone() : defRingtone; if (!TextUtils.isEmpty(ringtone)) { notifBuilder.setSound(Uri.parse(ringtone)); } if (!TextUtils.isEmpty(history.getCustomVibPattern())) { notifBuilder.setVibrate(LedContactInfo.getVibratePattern(history.getCustomVibPattern())); } Intent delIntent = new Intent(context, NotificationDismissReceiver.class); PendingIntent deletePendIntent = PendingIntent.getBroadcast(context, RequestCodes.NOTIFICATION_DISMISSED.ordinal(), delIntent, PendingIntent.FLAG_UPDATE_CURRENT); notifBuilder.setDeleteIntent(deletePendIntent); Notification notif = notifBuilder.build(); if (vibeForAllContacts) { notif.defaults |= Notification.DEFAULT_VIBRATE; } return notif; } public void postNotification(Context context, Notification notification) { // TODO when notif service enabled, do not use this. Make notif service mandatory too if (notification == null) { Log.i(TAG, "postNotification: null Notification"); return; } NotificationController.getInstance(context).postNotification(notification); } private Bitmap loadContactPhotoThumbnail(Context context, String contactUri) { if (contactUri == null) { return null; } Cursor mCursor = context.getContentResolver().query((Uri.parse(contactUri)), new String[]{ContactsContract.Contacts._ID, Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ? ContactsContract.Contacts.PHOTO_THUMBNAIL_URI : ContactsContract.Contacts._ID}, null, null, null); if (mCursor == null || !mCursor.moveToFirst()) { Log.e(TAG, "loadContactPhotoThumbnail: cursor error | " + mCursor); return null; } int mThumbnailColumn; int mIdColumn = mCursor.getColumnIndex(ContactsContract.Contacts._ID); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { mThumbnailColumn = mCursor.getColumnIndex(ContactsContract.Contacts.PHOTO_THUMBNAIL_URI); } else { mThumbnailColumn = mIdColumn; } String photoData = mCursor.getString(mThumbnailColumn); if (photoData == null) { return null; } Log.v(TAG, "loadContactPhotoThumbnail: photoData is " + photoData); InputStream is = null; try { try { Uri thumbUri; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { thumbUri = Uri.parse(photoData); } else { final Uri contactPhotoUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, photoData); thumbUri = Uri.withAppendedPath(contactPhotoUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY); } is = context.getContentResolver().openInputStream(thumbUri); if (is != null) { BitmapFactory.Options options = new BitmapFactory.Options(); int height = (int) context.getResources().getDimension(android.R.dimen.notification_large_icon_height); int width = (int) context.getResources().getDimension(android.R.dimen.notification_large_icon_width); Bitmap bm = BitmapFactory.decodeStream(is); return Bitmap.createScaledBitmap(bm, width, height, false); } } catch (FileNotFoundException e) { Log.e(TAG, "loadContactPhotoThumbnail: could not find file", e); } } finally { if (is != null) { try { is.close(); } catch (IOException e) { Log.e(TAG, "loadContactPhotoThumbnail: could not close input stream", e); } } if (mCursor != null) { mCursor.close(); } } return null; } }
Use fallback smsAppIntent. Fixes #8
contactNotifier/src/main/java/com/ciubotariu_levy/lednotifier/messages/MessageReceiver.java
Use fallback smsAppIntent. Fixes #8
Java
apache-2.0
c535a1eff98e5501960d30dc6d481fe5be9afbc0
0
PerfCake/PerfCake,PerfCake/PerfCake,PerfCake/PerfCake,PerfCake/PerfCake
/* * -----------------------------------------------------------------------\ * PerfCake *   * Copyright (C) 2010 - 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.perfcake.message.generator; import org.perfcake.PerfCakeConst; import org.perfcake.message.Message; import org.perfcake.message.MessageTemplate; import org.perfcake.message.ReceivedMessage; import org.perfcake.message.correlator.Correlator; import org.perfcake.message.sender.MessageSender; import org.perfcake.message.sender.MessageSenderManager; import org.perfcake.message.sequence.SequenceManager; import org.perfcake.reporting.MeasurementUnit; import org.perfcake.reporting.ReportManager; import org.perfcake.validation.ValidationManager; import org.perfcake.validation.ValidationTask; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.Serializable; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.concurrent.Semaphore; /** * Executes a single task of sending messages from the message store * using instances of {@link MessageSender} provided by message sender manager (see {@link org.perfcake.message.sender.MessageSenderManager}), * receiving the message sender's response and handling the reporting and response message validation. * Sender task is not part of the public API, it is used from generators. * * @author <a href="mailto:[email protected]">Pavel Macík</a> * @author <a href="mailto:[email protected]">Martin Večeřa</a> * @see org.perfcake.message.sender.MessageSenderManager */ public class SenderTask implements Runnable { /** * Sender task's logger. */ private static final Logger log = LogManager.getLogger(SenderTask.class); /** * Reference to a message sender manager that is providing the message senders. */ private MessageSenderManager senderManager; /** * Reference to a message store where the messages are taken from. */ private List<MessageTemplate> messageStore; /** * Reference to a report manager. */ private ReportManager reportManager; /** * A reference to the current validator manager. It is used to validate message responses. */ private ValidationManager validationManager; /** * A reference to the current sequence manager. This is used for determining message specific sequence values. */ private SequenceManager sequenceManager; /** * Controls the amount of prepared tasks in a buffer. */ private final CanalStreet canalStreet; /** * The time when the task was enqueued. */ private long enqueueTime = System.nanoTime(); /** * Correlator to correlate message received from a separate channel. */ private Correlator correlator = null; /** * A response matched by a correlator. */ private Serializable correlatedResponse = null; /** * Synchronize on waiting for a message from a correlator. * Must be set before correlator is used. */ private Semaphore waitForResponse; /** * Creates a new task to send a message. * There is a communication channel established that allows and requires the sender task to report the task completion and any possible error. * The visibility of this constructor is limited as it is not intended for normal use. * To obtain a new instance of a sender task properly initialized call * {@link org.perfcake.message.generator.AbstractMessageGenerator#newSenderTask(java.util.concurrent.Semaphore)}. * * @param canalStreet * The communication channel between this sender task instance and a generator. */ protected SenderTask(final CanalStreet canalStreet) { this.canalStreet = canalStreet; } private Serializable sendMessage(final MessageSender sender, final Message message, final Properties messageAttributes, final MeasurementUnit mu) { try { sender.preSend(message, messageAttributes); } catch (final Exception e) { if (log.isErrorEnabled()) { log.error("Unable to initialize sending of a message: ", e); } canalStreet.senderError(e); } mu.startMeasure(); Serializable result = null; try { result = sender.send(message, mu); } catch (final Exception e) { mu.setFailure(e); if (log.isErrorEnabled()) { log.error("Unable to send a message: ", e); } canalStreet.senderError(e); } mu.stopMeasure(); try { sender.postSend(message); } catch (final Exception e) { if (log.isErrorEnabled()) { log.error("Unable to finish sending of a message: ", e); } canalStreet.senderError(e); } return result; } /** * Executes the scheduled sender task. This is supposed to be controlled by an enclosing thread. */ @Override public void run() { assert messageStore != null && reportManager != null && validationManager != null && senderManager != null : "SenderTask was not properly initialized."; final Properties messageAttributes = sequenceManager != null ? sequenceManager.getSnapshot() : new Properties(); MessageSender sender = null; ReceivedMessage receivedMessage; try { final MeasurementUnit mu = reportManager.newMeasurementUnit(); long requestSize = 0; long responseSize = 0; if (mu != null) { mu.setEnqueueTime(enqueueTime); if (messageAttributes != null) { mu.appendResult(PerfCakeConst.ATTRIBUTES_TAG, messageAttributes); messageAttributes.put(PerfCakeConst.ITERATION_NUMBER_PROPERTY, String.valueOf(mu.getIteration())); } mu.appendResult(PerfCakeConst.THREADS_TAG, reportManager.getRunInfo().getThreads()); sender = senderManager.acquireSender(); final Iterator<MessageTemplate> iterator = messageStore.iterator(); if (iterator.hasNext()) { while (iterator.hasNext()) { final MessageTemplate messageToSend = iterator.next(); final Message currentMessage = messageToSend.getFilteredMessage(messageAttributes); final long multiplicity = messageToSend.getMultiplicity(); requestSize = requestSize + (currentMessage.getPayload().toString().length() * multiplicity); for (int i = 0; i < multiplicity; i++) { if (correlator != null) { correlator.registerRequest(this, currentMessage, messageAttributes); sendMessage(sender, currentMessage, messageAttributes, mu); waitForResponse.acquire(); receivedMessage = new ReceivedMessage(correlatedResponse, messageToSend, currentMessage, messageAttributes); } else { receivedMessage = new ReceivedMessage(sendMessage(sender, currentMessage, messageAttributes, mu), messageToSend, currentMessage, messageAttributes); } if (receivedMessage.getResponse() != null) { responseSize = responseSize + receivedMessage.getResponse().toString().length(); } if (validationManager.isEnabled()) { validationManager.submitValidationTask(new ValidationTask(Thread.currentThread().getName(), receivedMessage)); } } } } else { receivedMessage = new ReceivedMessage(sendMessage(sender, null, messageAttributes, mu), null, null, messageAttributes); if (validationManager.isEnabled()) { validationManager.submitValidationTask(new ValidationTask(Thread.currentThread().getName(), receivedMessage)); } } senderManager.releaseSender(sender); // !!! important !!! sender = null; mu.appendResult(PerfCakeConst.REQUEST_SIZE_TAG, requestSize); mu.appendResult(PerfCakeConst.RESPONSE_SIZE_TAG, responseSize); reportManager.report(mu); } } catch (final Exception e) { e.printStackTrace(); } finally { canalStreet.acknowledgeSend(); if (sender != null) { senderManager.releaseSender(sender); } } } /** * Notifies the sender task of receiving a response from a separate message channel. * This is called from {@link org.perfcake.message.correlator.Correlator} when {@link org.perfcake.message.receiver.Receiver} is used. * * @param response * The response corresponding to the original request. */ public void registerResponse(final Serializable response) { correlatedResponse = response; waitForResponse.release(); } /** * Configures a {@link org.perfcake.message.sender.MessageSenderManager} for the sender task. * * @param senderManager * {@link org.perfcake.message.sender.MessageSenderManager} to be used by the sender task. */ protected void setSenderManager(final MessageSenderManager senderManager) { this.senderManager = senderManager; } /** * Configures a message store for the sender task. * * @param messageStore * Message store to be used by the sender task. */ protected void setMessageStore(final List<MessageTemplate> messageStore) { this.messageStore = messageStore; } /** * Configures a {@link org.perfcake.reporting.ReportManager} for the sender task. * * @param reportManager * {@link org.perfcake.reporting.ReportManager} to be used by the sender task. */ protected void setReportManager(final ReportManager reportManager) { this.reportManager = reportManager; } /** * Configures a {@link org.perfcake.validation.ValidationManager} for the sender task. * * @param validationManager * {@link org.perfcake.validation.ValidationManager} to be used by the sender task. */ protected void setValidationManager(final ValidationManager validationManager) { this.validationManager = validationManager; } /** * Configures a {@link SequenceManager} for the sender task. * * @param sequenceManager * {@link SequenceManager} to be used by the sender task. */ public void setSequenceManager(final SequenceManager sequenceManager) { this.sequenceManager = sequenceManager; } /** * Sets the correlator that is used to notify us about receiving a response from a separate message channel. * * @param correlator * The correlator to be used. */ public void setCorrelator(final Correlator correlator) { waitForResponse = new Semaphore(0); this.correlator = correlator; } }
perfcake/src/main/java/org/perfcake/message/generator/SenderTask.java
/* * -----------------------------------------------------------------------\ * PerfCake *   * Copyright (C) 2010 - 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.perfcake.message.generator; import org.perfcake.PerfCakeConst; import org.perfcake.message.Message; import org.perfcake.message.MessageTemplate; import org.perfcake.message.ReceivedMessage; import org.perfcake.message.correlator.Correlator; import org.perfcake.message.sender.MessageSender; import org.perfcake.message.sender.MessageSenderManager; import org.perfcake.message.sequence.SequenceManager; import org.perfcake.reporting.MeasurementUnit; import org.perfcake.reporting.ReportManager; import org.perfcake.validation.ValidationManager; import org.perfcake.validation.ValidationTask; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.Serializable; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.concurrent.Semaphore; /** * Executes a single task of sending messages from the message store * using instances of {@link MessageSender} provided by message sender manager (see {@link org.perfcake.message.sender.MessageSenderManager}), * receiving the message sender's response and handling the reporting and response message validation. * Sender task is not part of the public API, it is used from generators. * * @author <a href="mailto:[email protected]">Pavel Macík</a> * @author <a href="mailto:[email protected]">Martin Večeřa</a> * @see org.perfcake.message.sender.MessageSenderManager */ public class SenderTask implements Runnable { /** * Sender task's logger. */ private static final Logger log = LogManager.getLogger(SenderTask.class); /** * Reference to a message sender manager that is providing the message senders. */ private MessageSenderManager senderManager; /** * Reference to a message store where the messages are taken from. */ private List<MessageTemplate> messageStore; /** * Reference to a report manager. */ private ReportManager reportManager; /** * A reference to the current validator manager. It is used to validate message responses. */ private ValidationManager validationManager; /** * A reference to the current sequence manager. This is used for determining message specific sequence values. */ private SequenceManager sequenceManager; /** * Controls the amount of prepared tasks in a buffer. */ private final CanalStreet canalStreet; /** * The time when the task was enqueued. */ private long enqueueTime = System.nanoTime(); /** * Correlator to correlate message received from a separate channel. */ private Correlator correlator = null; /** * A response matched by a correlator. */ private Serializable correlatedResponse = null; /** * Synchronize on waiting for a message from a correlator. * Must be set before correlator is used. */ private Semaphore waitForResponse; /** * Creates a new task to send a message. * There is a communication channel established that allows and requires the sender task to report the task completion and any possible error. * The visibility of this constructor is limited as it is not intended for normal use. * To obtain a new instance of a sender task properly initialized call * {@link org.perfcake.message.generator.AbstractMessageGenerator#newSenderTask(java.util.concurrent.Semaphore)}. * * @param canalStreet * The communication channel between this sender task instance and a generator. */ protected SenderTask(final CanalStreet canalStreet) { this.canalStreet = canalStreet; } private Serializable sendMessage(final MessageSender sender, final Message message, final Properties messageAttributes, final MeasurementUnit mu) { try { sender.preSend(message, messageAttributes); } catch (final Exception e) { if (log.isErrorEnabled()) { log.error("Unable to initialize sending of a message: ", e); } canalStreet.senderError(e); } mu.startMeasure(); Serializable result = null; try { result = sender.send(message, mu); } catch (final Exception e) { mu.setFailure(e); if (log.isErrorEnabled()) { log.error("Unable to send a message: ", e); } canalStreet.senderError(e); } mu.stopMeasure(); try { sender.postSend(message); } catch (final Exception e) { if (log.isErrorEnabled()) { log.error("Unable to finish sending of a message: ", e); } canalStreet.senderError(e); } return result; } /** * Executes the scheduled sender task. This is supposed to be controlled by an enclosing thread. */ @Override public void run() { assert messageStore != null && reportManager != null && validationManager != null && senderManager != null : "SenderTask was not properly initialized."; final Properties messageAttributes = sequenceManager != null ? sequenceManager.getSnapshot() : new Properties(); MessageSender sender = null; ReceivedMessage receivedMessage; try { final MeasurementUnit mu = reportManager.newMeasurementUnit(); long requestSize = 0; long responseSize = 0; if (mu != null) { mu.setEnqueueTime(enqueueTime); if (messageAttributes != null) { mu.appendResult(PerfCakeConst.ATTRIBUTES_TAG, messageAttributes); messageAttributes.put(PerfCakeConst.ITERATION_NUMBER_PROPERTY, String.valueOf(mu.getIteration())); } mu.appendResult(PerfCakeConst.THREADS_TAG, reportManager.getRunInfo().getThreads()); sender = senderManager.acquireSender(); final Iterator<MessageTemplate> iterator = messageStore.iterator(); if (iterator.hasNext()) { while (iterator.hasNext()) { final MessageTemplate messageToSend = iterator.next(); final Message currentMessage = messageToSend.getFilteredMessage(messageAttributes); final long multiplicity = messageToSend.getMultiplicity(); requestSize = requestSize + (currentMessage.getPayload().toString().length() * multiplicity); for (int i = 0; i < multiplicity; i++) { receivedMessage = new ReceivedMessage(sendMessage(sender, currentMessage, messageAttributes, mu), messageToSend, currentMessage, messageAttributes); if (receivedMessage.getResponse() != null) { responseSize = responseSize + receivedMessage.getResponse().toString().length(); } if (validationManager.isEnabled()) { validationManager.submitValidationTask(new ValidationTask(Thread.currentThread().getName(), receivedMessage)); } } } } else { receivedMessage = new ReceivedMessage(sendMessage(sender, null, messageAttributes, mu), null, null, messageAttributes); if (validationManager.isEnabled()) { validationManager.submitValidationTask(new ValidationTask(Thread.currentThread().getName(), receivedMessage)); } } senderManager.releaseSender(sender); // !!! important !!! sender = null; mu.appendResult(PerfCakeConst.REQUEST_SIZE_TAG, requestSize); mu.appendResult(PerfCakeConst.RESPONSE_SIZE_TAG, responseSize); reportManager.report(mu); } } catch (final Exception e) { e.printStackTrace(); } finally { canalStreet.acknowledgeSend(); if (sender != null) { senderManager.releaseSender(sender); } } } /** * Notifies the sender task of receiving a response from a separate message channel. * This is called from {@link org.perfcake.message.correlator.Correlator} when {@link org.perfcake.message.receiver.Receiver} is used. * * @param response * The response corresponding to the original request. */ public void registerResponse(final Serializable response) { correlatedResponse = response; waitForResponse.release(); } /** * Configures a {@link org.perfcake.message.sender.MessageSenderManager} for the sender task. * * @param senderManager * {@link org.perfcake.message.sender.MessageSenderManager} to be used by the sender task. */ protected void setSenderManager(final MessageSenderManager senderManager) { this.senderManager = senderManager; } /** * Configures a message store for the sender task. * * @param messageStore * Message store to be used by the sender task. */ protected void setMessageStore(final List<MessageTemplate> messageStore) { this.messageStore = messageStore; } /** * Configures a {@link org.perfcake.reporting.ReportManager} for the sender task. * * @param reportManager * {@link org.perfcake.reporting.ReportManager} to be used by the sender task. */ protected void setReportManager(final ReportManager reportManager) { this.reportManager = reportManager; } /** * Configures a {@link org.perfcake.validation.ValidationManager} for the sender task. * * @param validationManager * {@link org.perfcake.validation.ValidationManager} to be used by the sender task. */ protected void setValidationManager(final ValidationManager validationManager) { this.validationManager = validationManager; } /** * Configures a {@link SequenceManager} for the sender task. * * @param sequenceManager * {@link SequenceManager} to be used by the sender task. */ public void setSequenceManager(final SequenceManager sequenceManager) { this.sequenceManager = sequenceManager; } /** * Sets the correlator that is used to notify us about receiving a response from a separate message channel. * * @param correlator * The correlator to be used. */ public void setCorrelator(final Correlator correlator) { waitForResponse = new Semaphore(0); this.correlator = correlator; } }
#196 sender task support for correlation
perfcake/src/main/java/org/perfcake/message/generator/SenderTask.java
#196 sender task support for correlation
Java
apache-2.0
ec9b1bb19b043861007ebe620ef74d6bdf023acc
0
quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus
package io.quarkus.arc.processor; import io.quarkus.arc.ActivateRequestContextInterceptor; import io.quarkus.arc.InjectableRequestContextController; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import javax.enterprise.context.BeforeDestroyed; import javax.enterprise.context.Destroyed; import javax.enterprise.context.Initialized; import javax.enterprise.context.control.ActivateRequestContext; import javax.enterprise.inject.Any; import javax.enterprise.inject.Default; import javax.enterprise.inject.Intercepted; import javax.inject.Named; import org.jboss.jandex.AnnotationInstance; import org.jboss.jandex.ClassInfo; import org.jboss.jandex.CompositeIndex; import org.jboss.jandex.DotName; import org.jboss.jandex.Index; import org.jboss.jandex.IndexView; import org.jboss.jandex.Indexer; import org.jboss.jandex.Type; import org.jboss.logging.Logger; public final class BeanArchives { private static final Logger LOGGER = Logger.getLogger(BeanArchives.class); /** * * @param applicationIndexes * @return the final bean archive index */ public static IndexView buildBeanArchiveIndex(IndexView... applicationIndexes) { List<IndexView> indexes = new ArrayList<>(); Collections.addAll(indexes, applicationIndexes); indexes.add(buildAdditionalIndex()); return new IndexWrapper(CompositeIndex.create(indexes)); } private static IndexView buildAdditionalIndex() { Indexer indexer = new Indexer(); // CDI API index(indexer, ActivateRequestContext.class.getName()); index(indexer, Default.class.getName()); index(indexer, Any.class.getName()); index(indexer, Named.class.getName()); index(indexer, Initialized.class.getName()); index(indexer, BeforeDestroyed.class.getName()); index(indexer, Destroyed.class.getName()); index(indexer, Intercepted.class.getName()); // Arc built-in beans index(indexer, ActivateRequestContextInterceptor.class.getName()); index(indexer, InjectableRequestContextController.class.getName()); return indexer.complete(); } /** * This wrapper is used to index JDK classes on demand. */ static class IndexWrapper implements IndexView { private final Map<DotName, Optional<ClassInfo>> additionalClasses; private final IndexView index; public IndexWrapper(IndexView index) { this.index = index; this.additionalClasses = new ConcurrentHashMap<>(); } @Override public Collection<ClassInfo> getKnownClasses() { if (additionalClasses.isEmpty()) { return index.getKnownClasses(); } Collection<ClassInfo> known = index.getKnownClasses(); Collection<ClassInfo> additional = additionalClasses.values().stream().filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList()); List<ClassInfo> all = new ArrayList<>(known.size() + additional.size()); all.addAll(known); all.addAll(additional); return all; } @Override public ClassInfo getClassByName(DotName className) { ClassInfo classInfo = index.getClassByName(className); if (classInfo == null) { classInfo = additionalClasses.computeIfAbsent(className, this::computeAdditional).orElse(null); } return classInfo; } @Override public Collection<ClassInfo> getKnownDirectSubclasses(DotName className) { if (additionalClasses.isEmpty()) { return index.getKnownDirectSubclasses(className); } Set<ClassInfo> directSubclasses = new HashSet<ClassInfo>(index.getKnownDirectSubclasses(className)); for (Optional<ClassInfo> additional : additionalClasses.values()) { if (additional.isPresent() && className.equals(additional.get().superName())) { directSubclasses.add(additional.get()); } } return directSubclasses; } @Override public Collection<ClassInfo> getAllKnownSubclasses(DotName className) { if (additionalClasses.isEmpty()) { return index.getAllKnownSubclasses(className); } final Set<ClassInfo> allKnown = new HashSet<ClassInfo>(); final Set<DotName> processedClasses = new HashSet<DotName>(); getAllKnownSubClasses(className, allKnown, processedClasses); return allKnown; } @Override public Collection<ClassInfo> getKnownDirectImplementors(DotName className) { if (additionalClasses.isEmpty()) { return index.getKnownDirectImplementors(className); } Set<ClassInfo> directImplementors = new HashSet<ClassInfo>(index.getKnownDirectImplementors(className)); for (Optional<ClassInfo> additional : additionalClasses.values()) { if (!additional.isPresent()) { continue; } for (Type interfaceType : additional.get().interfaceTypes()) { if (className.equals(interfaceType.name())) { directImplementors.add(additional.get()); break; } } } return directImplementors; } @Override public Collection<ClassInfo> getAllKnownImplementors(DotName interfaceName) { if (additionalClasses.isEmpty()) { return index.getAllKnownImplementors(interfaceName); } final Set<ClassInfo> allKnown = new HashSet<ClassInfo>(); final Set<DotName> subInterfacesToProcess = new HashSet<DotName>(); final Set<DotName> processedClasses = new HashSet<DotName>(); subInterfacesToProcess.add(interfaceName); while (!subInterfacesToProcess.isEmpty()) { final Iterator<DotName> toProcess = subInterfacesToProcess.iterator(); DotName name = toProcess.next(); toProcess.remove(); processedClasses.add(name); getKnownImplementors(name, allKnown, subInterfacesToProcess, processedClasses); } return allKnown; } @Override public Collection<AnnotationInstance> getAnnotations(DotName annotationName) { return index.getAnnotations(annotationName); } private void getAllKnownSubClasses(DotName className, Set<ClassInfo> allKnown, Set<DotName> processedClasses) { final Set<DotName> subClassesToProcess = new HashSet<DotName>(); subClassesToProcess.add(className); while (!subClassesToProcess.isEmpty()) { final Iterator<DotName> toProcess = subClassesToProcess.iterator(); DotName name = toProcess.next(); toProcess.remove(); processedClasses.add(name); getAllKnownSubClasses(name, allKnown, subClassesToProcess, processedClasses); } } private void getAllKnownSubClasses(DotName name, Set<ClassInfo> allKnown, Set<DotName> subClassesToProcess, Set<DotName> processedClasses) { final Collection<ClassInfo> directSubclasses = getKnownDirectSubclasses(name); if (directSubclasses != null) { for (final ClassInfo clazz : directSubclasses) { final DotName className = clazz.name(); if (!processedClasses.contains(className)) { allKnown.add(clazz); subClassesToProcess.add(className); } } } } private void getKnownImplementors(DotName name, Set<ClassInfo> allKnown, Set<DotName> subInterfacesToProcess, Set<DotName> processedClasses) { final Collection<ClassInfo> list = getKnownDirectImplementors(name); if (list != null) { for (final ClassInfo clazz : list) { final DotName className = clazz.name(); if (!processedClasses.contains(className)) { if (Modifier.isInterface(clazz.flags())) { subInterfacesToProcess.add(className); } else { if (!allKnown.contains(clazz)) { allKnown.add(clazz); processedClasses.add(className); getAllKnownSubClasses(className, allKnown, processedClasses); } } } } } } private Optional<ClassInfo> computeAdditional(DotName className) { LOGGER.debugf("Index: %s", className); Indexer indexer = new Indexer(); if (BeanArchives.index(indexer, className.toString())) { Index index = indexer.complete(); return Optional.of(index.getClassByName(className)); } else { // Note that ConcurrentHashMap does not allow null to be used as a value return Optional.empty(); } } } static boolean index(Indexer indexer, String className) { try (InputStream stream = BeanProcessor.class.getClassLoader() .getResourceAsStream(className.replace('.', '/') + ".class")) { indexer.index(stream); return true; } catch (IOException e) { LOGGER.warnf("Failed to index %s: %s", className, e.getMessage()); return false; } } }
independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/BeanArchives.java
package io.quarkus.arc.processor; import io.quarkus.arc.ActivateRequestContextInterceptor; import io.quarkus.arc.InjectableRequestContextController; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import javax.enterprise.context.BeforeDestroyed; import javax.enterprise.context.Destroyed; import javax.enterprise.context.Initialized; import javax.enterprise.context.control.ActivateRequestContext; import javax.enterprise.inject.Any; import javax.enterprise.inject.Default; import javax.enterprise.inject.Intercepted; import javax.inject.Named; import org.jboss.jandex.AnnotationInstance; import org.jboss.jandex.ClassInfo; import org.jboss.jandex.CompositeIndex; import org.jboss.jandex.DotName; import org.jboss.jandex.Index; import org.jboss.jandex.IndexView; import org.jboss.jandex.Indexer; import org.jboss.jandex.Type; public final class BeanArchives { /** * * @param applicationIndexes * @return the final bean archive index */ public static IndexView buildBeanArchiveIndex(IndexView... applicationIndexes) { List<IndexView> indexes = new ArrayList<>(); Collections.addAll(indexes, applicationIndexes); indexes.add(buildAdditionalIndex()); return new IndexWrapper(CompositeIndex.create(indexes)); } private static IndexView buildAdditionalIndex() { Indexer indexer = new Indexer(); // CDI API index(indexer, ActivateRequestContext.class.getName()); index(indexer, Default.class.getName()); index(indexer, Any.class.getName()); index(indexer, Named.class.getName()); index(indexer, Initialized.class.getName()); index(indexer, BeforeDestroyed.class.getName()); index(indexer, Destroyed.class.getName()); index(indexer, Intercepted.class.getName()); // Arc built-in beans index(indexer, ActivateRequestContextInterceptor.class.getName()); index(indexer, InjectableRequestContextController.class.getName()); return indexer.complete(); } /** * This wrapper is used to index JDK classes on demand. */ static class IndexWrapper implements IndexView { private final Map<DotName, ClassInfo> additionalClasses; private final IndexView index; public IndexWrapper(IndexView index) { this.index = index; this.additionalClasses = new ConcurrentHashMap<>(); } @Override public Collection<ClassInfo> getKnownClasses() { return index.getKnownClasses(); } @Override public ClassInfo getClassByName(DotName className) { ClassInfo classInfo = index.getClassByName(className); if (classInfo == null) { return additionalClasses.computeIfAbsent(className, name -> { BeanProcessor.LOGGER.debugf("Index: %s", className); Indexer indexer = new Indexer(); BeanArchives.index(indexer, className.toString()); Index index = indexer.complete(); return index.getClassByName(name); }); } return classInfo; } @Override public Collection<ClassInfo> getKnownDirectSubclasses(DotName className) { if (additionalClasses.isEmpty()) { return index.getKnownDirectSubclasses(className); } Set<ClassInfo> directSubclasses = new HashSet<ClassInfo>(index.getKnownDirectSubclasses(className)); for (ClassInfo additional : additionalClasses.values()) { if (className.equals(additional.superName())) { directSubclasses.add(additional); } } return directSubclasses; } @Override public Collection<ClassInfo> getAllKnownSubclasses(DotName className) { if (additionalClasses.isEmpty()) { return index.getAllKnownSubclasses(className); } final Set<ClassInfo> allKnown = new HashSet<ClassInfo>(); final Set<DotName> processedClasses = new HashSet<DotName>(); getAllKnownSubClasses(className, allKnown, processedClasses); return allKnown; } @Override public Collection<ClassInfo> getKnownDirectImplementors(DotName className) { if (additionalClasses.isEmpty()) { return index.getKnownDirectImplementors(className); } Set<ClassInfo> directImplementors = new HashSet<ClassInfo>(index.getKnownDirectImplementors(className)); for (ClassInfo additional : additionalClasses.values()) { for (Type interfaceType : additional.interfaceTypes()) { if (className.equals(interfaceType.name())) { directImplementors.add(additional); break; } } } return directImplementors; } @Override public Collection<ClassInfo> getAllKnownImplementors(DotName interfaceName) { if (additionalClasses.isEmpty()) { return index.getAllKnownImplementors(interfaceName); } final Set<ClassInfo> allKnown = new HashSet<ClassInfo>(); final Set<DotName> subInterfacesToProcess = new HashSet<DotName>(); final Set<DotName> processedClasses = new HashSet<DotName>(); subInterfacesToProcess.add(interfaceName); while (!subInterfacesToProcess.isEmpty()) { final Iterator<DotName> toProcess = subInterfacesToProcess.iterator(); DotName name = toProcess.next(); toProcess.remove(); processedClasses.add(name); getKnownImplementors(name, allKnown, subInterfacesToProcess, processedClasses); } return allKnown; } @Override public Collection<AnnotationInstance> getAnnotations(DotName annotationName) { return index.getAnnotations(annotationName); } private void getAllKnownSubClasses(DotName className, Set<ClassInfo> allKnown, Set<DotName> processedClasses) { final Set<DotName> subClassesToProcess = new HashSet<DotName>(); subClassesToProcess.add(className); while (!subClassesToProcess.isEmpty()) { final Iterator<DotName> toProcess = subClassesToProcess.iterator(); DotName name = toProcess.next(); toProcess.remove(); processedClasses.add(name); getAllKnownSubClasses(name, allKnown, subClassesToProcess, processedClasses); } } private void getAllKnownSubClasses(DotName name, Set<ClassInfo> allKnown, Set<DotName> subClassesToProcess, Set<DotName> processedClasses) { final Collection<ClassInfo> directSubclasses = getKnownDirectSubclasses(name); if (directSubclasses != null) { for (final ClassInfo clazz : directSubclasses) { final DotName className = clazz.name(); if (!processedClasses.contains(className)) { allKnown.add(clazz); subClassesToProcess.add(className); } } } } private void getKnownImplementors(DotName name, Set<ClassInfo> allKnown, Set<DotName> subInterfacesToProcess, Set<DotName> processedClasses) { final Collection<ClassInfo> list = getKnownDirectImplementors(name); if (list != null) { for (final ClassInfo clazz : list) { final DotName className = clazz.name(); if (!processedClasses.contains(className)) { if (Modifier.isInterface(clazz.flags())) { subInterfacesToProcess.add(className); } else { if (!allKnown.contains(clazz)) { allKnown.add(clazz); processedClasses.add(className); getAllKnownSubClasses(className, allKnown, processedClasses); } } } } } } } static void index(Indexer indexer, String className) { try (InputStream stream = BeanProcessor.class.getClassLoader() .getResourceAsStream(className.replace('.', '/') + ".class")) { indexer.index(stream); } catch (IOException e) { throw new IllegalStateException("Failed to index: " + className, e); } } }
BeanArchives.index() should never throw ISE - resolves #3748
independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/BeanArchives.java
BeanArchives.index() should never throw ISE
Java
apache-2.0
f3b2aec512931287274decc8881b4e626a1bab5e
0
apache/velocity-tools,apache/velocity-tools
package org.apache.velocity.tools.view.tools; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import javax.servlet.http.HttpServletRequest; import org.apache.velocity.tools.view.context.ViewContext; /** * <p>browser-sniffing tool (session or request scope requested, session scope advised).</p> * <p></p> * <p><b>Usage:</b></p> * <p>BrowserSniffer defines properties that are used to test the client browser, operating system, device... * Apart from properties related to versioning, all properties are booleans.</p> * <p>The following properties are available:</p> * <ul> * <li><i>Versioning:</i>version majorVersion minorVersion geckoVersion</li> * <li><i>Browser:</i>mosaic netscape nav2 nav3 nav4 nav4up nav45 nav45up nav6 nav6up navgold firefox safari * ie ie3 ie4 ie4up ie5 ie5up ie55 ie55up ie6 opera opera3 opera4 opera5 opera6 opera7 lynx links * aol aol3 aol4 aol5 aol6 neoplanet neoplanet2 amaya icab avantgo emacs mozilla gecko webtv staroffice * lotusnotes konqueror</li> * <li><i>Operating systems:</i>win16 win3x win31 win95 win98 winnt windows win32 win2k winxp winme dotnet * mac macosx mac68k macppc os2 unix sun sun4 sun5 suni86 irix irix5 irix6 hpux hpux9 hpux10 aix aix1 aix2 aix3 aix4 * linux sco unixware mpras reliant dec sinix freebsd bsd vms x11 amiga</li> * <li><i>Devices:</i>palm audrey iopener wap blackberry</li> * <li><i>Features:</i>javascript css css1 css2 dom0 dom1 dom2</li> * <li><i>Special:</i>robot (true if the page is requested by a robot, i.e. when one of the following properties is true: * wget getright yahoo altavista lycos infoseek lwp webcrawler linkexchange slurp google java) * </ul> * * Thanks to Lee Semel ([email protected]), the author of the HTTP::BrowserDetect Perl module. * See also http://www.zytrax.com/tech/web/browser_ids.htm and http://www.mozilla.org/docs/web-developer/sniffer/browser_type.html * * @author <a href="mailto:[email protected]">Claude Brisson</a> * @since VelocityTools 1.2 * @version $Revision$ $Date$ */ public class BrowserSnifferTool { private String userAgent = null; private String version = null; private int majorVersion = -1; private int minorVersion = -1; private String geckoVersion = null; private int geckoMajorVersion = -1; private int geckoMinorVersion = -1; public BrowserSnifferTool() { } public void init(Object initData) { HttpServletRequest req; if(initData instanceof ViewContext) { req = ((ViewContext)initData).getRequest(); } else if(initData instanceof HttpServletRequest) { req = (HttpServletRequest)initData; } else { throw new IllegalArgumentException("Was expecting " + ViewContext.class + " or " + HttpServletRequest.class); } userAgent = req.getHeader("User-Agent").toLowerCase(); } /* Generic getter for unknown tests */ public boolean get(String key) { return test(key); } /* Versioning */ public String getVersion() { parseVersion(); return version; } public int getMajorVersion() { parseVersion(); return majorVersion; } public int getMinorVersion() { parseVersion(); return minorVersion; } public String getGeckoVersion() { parseVersion(); return geckoVersion; } public int getGeckoMajorVersion() { parseVersion(); return geckoMajorVersion; } public int getGeckoMinorVersion() { parseVersion(); return geckoMinorVersion; } /* Browsers */ public boolean getGecko() { return test("gecko"); } public boolean getFirefox() { return test("firefox") || test("firebird") || test("phoenix"); } public boolean getSafari() { return test("safari") || test("applewebkit"); } public boolean getNetscape() { return !getFirefox() && !getSafari() && test("mozilla") && !test("spoofer") && !test("compatible") && !test("opera") && !test("webtv") && !test("hotjava"); } public boolean getNav2() { return getNetscape() && getMajorVersion() == 2; } public boolean getNav3() { return getNetscape() && getMajorVersion() == 3; } public boolean getNav4() { return getNetscape() && getMajorVersion() == 4; } public boolean getNav4up() { return getNetscape() && getMajorVersion() >= 4; } public boolean getNav45() { return getNetscape() && getMajorVersion() == 4 && getMinorVersion() == 5; } public boolean getNav45up() { return getNetscape() && getMajorVersion() >= 5 || getNav4() && getMinorVersion() >= 5; } public boolean getNavgold() { return test("gold"); } public boolean getNav6() { return getNetscape() && getMajorVersion() == 5; /* sic */ } public boolean getNav6up() { return getNetscape() && getMajorVersion() >= 5; } public boolean getMozilla() { return getNetscape() && getGecko(); } public boolean getIe() { return test("msie") && !test("opera") || test("microsoft internet explorer"); } public boolean getIe3() { return getIe() && getMajorVersion() < 4; } public boolean getIe4() { return getIe() && getMajorVersion() == 4; } public boolean getIe4up() { return getIe() && getMajorVersion() >= 4; } public boolean getIe5() { return getIe() && getMajorVersion() == 5; } public boolean getIe5up() { return getIe() && getMajorVersion() >= 5; } public boolean getIe55() { return getIe() && getMajorVersion() == 5 && getMinorVersion() >= 5; } public boolean getIe55up() { return (getIe5() && getMinorVersion() >= 5) || (getIe() && getMajorVersion() >= 6); } public boolean getIe6() { return getIe() && getMajorVersion() == 6; } public boolean getIe6up() { return getIe() && getMajorVersion() >= 6; } public boolean getNeoplanet() { return test("neoplanet"); } public boolean getNeoplanet2() { return getNeoplanet() && test("2."); } public boolean getAol() { return test("aol"); } public boolean getAol3() { return test("aol 3.0") || getAol() && getIe3(); } public boolean getAol4() { return test("aol 4.0") || getAol() && getIe4(); } public boolean getAol5() { return test("aol 5.0"); } public boolean getAol6() { return test("aol 6.0"); } public boolean getAolTV() { return test("navio") || test("navio_aoltv"); } public boolean getOpera() { return test("opera"); } public boolean getOpera3() { return test("opera 3") || test("opera/3"); } public boolean getOpera4() { return test("opera 4") || test("opera/4"); } public boolean getOpera5() { return test("opera 5") || test("opera/5"); } public boolean getOpera6() { return test("opera 6") || test("opera/6"); } public boolean getOpera7() { return test("opera 7") || test("opera/7"); } public boolean getHotjava() { return test("hotjava"); } public boolean getHotjava3() { return getHotjava() && getMajorVersion() == 3; } public boolean getHotjava3up() { return getHotjava() && getMajorVersion() >= 3; } public boolean getAmaya() { return test("amaya"); } public boolean getCurl() { return test("libcurl"); } public boolean getStaroffice() { return test("staroffice"); } public boolean getIcab() { return test("icab"); } public boolean getLotusnotes() { return test("lotus-notes"); } public boolean getKonqueror() { return test("konqueror"); } public boolean getLynx() { return test("lynx"); } public boolean getLinks() { return test("links"); } public boolean getWebTV() { return test("webtv"); } public boolean getMosaic() { return test("mosaic"); } public boolean getWget() { return test("wget"); } public boolean getGetright() { return test("getright"); } public boolean getLwp() { return test("libwww-perl") || test("lwp-"); } public boolean getYahoo() { return test("yahoo"); } public boolean getGoogle() { return test("google"); } public boolean getJava() { return test("java") || test("jdk") || test("httpunit"); } public boolean getAltavista() { return test("altavista"); } public boolean getScooter() { return test("scooter"); } public boolean getLycos() { return test("lycos"); } public boolean getInfoseek() { return test("infoseek"); } public boolean getWebcrawler() { return test("webcrawler"); } public boolean getLinkexchange() { return test("lecodechecker"); } public boolean getSlurp() { return test("slurp"); } public boolean getRobot() { return getWget() || getGetright() || getLwp() || getYahoo() || getGoogle() || getAltavista() || getScooter() || getLycos() || getInfoseek() || getWebcrawler() || getLinkexchange() || test("bot") || test("spider") || test("crawl") || test("agent") || test("seek") || test("search") || test("reap") || test("worm") || test("find") || test("index") || test("copy") || test("fetch") || test("ia_archive") || test("zyborg"); } /* Devices */ public boolean getBlackberry() { return test("blackberry"); } public boolean getAudrey() { return test("audrey"); } public boolean getIopener() { return test("i-opener"); } public boolean getAvantgo() { return test("avantgo"); } public boolean getPalm() { return getAvantgo() || test("palmos"); } public boolean getWap() { return test("up.browser") || test("nokia") || test("alcatel") || test("ericsson") || userAgent.indexOf("sie-") == 0 || test("wmlib") || test(" wap") || test("wap ") || test("wap/") || test("-wap") || test("wap-") || userAgent.indexOf("wap") == 0 || test("wapper") || test("zetor"); } /* Operating System */ public boolean getWin16() { return test("win16") || test("16bit") || test("windows 3") || test("windows 16-bit"); } public boolean getWin3x() { return test("win16") || test("windows 3") || test("windows 16-bit"); } public boolean getWin31() { return test("win16") || test("windows 3.1") || test("windows 16-bit"); } public boolean getWin95() { return test("win95") || test("windows 95"); } public boolean getWin98() { return test("win98") || test("windows 98"); } public boolean getWinnt() { return test("winnt") || test("windows nt") || test("nt4") || test("nt3"); } public boolean getWin2k() { return test("nt 5.0") || test("nt5"); } public boolean getWinxp() { return test("nt 5.1"); } public boolean getDotnet() { return test(".net clr"); } public boolean getWinme() { return test("win 9x 4.90"); } public boolean getWin32() { return getWin95() || getWin98() || getWinnt() || getWin2k() || getWinxp() || getWinme() || test("win32"); } public boolean getWindows() { return getWin16() || getWin31() || getWin95() || getWin98() || getWinnt() || getWin32() || getWin2k() || getWinme() || test("win"); } public boolean getMac() { return test("macintosh") || test("mac_"); } public boolean getMacosx() { return test("macintosh") || test("mac os x"); } public boolean getMac68k() { return getMac() && (test("68k") || test("68000")); } public boolean getMacppc() { return getMac() && (test("ppc") || test("powerpc")); } public boolean getAmiga() { return test("amiga"); } public boolean getEmacs() { return test("emacs"); } public boolean getOs2() { return test("os/2"); } public boolean getSun() { return test("sun"); } public boolean getSun4() { return test("sunos 4"); } public boolean getSun5() { return test("sunos 5"); } public boolean getSuni86() { return getSun() && test("i86"); } public boolean getIrix() { return test("irix"); } public boolean getIrix5() { return test("irix5"); } public boolean getIrix6() { return test("irix6"); } public boolean getHpux() { return test("hp-ux"); } public boolean getHpux9() { return getHpux() && test("09."); } public boolean getHpux10() { return getHpux() && test("10."); } public boolean getAix() { return test("aix"); } public boolean getAix1() { return test("aix 1"); } public boolean getAix2() { return test("aix 2"); } public boolean getAix3() { return test("aix 3"); } public boolean getAix4() { return test("aix 4"); } public boolean getLinux() { return test("linux"); } public boolean getSco() { return test("sco") || test("unix_sv"); } public boolean getUnixware() { return test("unix_system_v"); } public boolean getMpras() { return test("ncr"); } public boolean getReliant() { return test("reliantunix"); } public boolean getDec() { return test("dec") || test("osf1") || test("delalpha") || test("alphaserver") || test("ultrix") || test("alphastation"); } public boolean getSinix() { return test("sinix"); } public boolean getFreebsd() { return test("freebsd"); } public boolean getBsd() { return test("bsd"); } public boolean getX11() { return test("x11"); } public boolean getUnix() { return getX11() || getSun() || getIrix() || getHpux() || getSco() || getUnixware() || getMpras() || getReliant() || getDec() || getLinux() || getBsd() || test("unix"); } public boolean getVMS() { return test("vax") || test("openvms"); } /* Features */ /* Since support of those features is often partial, the sniffer returns true when a consequent subset is supported. */ public boolean getCss() { return (getIe() && getMajorVersion() >= 4) || (getNetscape() && getMajorVersion() >= 4) || getGecko() || getKonqueror() || (getOpera() && getMajorVersion() >= 3) || getSafari() || getLinks(); } public boolean getCss1() { return getCss(); } public boolean getCss2() { return getIe() && (getMac() && getMajorVersion() >= 5) || (getWin32() && getMajorVersion() >= 6) || getGecko() || // && version >= ? (getOpera() && getMajorVersion() >= 4) || (getSafari() && getMajorVersion() >= 2) || (getKonqueror() && getMajorVersion() >= 2); } public boolean getDom0() { return (getIe() && getMajorVersion() >= 3) || (getNetscape() && getMajorVersion() >= 2) || (getOpera() && getMajorVersion() >= 3) || getGecko() || getSafari() || getKonqueror(); } public boolean getDom1() { return (getIe() && getMajorVersion() >= 5) || getGecko() || (getSafari() && getMajorVersion() >= 2) || (getOpera() && getMajorVersion() >= 4) || (getKonqueror() && getMajorVersion() >= 2); } public boolean getDom2() { return (getIe() && getMajorVersion() >= 6) || (getMozilla() && getMajorVersion() >= 5.0) || (getOpera() && getMajorVersion() >= 7) || getFirefox(); } public boolean getJavascript() { return getDom0(); // good approximation } /* Helpers */ private boolean test(String key) { return userAgent.indexOf(key) != -1; } private void parseVersion() { try { if(version != null) { return; /* parsing of version already done */ } /* generic versionning */ Matcher v = Pattern.compile( "/" /* Version starts with a slash */ + "([A-Za-z]*" /* Eat any letters before the major version */ + "( [\\d]* )" /* Major version number is every digit before the first dot */ + "\\." /* The first dot */ + "( [\\d]* )" /* Minor version number is every digit after the first dot */ + "[^\\s]*)" /* Throw away the remaining */ , Pattern.COMMENTS).matcher(userAgent); if(v.find()) { version = v.group(1); try { majorVersion = Integer.parseInt(v.group(2)); String minor = v.group(3); if(minor.startsWith("0"))minorVersion = 0; else minorVersion = Integer.parseInt(minor); } catch(NumberFormatException nfe) {} } /* Firefox versionning */ if(test("firefox")) { Matcher fx = Pattern.compile( "/" + "(( [\\d]* )" /* Major version number is every digit before the first dot */ + "\\." /* The first dot */ + "( [\\d]* )" /* Minor version number is every digit after the first dot */ + "[^\\s]*)" /* Throw away the remaining */ , Pattern.COMMENTS) .matcher(userAgent); if(fx.find()) { version = fx.group(1); try { majorVersion = Integer.parseInt(fx.group(2)); String minor = fx.group(3); if(minor.startsWith("0"))minorVersion = 0; else minorVersion = Integer.parseInt(minor); } catch(NumberFormatException nfe) {} } } /* IE versionning */ if(test("compatible")) { Matcher ie = Pattern.compile( "compatible;" + "\\s*" + "\\w*" /* Browser name */ + "[\\s|/]" + "([A-Za-z]*" /* Eat any letters before the major version */ + "( [\\d]* )" /* Major version number is every digit before first dot */ + "\\." /* The first dot */ + "( [\\d]* )" /* Minor version number is digits after first dot */ + "[^\\s]*)" /* Throw away remaining dots and digits */ , Pattern.COMMENTS) .matcher(userAgent); if(ie.find()) { version = ie.group(1); try { majorVersion = Integer.parseInt(ie.group(2)); String minor = ie.group(3); if(minor.startsWith("0"))minorVersion = 0; else minorVersion = Integer.parseInt(minor); } catch(NumberFormatException nfe) {} } } /* Safari versionning*/ if(getSafari()) { Matcher safari = Pattern.compile( "safari/" + "(( [\\d]* )" /* Major version number is every digit before first dot */ + "(?:" + "\\." /* The first dot */ + " [\\d]* )?)" /* Minor version number is digits after first dot */ , Pattern.COMMENTS) .matcher(userAgent); if(safari.find()) { version = safari.group(1); try { int sv = Integer.parseInt(safari.group(2)); majorVersion = sv / 100; minorVersion = sv % 100; } catch(NumberFormatException nfe) {} } } /* Gecko-powered Netscape (i.e. Mozilla) versions */ if(getGecko() && getNetscape() && test("netscape")) { Matcher netscape = Pattern.compile( "netscape/" + "(( [\\d]* )" /* Major version number is every digit before the first dot */ + "\\." /* The first dot */ + "( [\\d]* )" /* Minor version number is every digit after the first dot */ + "[^\\s]*)" /* Throw away the remaining */ , Pattern.COMMENTS) .matcher(userAgent); if(netscape.find()) { version = netscape.group(1); try { majorVersion = Integer.parseInt(netscape.group(2)); String minor = netscape.group(3); if(minor.startsWith("0"))minorVersion = 0; else minorVersion = Integer.parseInt(minor); } catch(NumberFormatException nfe) {} } } /* last try if version not found */ if(version == null) { Matcher mv = Pattern.compile( "[\\w]+/" + "( [\\d]+ );" /* Major version number is every digit before the first dot */ , Pattern.COMMENTS) .matcher(userAgent); if(mv.find()) { version = mv.group(1); try { majorVersion = Integer.parseInt(version); minorVersion = 0; } catch(NumberFormatException nfe) {} } } /* gecko engine version */ if(getGecko()) { Matcher g = Pattern.compile( "\\([^)]*rv:(([\\d]*)\\.([\\d]*).*?)\\)" ).matcher(userAgent); if(g.find()) { geckoVersion = g.group(1); try { geckoMajorVersion = Integer.parseInt(g.group(2)); String minor = g.group(3); if(minor.startsWith("0"))geckoMinorVersion = 0; else geckoMinorVersion = Integer.parseInt(minor); } catch(NumberFormatException nfe) {} } } } catch(PatternSyntaxException nfe) { // where should I log ?! } } }
src/java/org/apache/velocity/tools/view/tools/BrowserSnifferTool.java
package org.apache.velocity.tools.view.tools; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import javax.servlet.http.HttpServletRequest; import org.apache.velocity.tools.view.context.ViewContext; /** * <p>browser-sniffing tool (session or request scope requested, session scope advised).</p> * <p></p> * <p><b>Usage:</b></p> * <p>BrowserSniffer defines properties that are used to test the client browser, operating system, device... * Apart from properties related to versioning, all properties are booleans.</p> * <p>The following properties are available:</p> * <ul> * <li><i>Versioning:</i>version majorVersion minorVersion geckoVersion</li> * <li><i>Browser:</i>mosaic netscape nav2 nav3 nav4 nav4up nav45 nav45up nav6 nav6up navgold firefox safari * ie ie3 ie4 ie4up ie5 ie5up ie55 ie55up ie6 opera opera3 opera4 opera5 opera6 opera7 lynx links * aol aol3 aol4 aol5 aol6 neoplanet neoplanet2 amaya icab avantgo emacs mozilla gecko webtv staroffice * lotusnotes konqueror</li> * <li><i>Operating systems:</i>win16 win3x win31 win95 win98 winnt windows win32 win2k winxp winme dotnet * mac macosx mac68k macppc os2 unix sun sun4 sun5 suni86 irix irix5 irix6 hpux hpux9 hpux10 aix aix1 aix2 aix3 aix4 * linux sco unixware mpras reliant dec sinix freebsd bsd vms x11 amiga</li> * <li><i>Devices:</i>palm audrey iopener wap blackberry</li> * <li><i>Features:</i>javascript css css1 css2 dom0 dom1 dom2</li> * <li><i>Special:</i>robot (true if the page is requested by a robot, i.e. when one of the following properties is true: * wget getright yahoo altavista lycos infoseek lwp webcrawler linkexchange slurp google java) * </ul> * * Thanks to Lee Semel ([email protected]), the author of the HTTP::BrowserDetect Perl module. * See also http://www.zytrax.com/tech/web/browser_ids.htm and http://www.mozilla.org/docs/web-developer/sniffer/browser_type.html * * @author <a href="mailto:[email protected]">Claude Brisson</a> * @since VelocityTools 1.2 * @version $Revision$ $Date$ */ public class BrowserSnifferTool { private String userAgent = null; private String version = null; private int majorVersion = -1; private int minorVersion = -1; private String geckoVersion = null; private int geckoMajorVersion = -1; private int geckoMinorVersion = -1; public BrowserSnifferTool() { } public void init(Object initData) { HttpServletRequest req; if(initData instanceof ViewContext) { req = ((ViewContext)initData).getRequest(); } else if(initData instanceof HttpServletRequest) { req = (HttpServletRequest)initData; } else { throw new IllegalArgumentException("Was expecting " + ViewContext.class + " or " + HttpServletRequest.class); } userAgent = req.getHeader("User-Agent").toLowerCase(); } /* Generic getter for unknown tests */ public boolean get(String key) { return test(key); } /* Versioning */ public String getVersion() { parseVersion(); return version; } public int getMajorVersion() { parseVersion(); return majorVersion; } public int getMinorVersion() { parseVersion(); return minorVersion; } public String getGeckoVersion() { parseVersion(); return geckoVersion; } public int getGeckoMajorVersion() { parseVersion(); return geckoMajorVersion; } public int getGeckoMinorVersion() { parseVersion(); return geckoMinorVersion; } /* Browsers */ public boolean getGecko() { return test("gecko"); } public boolean getFirefox() { return test("firefox") || test("firebird") || test("phoenix"); } public boolean getSafari() { return test("safari") || test("applewebkit"); } public boolean getNetscape() { return !getFirefox() && !getSafari() && test("mozilla") && !test("spoofer") && !test("compatible") && !test("opera") && !test("webtv") && !test("hotjava"); } public boolean getNav2() { return getNetscape() && getMajorVersion() == 2; } public boolean getNav3() { return getNetscape() && getMajorVersion() == 3; } public boolean getNav4() { return getNetscape() && getMajorVersion() == 4; } public boolean getNav4up() { return getNetscape() && getMajorVersion() >= 4; } public boolean getNav45() { return getNetscape() && getMajorVersion() == 4 && getMinorVersion() == 5; } public boolean getNav45up() { return getNetscape() && getMajorVersion() >= 5 || getNav4() && getMinorVersion() >= 5; } public boolean getNavgold() { return test("gold"); } public boolean getNav6() { return getNetscape() && getMajorVersion() == 5; /* sic */ } public boolean getNav6up() { return getNetscape() && getMajorVersion() >= 5; } public boolean getMozilla() { return getNetscape() && getGecko(); } public boolean getIe() { return test("msie") && !test("opera") || test("microsoft internet explorer"); } public boolean getIe3() { return getIe() && getMajorVersion() < 4; } public boolean getIe4() { return getIe() && getMajorVersion() == 4; } public boolean getIe4up() { return getIe() && getMajorVersion() >= 4; } public boolean getIe5() { return getIe() && getMajorVersion() == 5; } public boolean getIe5up() { return getIe() && getMajorVersion() >= 5; } public boolean getIe55() { return getIe() && getMajorVersion() == 5 && getMinorVersion() >= 5; } public boolean getIe55up() { return (getIe5() && getMinorVersion() >= 5) || (getIe() && getMajorVersion() >= 6); } public boolean getIe6() { return getIe() && getMajorVersion() == 6; } public boolean getIe6up() { return getIe() && getMajorVersion() >= 6; } public boolean getNeoplanet() { return test("neoplanet"); } public boolean getNeoplanet2() { return getNeoplanet() && test("2."); } public boolean getAol() { return test("aol"); } public boolean getAol3() { return test("aol 3.0") || getAol() && getIe3(); } public boolean getAol4() { return test("aol 4.0") || getAol() && getIe4(); } public boolean getAol5() { return test("aol 5.0"); } public boolean getAol6() { return test("aol 6.0"); } public boolean getAolTV() { return test("navio") || test("navio_aoltv"); } public boolean getOpera() { return test("opera"); } public boolean getOpera3() { return test("opera 3") || test("opera/3"); } public boolean getOpera4() { return test("opera 4") || test("opera/4"); } public boolean getOpera5() { return test("opera 5") || test("opera/5"); } public boolean getOpera6() { return test("opera 6") || test("opera/6"); } public boolean getOpera7() { return test("opera 7") || test("opera/7"); } public boolean getHotjava() { return test("hotjava"); } public boolean getHotjava3() { return getHotjava() && getMajorVersion() == 3; } public boolean getHotjava3up() { return getHotjava() && getMajorVersion() >= 3; } public boolean getAmaya() { return test("amaya"); } public boolean getCurl() { return test("libcurl"); } public boolean getStaroffice() { return test("staroffice"); } public boolean getIcab() { return test("icab"); } public boolean getLotusnotes() { return test("lotus-notes"); } public boolean getKonqueror() { return test("konqueror"); } public boolean getLynx() { return test("lynx"); } public boolean getLinks() { return test("links"); } public boolean getWebTV() { return test("webtv"); } public boolean getMosaic() { return test("mosaic"); } public boolean getWget() { return test("wget"); } public boolean getGetright() { return test("getright"); } public boolean getLwp() { return test("libwww-perl") || test("lwp-"); } public boolean getYahoo() { return test("yahoo"); } public boolean getGoogle() { return test("google"); } public boolean getJava() { return test("java") || test("jdk"); } public boolean getAltavista() { return test("altavista"); } public boolean getScooter() { return test("scooter"); } public boolean getLycos() { return test("lycos"); } public boolean getInfoseek() { return test("infoseek"); } public boolean getWebcrawler() { return test("webcrawler"); } public boolean getLinkexchange() { return test("lecodechecker"); } public boolean getSlurp() { return test("slurp"); } public boolean getRobot() { return getWget() || getGetright() || getLwp() || getYahoo() || getGoogle() || getAltavista() || getScooter() || getLycos() || getInfoseek() || getWebcrawler() || getLinkexchange() || test("bot") || test("spider") || test("crawl") || test("agent") || test("seek") || test("search") || test("reap") || test("worm") || test("find") || test("index") || test("copy") || test("fetch") || test("ia_archive") || test("zyborg"); } /* Devices */ public boolean getBlackberry() { return test("blackberry"); } public boolean getAudrey() { return test("audrey"); } public boolean getIopener() { return test("i-opener"); } public boolean getAvantgo() { return test("avantgo"); } public boolean getPalm() { return getAvantgo() || test("palmos"); } public boolean getWap() { return test("up.browser") || test("nokia") || test("alcatel") || test("ericsson") || userAgent.indexOf("sie-") == 0 || test("wmlib") || test(" wap") || test("wap ") || test("wap/") || test("-wap") || test("wap-") || userAgent.indexOf("wap") == 0 || test("wapper") || test("zetor"); } /* Operating System */ public boolean getWin16() { return test("win16") || test("16bit") || test("windows 3") || test("windows 16-bit"); } public boolean getWin3x() { return test("win16") || test("windows 3") || test("windows 16-bit"); } public boolean getWin31() { return test("win16") || test("windows 3.1") || test("windows 16-bit"); } public boolean getWin95() { return test("win95") || test("windows 95"); } public boolean getWin98() { return test("win98") || test("windows 98"); } public boolean getWinnt() { return test("winnt") || test("windows nt") || test("nt4") || test("nt3"); } public boolean getWin2k() { return test("nt 5.0") || test("nt5"); } public boolean getWinxp() { return test("nt 5.1"); } public boolean getDotnet() { return test(".net clr"); } public boolean getWinme() { return test("win 9x 4.90"); } public boolean getWin32() { return getWin95() || getWin98() || getWinnt() || getWin2k() || getWinxp() || getWinme() || test("win32"); } public boolean getWindows() { return getWin16() || getWin31() || getWin95() || getWin98() || getWinnt() || getWin32() || getWin2k() || getWinme() || test("win"); } public boolean getMac() { return test("macintosh") || test("mac_"); } public boolean getMacosx() { return test("macintosh") || test("mac os x"); } public boolean getMac68k() { return getMac() && (test("68k") || test("68000")); } public boolean getMacppc() { return getMac() && (test("ppc") || test("powerpc")); } public boolean getAmiga() { return test("amiga"); } public boolean getEmacs() { return test("emacs"); } public boolean getOs2() { return test("os/2"); } public boolean getSun() { return test("sun"); } public boolean getSun4() { return test("sunos 4"); } public boolean getSun5() { return test("sunos 5"); } public boolean getSuni86() { return getSun() && test("i86"); } public boolean getIrix() { return test("irix"); } public boolean getIrix5() { return test("irix5"); } public boolean getIrix6() { return test("irix6"); } public boolean getHpux() { return test("hp-ux"); } public boolean getHpux9() { return getHpux() && test("09."); } public boolean getHpux10() { return getHpux() && test("10."); } public boolean getAix() { return test("aix"); } public boolean getAix1() { return test("aix 1"); } public boolean getAix2() { return test("aix 2"); } public boolean getAix3() { return test("aix 3"); } public boolean getAix4() { return test("aix 4"); } public boolean getLinux() { return test("linux"); } public boolean getSco() { return test("sco") || test("unix_sv"); } public boolean getUnixware() { return test("unix_system_v"); } public boolean getMpras() { return test("ncr"); } public boolean getReliant() { return test("reliantunix"); } public boolean getDec() { return test("dec") || test("osf1") || test("delalpha") || test("alphaserver") || test("ultrix") || test("alphastation"); } public boolean getSinix() { return test("sinix"); } public boolean getFreebsd() { return test("freebsd"); } public boolean getBsd() { return test("bsd"); } public boolean getX11() { return test("x11"); } public boolean getUnix() { return getX11() || getSun() || getIrix() || getHpux() || getSco() || getUnixware() || getMpras() || getReliant() || getDec() || getLinux() || getBsd() || test("unix"); } public boolean getVMS() { return test("vax") || test("openvms"); } /* Features */ /* Since support of those features is often partial, the sniffer returns true when a consequent subset is supported. */ public boolean getCss() { return (getIe() && getMajorVersion() >= 4) || (getNetscape() && getMajorVersion() >= 4) || getGecko() || getKonqueror() || (getOpera() && getMajorVersion() >= 3) || getSafari() || getLinks(); } public boolean getCss1() { return getCss(); } public boolean getCss2() { return getIe() && (getMac() && getMajorVersion() >= 5) || (getWin32() && getMajorVersion() >= 6) || getGecko() || // && version >= ? (getOpera() && getMajorVersion() >= 4) || (getSafari() && getMajorVersion() >= 2) || (getKonqueror() && getMajorVersion() >= 2); } public boolean getDom0() { return (getIe() && getMajorVersion() >= 3) || (getNetscape() && getMajorVersion() >= 2) || (getOpera() && getMajorVersion() >= 3) || getGecko() || getSafari() || getKonqueror(); } public boolean getDom1() { return (getIe() && getMajorVersion() >= 5) || getGecko() || (getSafari() && getMajorVersion() >= 2) || (getOpera() && getMajorVersion() >= 4) || (getKonqueror() && getMajorVersion() >= 2); } public boolean getDom2() { return (getIe() && getMajorVersion() >= 6) || (getMozilla() && getMajorVersion() >= 5.0) || (getOpera() && getMajorVersion() >= 7) || getFirefox(); } public boolean getJavascript() { return getDom0(); // good approximation } /* Helpers */ private boolean test(String key) { return userAgent.indexOf(key) != -1; } private void parseVersion() { try { if(version != null) { return; /* parsing of version already done */ } /* generic versionning */ Matcher v = Pattern.compile( "/" /* Version starts with a slash */ + "([A-Za-z]*" /* Eat any letters before the major version */ + "( [\\d]* )" /* Major version number is every digit before the first dot */ + "\\." /* The first dot */ + "( [\\d]* )" /* Minor version number is every digit after the first dot */ + "[^\\s]*)" /* Throw away the remaining */ , Pattern.COMMENTS).matcher(userAgent); if(v.find()) { version = v.group(1); try { majorVersion = Integer.parseInt(v.group(2)); String minor = v.group(3); if(minor.startsWith("0"))minorVersion = 0; else minorVersion = Integer.parseInt(minor); } catch(NumberFormatException nfe) {} } /* Firefox versionning */ if(test("firefox")) { Matcher fx = Pattern.compile( "/" + "(( [\\d]* )" /* Major version number is every digit before the first dot */ + "\\." /* The first dot */ + "( [\\d]* )" /* Minor version number is every digit after the first dot */ + "[^\\s]*)" /* Throw away the remaining */ , Pattern.COMMENTS) .matcher(userAgent); if(fx.find()) { version = fx.group(1); try { majorVersion = Integer.parseInt(fx.group(2)); String minor = fx.group(3); if(minor.startsWith("0"))minorVersion = 0; else minorVersion = Integer.parseInt(minor); } catch(NumberFormatException nfe) {} } } /* IE versionning */ if(test("compatible")) { Matcher ie = Pattern.compile( "compatible;" + "\\s*" + "\\w*" /* Browser name */ + "[\\s|/]" + "([A-Za-z]*" /* Eat any letters before the major version */ + "( [\\d]* )" /* Major version number is every digit before first dot */ + "\\." /* The first dot */ + "( [\\d]* )" /* Minor version number is digits after first dot */ + "[^\\s]*)" /* Throw away remaining dots and digits */ , Pattern.COMMENTS) .matcher(userAgent); if(ie.find()) { version = ie.group(1); try { majorVersion = Integer.parseInt(ie.group(2)); String minor = ie.group(3); if(minor.startsWith("0"))minorVersion = 0; else minorVersion = Integer.parseInt(minor); } catch(NumberFormatException nfe) {} } } /* Safari versionning*/ if(getSafari()) { Matcher safari = Pattern.compile( "safari/" + "(( [\\d]* )" /* Major version number is every digit before first dot */ + "(?:" + "\\." /* The first dot */ + " [\\d]* )?)" /* Minor version number is digits after first dot */ , Pattern.COMMENTS) .matcher(userAgent); if(safari.find()) { version = safari.group(1); try { int sv = Integer.parseInt(safari.group(2)); majorVersion = sv / 100; minorVersion = sv % 100; } catch(NumberFormatException nfe) {} } } /* Gecko-powered Netscape (i.e. Mozilla) versions */ if(getGecko() && getNetscape() && test("netscape")) { Matcher netscape = Pattern.compile( "netscape/" + "(( [\\d]* )" /* Major version number is every digit before the first dot */ + "\\." /* The first dot */ + "( [\\d]* )" /* Minor version number is every digit after the first dot */ + "[^\\s]*)" /* Throw away the remaining */ , Pattern.COMMENTS) .matcher(userAgent); if(netscape.find()) { version = netscape.group(1); try { majorVersion = Integer.parseInt(netscape.group(2)); String minor = netscape.group(3); if(minor.startsWith("0"))minorVersion = 0; else minorVersion = Integer.parseInt(minor); } catch(NumberFormatException nfe) {} } } /* last try if version not found */ if(version == null) { Matcher mv = Pattern.compile( "[\\w]+/" + "( [\\d]+ );" /* Major version number is every digit before the first dot */ , Pattern.COMMENTS) .matcher(userAgent); if(mv.find()) { version = mv.group(1); try { majorVersion = Integer.parseInt(version); minorVersion = 0; } catch(NumberFormatException nfe) {} } } /* gecko engine version */ if(getGecko()) { Matcher g = Pattern.compile( "\\([^)]*rv:(([\\d]*)\\.([\\d]*).*?)\\)" ).matcher(userAgent); if(g.find()) { geckoVersion = g.group(1); try { geckoMajorVersion = Integer.parseInt(g.group(2)); String minor = g.group(3); if(minor.startsWith("0"))geckoMinorVersion = 0; else geckoMinorVersion = Integer.parseInt(minor); } catch(NumberFormatException nfe) {} } } } catch(PatternSyntaxException nfe) { // where should I log ?! } } }
let the BrowerSnifferTool detect java when the client is HttpUnit git-svn-id: 08feff1e20460d5e8b75c2f5109ada1fb2e66d41@493735 13f79535-47bb-0310-9956-ffa450edef68
src/java/org/apache/velocity/tools/view/tools/BrowserSnifferTool.java
let the BrowerSnifferTool detect java when the client is HttpUnit
Java
apache-2.0
44fc1d7dbcf2d703c85503d88f52d6507fea482b
0
kexianda/pig,faspl/pig,ljl1988com/pig,jcamachor/pigreuse,dongjiaqiang/pig,alpinedatalabs/pig,dongjiaqiang/pig,likaiwalkman/pig,kexianda/pig,kellyzly/pig,likaiwalkman/pig,hliu2/pig,hliu2/pig,faspl/pig,alpinedatalabs/pig,jcamachor/pigreuse,alpinedatalabs/pig,kellyzly/pig,ljl1988com/pig,kellyzly/pig,ljl1988com/pig,jcamachor/pigreuse,jcamachor/pigreuse,jcamachor/pigreuse,alpinedatalabs/pig,likaiwalkman/pig,kellyzly/pig,likaiwalkman/pig,alpinedatalabs/pig,dongjiaqiang/pig,hliu2/pig,kellyzly/pig,dongjiaqiang/pig,kexianda/pig,ljl1988com/pig,jcamachor/pigreuse,faspl/pig,alpinedatalabs/pig,hliu2/pig,ljl1988com/pig,kellyzly/pig,kexianda/pig,hliu2/pig,faspl/pig,kellyzly/pig,kexianda/pig,dongjiaqiang/pig,ljl1988com/pig,faspl/pig,faspl/pig,ljl1988com/pig,faspl/pig,dongjiaqiang/pig,likaiwalkman/pig,hliu2/pig,hliu2/pig,jcamachor/pigreuse,likaiwalkman/pig,kexianda/pig,dongjiaqiang/pig,kexianda/pig,likaiwalkman/pig
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.pig.backend.hadoop.executionengine.mapReduceLayer; import org.apache.pig.impl.io.NullablePartitionWritable; public class PigWritableComparators { // // Raw Comparators for Skewed Join // public static class PigBooleanRawPartitionComparator extends PigBooleanRawComparator { public PigBooleanRawPartitionComparator() { super(); } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { // Skip the first byte which is the type of the key return super.compare(b1, s1 + 1, l1, b2, s2 + 1, l2); } @Override public int compare(Object o1, Object o2) { return super.compare(((NullablePartitionWritable)o1).getKey(), ((NullablePartitionWritable)o2).getKey()); } } public static class PigIntRawPartitionComparator extends PigIntRawComparator { public PigIntRawPartitionComparator() { super(); } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return super.compare(b1, s1 + 1, l1, b2, s2 + 1, l2); } @Override public int compare(Object o1, Object o2) { return super.compare(((NullablePartitionWritable)o1).getKey(), ((NullablePartitionWritable)o2).getKey()); } } public static class PigBigIntegerRawPartitionComparator extends PigBigIntegerRawComparator { public PigBigIntegerRawPartitionComparator() { super(); } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return super.compare(b1, s1 + 1, l1, b2, s2 + 1, l2); } @Override public int compare(Object o1, Object o2) { return super.compare(((NullablePartitionWritable)o1).getKey(), ((NullablePartitionWritable)o2).getKey()); } } public static class PigBigDecimalRawPartitionComparator extends PigBigDecimalRawComparator { public PigBigDecimalRawPartitionComparator() { super(); } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return super.compare(b1, s1 + 1, l1, b2, s2 + 1, l2); } @Override public int compare(Object o1, Object o2) { return super.compare(((NullablePartitionWritable)o1).getKey(), ((NullablePartitionWritable)o2).getKey()); } } public static class PigLongRawPartitionComparator extends PigLongRawComparator { public PigLongRawPartitionComparator() { super(); } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return super.compare(b1, s1 + 1, l1, b2, s2 + 1, l2); } @Override public int compare(Object o1, Object o2) { return super.compare(((NullablePartitionWritable)o1).getKey(), ((NullablePartitionWritable)o2).getKey()); } } public static class PigFloatRawPartitionComparator extends PigFloatRawComparator { public PigFloatRawPartitionComparator() { super(); } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return super.compare(b1, s1 + 1, l1, b2, s2 + 1, l2); } @Override public int compare(Object o1, Object o2) { return super.compare(((NullablePartitionWritable)o1).getKey(), ((NullablePartitionWritable)o2).getKey()); } } public static class PigDoubleRawPartitionComparator extends PigDoubleRawComparator { public PigDoubleRawPartitionComparator() { super(); } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return super.compare(b1, s1 + 1, l1, b2, s2 + 1, l2); } @Override public int compare(Object o1, Object o2) { return super.compare(((NullablePartitionWritable)o1).getKey(), ((NullablePartitionWritable)o2).getKey()); } } public static class PigDateTimeRawPartitionComparator extends PigDateTimeRawComparator { public PigDateTimeRawPartitionComparator() { super(); } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return super.compare(b1, s1 + 1, l1, b2, s2 + 1, l2); } @Override public int compare(Object o1, Object o2) { return super.compare(((NullablePartitionWritable)o1).getKey(), ((NullablePartitionWritable)o2).getKey()); } } public static class PigTextRawPartitionComparator extends PigTextRawComparator { public PigTextRawPartitionComparator() { super(); } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return super.compare(b1, s1 + 1, l1, b2, s2 + 1, l2); } @Override public int compare(Object o1, Object o2) { return super.compare(((NullablePartitionWritable)o1).getKey(), ((NullablePartitionWritable)o2).getKey()); } } public static class PigBytesRawPartitionComparator extends PigBytesRawComparator { public PigBytesRawPartitionComparator() { super(); } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return super.compare(b1, s1 + 1, l1, b2, s2 + 1, l2); } @Override public int compare(Object o1, Object o2) { return super.compare(((NullablePartitionWritable)o1).getKey(), ((NullablePartitionWritable)o2).getKey()); } } public static class PigTupleSortPartitionComparator extends PigTupleSortComparator { public PigTupleSortPartitionComparator() { super(); } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return super.compare(b1, s1 + 1, l1, b2, s2 + 1, l2); } @Override public int compare(Object o1, Object o2) { return super.compare(((NullablePartitionWritable)o1).getKey(), ((NullablePartitionWritable)o2).getKey()); } } }
src/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/PigWritableComparators.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.pig.backend.hadoop.executionengine.mapReduceLayer; import org.apache.pig.impl.io.NullablePartitionWritable; public class PigWritableComparators { // // Raw Comparators for Skewed Join // public static class PigBooleanRawPartitionComparator extends PigBooleanRawComparator { public PigBooleanRawPartitionComparator() { super(); } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { // Skip the first byte which is the type of the key return super.compare(b1, s1 + 1, l1, b2, s2 + 1, l2); } @Override public int compare(Object o1, Object o2) { return super.compare(((NullablePartitionWritable)o1).getKey(), ((NullablePartitionWritable)o2).getKey()); } } public static class PigIntRawPartitionComparator extends PigIntRawComparator { public PigIntRawPartitionComparator() { super(); } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return super.compare(b1, s1 + 1, l1, b2, s2 + 1, l2); } @Override public int compare(Object o1, Object o2) { return super.compare(((NullablePartitionWritable)o1).getKey(), ((NullablePartitionWritable)o2).getKey()); } } public static class PigBigIntegerRawPartitionComparator extends PigBigIntegerRawComparator { public PigBigIntegerRawPartitionComparator() { super(); } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return super.compare(b1, s1 + 1, l1, b2, s2 + 1, l2); } @Override public int compare(Object o1, Object o2) { return super.compare(((NullablePartitionWritable)o1).getKey(), ((NullablePartitionWritable)o2).getKey()); } } public static class PigBigDecimalRawPartitionComparator extends PigBigDecimalRawComparator { public PigBigDecimalRawPartitionComparator() { super(); } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return super.compare(b1, s1 + 1, l1, b2, s2 + 1, l2); } @Override public int compare(Object o1, Object o2) { return super.compare(((NullablePartitionWritable)o1).getKey(), ((NullablePartitionWritable)o2).getKey()); } } public static class PigLongRawPartitionComparator extends PigLongRawComparator { public PigLongRawPartitionComparator() { super(); } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return super.compare(b1, s1 + 1, l1, b2, s2 + 1, l2); } @Override public int compare(Object o1, Object o2) { return super.compare(((NullablePartitionWritable)o1).getKey(), ((NullablePartitionWritable)o2).getKey()); } } public static class PigFloatRawPartitionComparator extends PigFloatRawComparator { public PigFloatRawPartitionComparator() { super(); } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return super.compare(b1, s1 + 1, l1, b2, s2 + 1, l2); } @Override public int compare(Object o1, Object o2) { return super.compare(((NullablePartitionWritable)o1).getKey(), ((NullablePartitionWritable)o2).getKey()); } } public static class PigDoubleRawPartitionComparator extends PigDoubleRawComparator { public PigDoubleRawPartitionComparator() { super(); } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return super.compare(b1, s1 + 1, l1, b2, s2 + 1, l2); } @Override public int compare(Object o1, Object o2) { return super.compare(((NullablePartitionWritable)o1).getKey(), ((NullablePartitionWritable)o2).getKey()); } } public static class PigDateTimeRawPartitionComparator extends PigDateTimeRawComparator { public PigDateTimeRawPartitionComparator() { super(); } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return super.compare(b1, s1 + 1, l1, b2, s2 + 1, l2); } @Override public int compare(Object o1, Object o2) { return super.compare(((NullablePartitionWritable)o1).getKey(), ((NullablePartitionWritable)o2).getKey()); } } public static class PigTextRawPartitionComparator extends PigTextRawComparator { public PigTextRawPartitionComparator() { super(); } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return super.compare(b1, s1 + 1, l1, b2, s2 + 1, l2); } @Override public int compare(Object o1, Object o2) { return super.compare(((NullablePartitionWritable)o1).getKey(), ((NullablePartitionWritable)o2).getKey()); } } public static class PigBytesRawPartitionComparator extends PigBytesRawComparator { public PigBytesRawPartitionComparator() { super(); } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return super.compare(b1, s1 + 1, l1, b2, s2 + 1, l2); } @Override public int compare(Object o1, Object o2) { return super.compare(((NullablePartitionWritable)o1).getKey(), ((NullablePartitionWritable)o2).getKey()); } } public static class PigTupleSortPartitionComparator extends PigTupleSortComparator { public PigTupleSortPartitionComparator() { super(); } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return super.compare(b1, s1 + 1, l1, b2, s2 + 1, l2); } @Override public int compare(Object o1, Object o2) { return super.compare(((NullablePartitionWritable)o1).getKey(), ((NullablePartitionWritable)o2).getKey()); } } } /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.pig.backend.hadoop.executionengine.mapReduceLayer; import org.apache.pig.impl.io.NullablePartitionWritable; public class PigWritableComparators { // // Raw Comparators for Skewed Join // public static class PigBooleanRawPartitionComparator extends PigBooleanRawComparator { public PigBooleanRawPartitionComparator() { super(); } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { // Skip the first byte which is the type of the key return super.compare(b1, s1 + 1, l1, b2, s2 + 1, l2); } @Override public int compare(Object o1, Object o2) { return super.compare(((NullablePartitionWritable)o1).getKey(), ((NullablePartitionWritable)o2).getKey()); } } public static class PigIntRawPartitionComparator extends PigIntRawComparator { public PigIntRawPartitionComparator() { super(); } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return super.compare(b1, s1 + 1, l1, b2, s2 + 1, l2); } @Override public int compare(Object o1, Object o2) { return super.compare(((NullablePartitionWritable)o1).getKey(), ((NullablePartitionWritable)o2).getKey()); } } public static class PigBigIntegerRawPartitionComparator extends PigBigIntegerRawComparator { public PigBigIntegerRawPartitionComparator() { super(); } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return super.compare(b1, s1 + 1, l1, b2, s2 + 1, l2); } @Override public int compare(Object o1, Object o2) { return super.compare(((NullablePartitionWritable)o1).getKey(), ((NullablePartitionWritable)o2).getKey()); } } public static class PigBigDecimalRawPartitionComparator extends PigBigDecimalRawComparator { public PigBigDecimalRawPartitionComparator() { super(); } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return super.compare(b1, s1 + 1, l1, b2, s2 + 1, l2); } @Override public int compare(Object o1, Object o2) { return super.compare(((NullablePartitionWritable)o1).getKey(), ((NullablePartitionWritable)o2).getKey()); } } public static class PigLongRawPartitionComparator extends PigLongRawComparator { public PigLongRawPartitionComparator() { super(); } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return super.compare(b1, s1 + 1, l1, b2, s2 + 1, l2); } @Override public int compare(Object o1, Object o2) { return super.compare(((NullablePartitionWritable)o1).getKey(), ((NullablePartitionWritable)o2).getKey()); } } public static class PigFloatRawPartitionComparator extends PigFloatRawComparator { public PigFloatRawPartitionComparator() { super(); } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return super.compare(b1, s1 + 1, l1, b2, s2 + 1, l2); } @Override public int compare(Object o1, Object o2) { return super.compare(((NullablePartitionWritable)o1).getKey(), ((NullablePartitionWritable)o2).getKey()); } } public static class PigDoubleRawPartitionComparator extends PigDoubleRawComparator { public PigDoubleRawPartitionComparator() { super(); } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return super.compare(b1, s1 + 1, l1, b2, s2 + 1, l2); } @Override public int compare(Object o1, Object o2) { return super.compare(((NullablePartitionWritable)o1).getKey(), ((NullablePartitionWritable)o2).getKey()); } } public static class PigDateTimeRawPartitionComparator extends PigDateTimeRawComparator { public PigDateTimeRawPartitionComparator() { super(); } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return super.compare(b1, s1 + 1, l1, b2, s2 + 1, l2); } @Override public int compare(Object o1, Object o2) { return super.compare(((NullablePartitionWritable)o1).getKey(), ((NullablePartitionWritable)o2).getKey()); } } public static class PigTextRawPartitionComparator extends PigTextRawComparator { public PigTextRawPartitionComparator() { super(); } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return super.compare(b1, s1 + 1, l1, b2, s2 + 1, l2); } @Override public int compare(Object o1, Object o2) { return super.compare(((NullablePartitionWritable)o1).getKey(), ((NullablePartitionWritable)o2).getKey()); } } public static class PigBytesRawPartitionComparator extends PigBytesRawComparator { public PigBytesRawPartitionComparator() { super(); } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return super.compare(b1, s1 + 1, l1, b2, s2 + 1, l2); } @Override public int compare(Object o1, Object o2) { return super.compare(((NullablePartitionWritable)o1).getKey(), ((NullablePartitionWritable)o2).getKey()); } } public static class PigTupleSortPartitionComparator extends PigTupleSortComparator { public PigTupleSortPartitionComparator() { super(); } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return super.compare(b1, s1 + 1, l1, b2, s2 + 1, l2); } @Override public int compare(Object o1, Object o2) { return super.compare(((NullablePartitionWritable)o1).getKey(), ((NullablePartitionWritable)o2).getKey()); } } }
Fix double application of patch and code duplication in PIG-4651 git-svn-id: c4d08399a8c07badad33cbf13a0909bacb78f41f@1695402 13f79535-47bb-0310-9956-ffa450edef68
src/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/PigWritableComparators.java
Fix double application of patch and code duplication in PIG-4651
Java
apache-2.0
b1a355218a75029f864e5e0e825fad74d12e94b0
0
Wechat-Group/WxJava,Wechat-Group/WxJava
package com.github.binarywang.wxpay.bean.result; import java.io.Serializable; import java.util.List; import com.google.common.collect.Lists; import com.thoughtworks.xstream.annotations.XStreamAlias; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; /** * <pre> * 微信支付-申请退款返回结果. * https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_4 * </pre> * * @author liukaitj & Binary Wang */ @Data @EqualsAndHashCode(callSuper = true) @NoArgsConstructor @XStreamAlias("xml") public class WxPayRefundResult extends BaseWxPayResult implements Serializable { private static final long serialVersionUID = -3392333879907788033L; /** * 微信订单号. */ @XStreamAlias("transaction_id") private String transactionId; /** * 商户订单号. */ @XStreamAlias("out_trade_no") private String outTradeNo; /** * 商户退款单号. */ @XStreamAlias("out_refund_no") private String outRefundNo; /** * 微信退款单号. */ @XStreamAlias("refund_id") private String refundId; /** * 退款金额. */ @XStreamAlias("refund_fee") private Integer refundFee; /** * 应结退款金额. */ @XStreamAlias("settlement_refund_fee") private Integer settlementRefundFee; /** * 标价金额. */ @XStreamAlias("total_fee") private Integer totalFee; /** * 应结订单金额. */ @XStreamAlias("settlement_total_fee") private Integer settlementTotalFee; /** * 标价币种. */ @XStreamAlias("fee_type") private String feeType; /** * 现金支付金额. */ @XStreamAlias("cash_fee") private Integer cashFee; /** * 现金支付币种. */ @XStreamAlias("cash_fee_type") private String cashFeeType; /** * 现金退款金额,单位为分,只能为整数,详见支付金额. */ @XStreamAlias("cash_refund_fee") private Integer cashRefundFee; /** * 退款代金券使用数量. */ @XStreamAlias("coupon_refund_count") private Integer couponRefundCount; /** * <pre> * 字段名:代金券退款总金额. * 变量名:coupon_refund_fee * 是否必填:否 * 类型:Int * 示例值:100 * 描述:代金券退款金额<=退款金额,退款金额-代金券或立减优惠退款金额为现金,说明详见代金券或立减优惠 * </pre> */ @XStreamAlias("coupon_refund_fee") private Integer couponRefundFee; private List<WxPayRefundCouponInfo> refundCoupons; /** * 组装生成退款代金券信息. */ private void composeRefundCoupons() { List<WxPayRefundCouponInfo> coupons = Lists.newArrayList(); Integer refundCount = this.getCouponRefundCount(); if (refundCount == null) { //无退款代金券信息 return; } for (int i = 0; i < refundCount; i++) { coupons.add( new WxPayRefundCouponInfo( this.getXmlValue("xml/coupon_refund_id_" + i), this.getXmlValueAsInt("xml/coupon_refund_fee_" + i), this.getXmlValue("xml/coupon_type_" + i) ) ); } this.setRefundCoupons(coupons); } public static WxPayRefundResult fromXML(String xml) { WxPayRefundResult result = BaseWxPayResult.fromXML(xml, WxPayRefundResult.class); result.composeRefundCoupons(); return result; } }
weixin-java-pay/src/main/java/com/github/binarywang/wxpay/bean/result/WxPayRefundResult.java
package com.github.binarywang.wxpay.bean.result; import java.io.Serializable; import java.util.List; import com.google.common.collect.Lists; import com.thoughtworks.xstream.annotations.XStreamAlias; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; /** * <pre> * 微信支付-申请退款返回结果. * https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_4 * </pre> * * @author liukaitj & Binary Wang */ @Data @EqualsAndHashCode(callSuper = true) @NoArgsConstructor @XStreamAlias("xml") public class WxPayRefundResult extends BaseWxPayResult implements Serializable { private static final long serialVersionUID = -3392333879907788033L; /** * 微信订单号. */ @XStreamAlias("transaction_id") private String transactionId; /** * 商户订单号. */ @XStreamAlias("out_trade_no") private String outTradeNo; /** * 商户退款单号. */ @XStreamAlias("out_refund_no") private String outRefundNo; /** * 微信退款单号. */ @XStreamAlias("refund_id") private String refundId; /** * 退款金额. */ @XStreamAlias("refund_fee") private Integer refundFee; /** * 应结退款金额. */ @XStreamAlias("settlement_refund_fee") private Integer settlementRefundFee; /** * 标价金额. */ @XStreamAlias("total_fee") private Integer totalFee; /** * 应结订单金额. */ @XStreamAlias("settlement_total_fee") private Integer settlementTotalFee; /** * 标价币种. */ @XStreamAlias("fee_type") private String feeType; /** * 现金支付金额. */ @XStreamAlias("cash_fee") private Integer cashFee; /** * 现金支付币种. */ @XStreamAlias("cash_fee_type") private String cashFeeType; /** * 现金退款金额. */ @XStreamAlias("cash_refund_fee") private String cashRefundFee; /** * 退款代金券使用数量. */ @XStreamAlias("coupon_refund_count") private Integer couponRefundCount; /** * <pre> * 字段名:代金券退款总金额. * 变量名:coupon_refund_fee * 是否必填:否 * 类型:Int * 示例值:100 * 描述:代金券退款金额<=退款金额,退款金额-代金券或立减优惠退款金额为现金,说明详见代金券或立减优惠 * </pre> */ @XStreamAlias("coupon_refund_fee") private Integer couponRefundFee; private List<WxPayRefundCouponInfo> refundCoupons; /** * 组装生成退款代金券信息. */ private void composeRefundCoupons() { List<WxPayRefundCouponInfo> coupons = Lists.newArrayList(); Integer refundCount = this.getCouponRefundCount(); if (refundCount == null) { //无退款代金券信息 return; } for (int i = 0; i < refundCount; i++) { coupons.add( new WxPayRefundCouponInfo( this.getXmlValue("xml/coupon_refund_id_" + i), this.getXmlValueAsInt("xml/coupon_refund_fee_" + i), this.getXmlValue("xml/coupon_type_" + i) ) ); } this.setRefundCoupons(coupons); } public static WxPayRefundResult fromXML(String xml) { WxPayRefundResult result = BaseWxPayResult.fromXML(xml, WxPayRefundResult.class); result.composeRefundCoupons(); return result; } }
#957 修改微信支付退款响应类的cash_refund_fee字段类型为Integer
weixin-java-pay/src/main/java/com/github/binarywang/wxpay/bean/result/WxPayRefundResult.java
#957 修改微信支付退款响应类的cash_refund_fee字段类型为Integer
Java
apache-2.0
7cdf86afba290f3b27d99ed113fe5d2988f4601f
0
darranl/directory-shared
ldap/client/api/src/main/java/org/apache/directory/ldap/client/api/LdapConnectionFactory.java
/* * 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.directory.ldap.client.api; /** * A LdapConnection factory. * * @author <a href="mailto:[email protected]">Apache Directory Project</a> */ public final class LdapConnectionFactory { /** * Private constructor. * */ private LdapConnectionFactory() { } /** * Gets the core session connection. * * @return a connection based on the the CoreSession */ public static LdapConnection getCoreSessionConnection() { try { Class<?> cl = Class.forName( "org.apache.directory.server.core.api.LdapCoreSessionConnection" ); return ( LdapConnection ) cl.newInstance(); } catch ( Exception e ) { throw new RuntimeException( e ); } } /** * Gets the network connection. * * @param host the host * @param port the port * @return the LdapNetworkConnection */ public static LdapAsyncConnection getNetworkConnection( String host, int port ) { try { Class<?> cl = Class.forName( "org.apache.directory.ldap.client.api.LdapNetworkConnection" ); LdapAsyncConnection networkConnection = ( LdapAsyncConnection ) cl.newInstance(); networkConnection.getConfig().setLdapHost( host ); networkConnection.getConfig().setLdapPort( port ); return networkConnection; } catch ( Exception e ) { throw new RuntimeException( e ); } } }
Removed the LdapConnectionFactory class git-svn-id: a98780f44e7643575d86f056c30a4189ca15db44@1299690 13f79535-47bb-0310-9956-ffa450edef68
ldap/client/api/src/main/java/org/apache/directory/ldap/client/api/LdapConnectionFactory.java
Removed the LdapConnectionFactory class
Java
apache-2.0
94a39a2c38c429eb507ad92319a5ebedea6b838b
0
java110/MicroCommunity,java110/MicroCommunity,java110/MicroCommunity,java110/MicroCommunity
package com.java110.core.smo.purchaseApply; import com.java110.core.feign.FeignConfiguration; import com.java110.dto.purchaseApply.PurchaseApplyDetailDto; import com.java110.dto.purchaseApply.PurchaseApplyDto; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import java.util.List; /** * @ClassName IPurchaseApplyInnerServiceSMO * @Description 采购申请接口类 * @Author wuxw * @Date 2019/4/24 9:04 * @Version 1.0 * add by wuxw 2019/4/24 **/ @FeignClient(name = "store-service", configuration = {FeignConfiguration.class}) @RequestMapping("/purchaseApplyApi") public interface IPurchaseApplyInnerServiceSMO { /** * <p>查询小区楼信息</p> * * * @param purchaseApplyDto 数据对象分享 * @return PurchaseApplyDto 对象数据 */ @RequestMapping(value = "/queryPurchaseApplys", method = RequestMethod.POST) List<PurchaseApplyDto> queryPurchaseApplys(@RequestBody PurchaseApplyDto purchaseApplyDto); /** * 查询<p>小区楼</p>总记录数 * * @param purchaseApplyDto 数据对象分享 * @return 小区下的小区楼记录数 */ @RequestMapping(value = "/queryPurchaseApplysCount", method = RequestMethod.POST) int queryPurchaseApplysCount(@RequestBody PurchaseApplyDto purchaseApplyDto); //查询采购明细表 @RequestMapping(value = "/queryPurchaseApplyDetails", method = RequestMethod.POST) List<PurchaseApplyDetailDto> queryPurchaseApplyDetails(@RequestBody PurchaseApplyDetailDto purchaseApplyDetailDto); }
java110-core/src/main/java/com/java110/core/smo/purchaseApply/IPurchaseApplyInnerServiceSMO.java
package com.java110.core.smo.purchaseApply; import com.java110.core.feign.FeignConfiguration; import com.java110.dto.purchaseApply.PurchaseApplyDto; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import java.util.List; /** * @ClassName IPurchaseApplyInnerServiceSMO * @Description 采购申请接口类 * @Author wuxw * @Date 2019/4/24 9:04 * @Version 1.0 * add by wuxw 2019/4/24 **/ @FeignClient(name = "store-service", configuration = {FeignConfiguration.class}) @RequestMapping("/purchaseApplyApi") public interface IPurchaseApplyInnerServiceSMO { /** * <p>查询小区楼信息</p> * * * @param purchaseApplyDto 数据对象分享 * @return PurchaseApplyDto 对象数据 */ @RequestMapping(value = "/queryPurchaseApplys", method = RequestMethod.POST) List<PurchaseApplyDto> queryPurchaseApplys(@RequestBody PurchaseApplyDto purchaseApplyDto); /** * 查询<p>小区楼</p>总记录数 * * @param purchaseApplyDto 数据对象分享 * @return 小区下的小区楼记录数 */ @RequestMapping(value = "/queryPurchaseApplysCount", method = RequestMethod.POST) int queryPurchaseApplysCount(@RequestBody PurchaseApplyDto purchaseApplyDto); }
优化采购申请
java110-core/src/main/java/com/java110/core/smo/purchaseApply/IPurchaseApplyInnerServiceSMO.java
优化采购申请
Java
apache-2.0
adaa8fc12293af0cf514c4dc10978e7b0ae35ab1
0
calvinjia/tachyon,jsimsa/alluxio,riversand963/alluxio,jswudi/alluxio,aaudiber/alluxio,PasaLab/tachyon,maobaolong/alluxio,jsimsa/alluxio,riversand963/alluxio,apc999/alluxio,Reidddddd/mo-alluxio,wwjiang007/alluxio,riversand963/alluxio,ShailShah/alluxio,wwjiang007/alluxio,maboelhassan/alluxio,EvilMcJerkface/alluxio,calvinjia/tachyon,WilliamZapata/alluxio,calvinjia/tachyon,maobaolong/alluxio,maobaolong/alluxio,jswudi/alluxio,jswudi/alluxio,ChangerYoung/alluxio,wwjiang007/alluxio,madanadit/alluxio,bf8086/alluxio,EvilMcJerkface/alluxio,yuluo-ding/alluxio,bf8086/alluxio,WilliamZapata/alluxio,Alluxio/alluxio,calvinjia/tachyon,maboelhassan/alluxio,yuluo-ding/alluxio,wwjiang007/alluxio,Reidddddd/alluxio,EvilMcJerkface/alluxio,maboelhassan/alluxio,EvilMcJerkface/alluxio,maobaolong/alluxio,maobaolong/alluxio,uronce-cc/alluxio,bf8086/alluxio,jswudi/alluxio,PasaLab/tachyon,maobaolong/alluxio,madanadit/alluxio,ShailShah/alluxio,uronce-cc/alluxio,EvilMcJerkface/alluxio,Reidddddd/alluxio,maobaolong/alluxio,jsimsa/alluxio,EvilMcJerkface/alluxio,madanadit/alluxio,aaudiber/alluxio,yuluo-ding/alluxio,PasaLab/tachyon,Reidddddd/alluxio,calvinjia/tachyon,PasaLab/tachyon,maobaolong/alluxio,Alluxio/alluxio,bf8086/alluxio,Alluxio/alluxio,uronce-cc/alluxio,PasaLab/tachyon,Reidddddd/mo-alluxio,calvinjia/tachyon,EvilMcJerkface/alluxio,aaudiber/alluxio,jsimsa/alluxio,aaudiber/alluxio,ShailShah/alluxio,maobaolong/alluxio,madanadit/alluxio,PasaLab/tachyon,apc999/alluxio,riversand963/alluxio,WilliamZapata/alluxio,yuluo-ding/alluxio,calvinjia/tachyon,maboelhassan/alluxio,Alluxio/alluxio,Alluxio/alluxio,bf8086/alluxio,maboelhassan/alluxio,maobaolong/alluxio,bf8086/alluxio,calvinjia/tachyon,apc999/alluxio,Alluxio/alluxio,ChangerYoung/alluxio,wwjiang007/alluxio,ChangerYoung/alluxio,jswudi/alluxio,Reidddddd/alluxio,Reidddddd/mo-alluxio,madanadit/alluxio,uronce-cc/alluxio,wwjiang007/alluxio,apc999/alluxio,madanadit/alluxio,Reidddddd/mo-alluxio,Reidddddd/alluxio,Reidddddd/alluxio,apc999/alluxio,ChangerYoung/alluxio,wwjiang007/alluxio,aaudiber/alluxio,wwjiang007/alluxio,jsimsa/alluxio,ShailShah/alluxio,wwjiang007/alluxio,jswudi/alluxio,WilliamZapata/alluxio,apc999/alluxio,apc999/alluxio,aaudiber/alluxio,madanadit/alluxio,bf8086/alluxio,ShailShah/alluxio,ChangerYoung/alluxio,Reidddddd/alluxio,aaudiber/alluxio,Alluxio/alluxio,Alluxio/alluxio,EvilMcJerkface/alluxio,jsimsa/alluxio,yuluo-ding/alluxio,riversand963/alluxio,ChangerYoung/alluxio,maboelhassan/alluxio,yuluo-ding/alluxio,madanadit/alluxio,wwjiang007/alluxio,riversand963/alluxio,uronce-cc/alluxio,WilliamZapata/alluxio,Alluxio/alluxio,uronce-cc/alluxio,maboelhassan/alluxio,ShailShah/alluxio,PasaLab/tachyon,Reidddddd/mo-alluxio,WilliamZapata/alluxio,bf8086/alluxio,Alluxio/alluxio,Reidddddd/mo-alluxio
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.worker.netty; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.anyLong; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import alluxio.ConfigurationRule; import alluxio.PropertyKey; import alluxio.client.netty.ClientHandler; import alluxio.client.netty.NettyClient; import alluxio.client.netty.SingleResponseListener; import alluxio.exception.BlockDoesNotExistException; import alluxio.network.protocol.RPCBlockReadRequest; import alluxio.network.protocol.RPCBlockWriteRequest; import alluxio.network.protocol.RPCFileReadRequest; import alluxio.network.protocol.RPCFileWriteRequest; import alluxio.network.protocol.RPCRequest; import alluxio.network.protocol.RPCResponse; import alluxio.network.protocol.databuffer.DataByteArrayChannel; import alluxio.worker.AlluxioWorkerService; import alluxio.worker.block.BlockWorker; import alluxio.worker.block.io.MockBlockReader; import alluxio.worker.block.io.MockBlockWriter; import alluxio.worker.file.FileSystemWorker; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableMap; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.Mockito; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.net.InetSocketAddress; import java.util.concurrent.TimeUnit; /** * Unit tests for {@link NettyDataServer}. The entire alluxio.worker.netty package is treated as one * unit for the purposes of these tests; all classes except for NettyDataServer are package-private. */ public final class NettyDataServerTest { private NettyDataServer mNettyDataServer; private BlockWorker mBlockWorker; private FileSystemWorker mFileSystemWorker; @Rule public ConfigurationRule mRule = new ConfigurationRule(ImmutableMap.of( PropertyKey.WORKER_NETWORK_NETTY_SHUTDOWN_QUIET_PERIOD, "0")); @Before public void before() { mBlockWorker = Mockito.mock(BlockWorker.class); mFileSystemWorker = Mockito.mock(FileSystemWorker.class); AlluxioWorkerService alluxioWorker = Mockito.mock(AlluxioWorkerService.class); Mockito.when(alluxioWorker.getBlockWorker()).thenReturn(mBlockWorker); Mockito.when(alluxioWorker.getFileSystemWorker()).thenReturn(mFileSystemWorker); mNettyDataServer = new NettyDataServer(new InetSocketAddress(0), alluxioWorker); } @After public void after() throws Exception { mNettyDataServer.close(); } @Test public void close() throws Exception { mNettyDataServer.close(); } @Test public void port() { assertTrue(mNettyDataServer.getPort() > 0); } @Test public void readBlock() throws Exception { long sessionId = 0; long blockId = 1; long offset = 2; long length = 3; long lockId = 4; when(mBlockWorker.readBlockRemote(sessionId, blockId, lockId)).thenReturn( new MockBlockReader("abcdefg".getBytes(Charsets.UTF_8))); RPCResponse response = request(new RPCBlockReadRequest(blockId, offset, length, lockId, sessionId)); // Verify that the 3 bytes were read at offset 2. assertEquals("cde", Charsets.UTF_8.decode(response.getPayloadDataBuffer().getReadOnlyByteBuffer()).toString()); } @Test public void blockWorkerExceptionCausesReadFailedStatus() throws Exception { when(mBlockWorker.readBlockRemote(anyLong(), anyLong(), anyLong())) .thenThrow(new RuntimeException()); RPCResponse response = request(new RPCBlockReadRequest(1, 2, 3, 4, 0)); // Verify that the read request failed with UFS_READ_FAILED status. assertEquals(RPCResponse.Status.UFS_READ_FAILED, response.getStatus()); } @Test public void blockWorkerBlockDoesNotExistExceptionCausesFileDneStatus() throws Exception { when(mBlockWorker.readBlockRemote(anyLong(), anyLong(), anyLong())) .thenThrow(new BlockDoesNotExistException("")); RPCResponse response = request(new RPCBlockReadRequest(1, 2, 3, 4, 0)); // Verify that the read request failed with a FILE_DNE status. assertEquals(RPCResponse.Status.FILE_DNE, response.getStatus()); } @Test public void blockWorkerExceptionCausesFailStatusOnRead() throws Exception { when(mBlockWorker.readBlockRemote(anyLong(), anyLong(), anyLong())) .thenThrow(new RuntimeException()); RPCResponse response = request(new RPCBlockReadRequest(1, 2, 3, 4, 0)); // Verify that the write request failed. assertEquals(RPCResponse.Status.UFS_READ_FAILED, response.getStatus()); } @Test public void writeNewBlock() throws Exception { long sessionId = 0; long blockId = 1; long length = 2; // Offset is set to 0 so that a new block will be created. long offset = 0; DataByteArrayChannel data = new DataByteArrayChannel("abc".getBytes(Charsets.UTF_8), 0, 3); MockBlockWriter blockWriter = new MockBlockWriter(); when(mBlockWorker.getTempBlockWriterRemote(sessionId, blockId)).thenReturn(blockWriter); RPCResponse response = request(new RPCBlockWriteRequest(sessionId, blockId, offset, length, data)); // Verify that the write request tells the worker to create a new block and write the specified // data to it. assertEquals(RPCResponse.Status.SUCCESS, response.getStatus()); verify(mBlockWorker).createBlockRemote(sessionId, blockId, "MEM", length); assertEquals("ab", new String(blockWriter.getBytes(), Charsets.UTF_8)); } @Test public void writeExistingBlock() throws Exception { long sessionId = 0; long blockId = 1; // Offset is set to 1 so that the write is directed to an existing block long offset = 1; long length = 2; DataByteArrayChannel data = new DataByteArrayChannel("abc".getBytes(Charsets.UTF_8), 0, 3); MockBlockWriter blockWriter = new MockBlockWriter(); when(mBlockWorker.getTempBlockWriterRemote(sessionId, blockId)).thenReturn(blockWriter); RPCResponse response = request(new RPCBlockWriteRequest(sessionId, blockId, offset, length, data)); // Verify that the write request requests space on an existing block and then writes the // specified data. assertEquals(RPCResponse.Status.SUCCESS, response.getStatus()); verify(mBlockWorker).requestSpace(sessionId, blockId, length); assertEquals("ab", new String(blockWriter.getBytes(), Charsets.UTF_8)); } @Test public void blockWorkerExceptionCausesFailStatusOnWrite() throws Exception { long sessionId = 0; long blockId = 1; long offset = 0; long length = 2; when(mBlockWorker.getTempBlockWriterRemote(sessionId, blockId)) .thenThrow(new RuntimeException()); DataByteArrayChannel data = new DataByteArrayChannel("abc".getBytes(Charsets.UTF_8), 0, 3); RPCResponse response = request(new RPCBlockWriteRequest(sessionId, blockId, offset, length, data)); // Verify that the write request failed. assertEquals(RPCResponse.Status.WRITE_ERROR, response.getStatus()); } @Test public void readFile() throws Exception { long tempUfsFileId = 1; long offset = 0; long length = 3; when(mFileSystemWorker.getUfsInputStream(tempUfsFileId, offset)).thenReturn( new ByteArrayInputStream("abc".getBytes(Charsets.UTF_8))); RPCResponse response = request(new RPCFileReadRequest(tempUfsFileId, offset, length)); // Verify that the 3 bytes were read. assertEquals("abc", Charsets.UTF_8.decode(response.getPayloadDataBuffer().getReadOnlyByteBuffer()).toString()); } @Test public void fileSystemWorkerExceptionCausesFailStatusOnRead() throws Exception { when(mFileSystemWorker.getUfsInputStream(1, 0)) .thenThrow(new RuntimeException()); RPCResponse response = request(new RPCFileReadRequest(1, 0, 3)); // Verify that the write request failed. assertEquals(RPCResponse.Status.UFS_READ_FAILED, response.getStatus()); } @Test public void writeFile() throws Exception { long tempUfsFileId = 1; long offset = 0; long length = 3; DataByteArrayChannel data = new DataByteArrayChannel("abc".getBytes(Charsets.UTF_8), 0, 3); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); when(mFileSystemWorker.getUfsOutputStream(tempUfsFileId)).thenReturn(outStream); RPCResponse response = request(new RPCFileWriteRequest(tempUfsFileId, offset, length, data)); // Verify that the write request writes to the OutputStream returned by the worker. assertEquals(RPCResponse.Status.SUCCESS, response.getStatus()); assertEquals("abc", new String(outStream.toByteArray(), Charsets.UTF_8)); } @Test public void fileSystemWorkerExceptionCausesFailStatusOnWrite() throws Exception { DataByteArrayChannel data = new DataByteArrayChannel("abc".getBytes(Charsets.UTF_8), 0, 3); when(mFileSystemWorker.getUfsOutputStream(1)).thenThrow(new RuntimeException()); RPCResponse response = request(new RPCFileWriteRequest(1, 0, 3, data)); // Verify that the write request failed. assertEquals(RPCResponse.Status.UFS_WRITE_FAILED, response.getStatus()); } private RPCResponse request(RPCRequest rpcBlockWriteRequest) throws Exception { InetSocketAddress address = new InetSocketAddress(mNettyDataServer.getBindHost(), mNettyDataServer.getPort()); ClientHandler handler = new ClientHandler(); Bootstrap clientBootstrap = NettyClient.createClientBootstrap(handler); ChannelFuture f = clientBootstrap.connect(address).sync(); Channel channel = f.channel(); try { SingleResponseListener listener = new SingleResponseListener(); handler.addListener(listener); channel.writeAndFlush(rpcBlockWriteRequest); return listener.get(NettyClient.TIMEOUT_MS, TimeUnit.MILLISECONDS); } finally { channel.close().sync(); } } }
core/server/src/test/java/alluxio/worker/netty/NettyDataServerTest.java
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.worker.netty; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.anyLong; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import alluxio.client.netty.ClientHandler; import alluxio.client.netty.NettyClient; import alluxio.client.netty.SingleResponseListener; import alluxio.exception.BlockDoesNotExistException; import alluxio.network.protocol.RPCBlockReadRequest; import alluxio.network.protocol.RPCBlockWriteRequest; import alluxio.network.protocol.RPCFileReadRequest; import alluxio.network.protocol.RPCFileWriteRequest; import alluxio.network.protocol.RPCRequest; import alluxio.network.protocol.RPCResponse; import alluxio.network.protocol.databuffer.DataByteArrayChannel; import alluxio.worker.AlluxioWorkerService; import alluxio.worker.block.BlockWorker; import alluxio.worker.block.io.MockBlockReader; import alluxio.worker.block.io.MockBlockWriter; import alluxio.worker.file.FileSystemWorker; import com.google.common.base.Charsets; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.net.InetSocketAddress; import java.util.concurrent.TimeUnit; /** * Unit tests for {@link NettyDataServer}. The entire alluxio.worker.netty package is treated as one * unit for the purposes of these tests; all classes except for NettyDataServer are package-private. */ public final class NettyDataServerTest { private NettyDataServer mNettyDataServer; private BlockWorker mBlockWorker; private FileSystemWorker mFileSystemWorker; @Before public void before() { mBlockWorker = Mockito.mock(BlockWorker.class); mFileSystemWorker = Mockito.mock(FileSystemWorker.class); AlluxioWorkerService alluxioWorker = Mockito.mock(AlluxioWorkerService.class); Mockito.when(alluxioWorker.getBlockWorker()).thenReturn(mBlockWorker); Mockito.when(alluxioWorker.getFileSystemWorker()).thenReturn(mFileSystemWorker); mNettyDataServer = new NettyDataServer(new InetSocketAddress(0), alluxioWorker); } @After public void after() throws Exception { mNettyDataServer.close(); } @Test public void close() throws Exception { mNettyDataServer.close(); } @Test public void port() { assertTrue(mNettyDataServer.getPort() > 0); } @Test public void readBlock() throws Exception { long sessionId = 0; long blockId = 1; long offset = 2; long length = 3; long lockId = 4; when(mBlockWorker.readBlockRemote(sessionId, blockId, lockId)).thenReturn( new MockBlockReader("abcdefg".getBytes(Charsets.UTF_8))); RPCResponse response = request(new RPCBlockReadRequest(blockId, offset, length, lockId, sessionId)); // Verify that the 3 bytes were read at offset 2. assertEquals("cde", Charsets.UTF_8.decode(response.getPayloadDataBuffer().getReadOnlyByteBuffer()).toString()); } @Test public void blockWorkerExceptionCausesReadFailedStatus() throws Exception { when(mBlockWorker.readBlockRemote(anyLong(), anyLong(), anyLong())) .thenThrow(new RuntimeException()); RPCResponse response = request(new RPCBlockReadRequest(1, 2, 3, 4, 0)); // Verify that the read request failed with UFS_READ_FAILED status. assertEquals(RPCResponse.Status.UFS_READ_FAILED, response.getStatus()); } @Test public void blockWorkerBlockDoesNotExistExceptionCausesFileDneStatus() throws Exception { when(mBlockWorker.readBlockRemote(anyLong(), anyLong(), anyLong())) .thenThrow(new BlockDoesNotExistException("")); RPCResponse response = request(new RPCBlockReadRequest(1, 2, 3, 4, 0)); // Verify that the read request failed with a FILE_DNE status. assertEquals(RPCResponse.Status.FILE_DNE, response.getStatus()); } @Test public void blockWorkerExceptionCausesFailStatusOnRead() throws Exception { when(mBlockWorker.readBlockRemote(anyLong(), anyLong(), anyLong())) .thenThrow(new RuntimeException()); RPCResponse response = request(new RPCBlockReadRequest(1, 2, 3, 4, 0)); // Verify that the write request failed. assertEquals(RPCResponse.Status.UFS_READ_FAILED, response.getStatus()); } @Test public void writeNewBlock() throws Exception { long sessionId = 0; long blockId = 1; long length = 2; // Offset is set to 0 so that a new block will be created. long offset = 0; DataByteArrayChannel data = new DataByteArrayChannel("abc".getBytes(Charsets.UTF_8), 0, 3); MockBlockWriter blockWriter = new MockBlockWriter(); when(mBlockWorker.getTempBlockWriterRemote(sessionId, blockId)).thenReturn(blockWriter); RPCResponse response = request(new RPCBlockWriteRequest(sessionId, blockId, offset, length, data)); // Verify that the write request tells the worker to create a new block and write the specified // data to it. assertEquals(RPCResponse.Status.SUCCESS, response.getStatus()); verify(mBlockWorker).createBlockRemote(sessionId, blockId, "MEM", length); assertEquals("ab", new String(blockWriter.getBytes(), Charsets.UTF_8)); } @Test public void writeExistingBlock() throws Exception { long sessionId = 0; long blockId = 1; // Offset is set to 1 so that the write is directed to an existing block long offset = 1; long length = 2; DataByteArrayChannel data = new DataByteArrayChannel("abc".getBytes(Charsets.UTF_8), 0, 3); MockBlockWriter blockWriter = new MockBlockWriter(); when(mBlockWorker.getTempBlockWriterRemote(sessionId, blockId)).thenReturn(blockWriter); RPCResponse response = request(new RPCBlockWriteRequest(sessionId, blockId, offset, length, data)); // Verify that the write request requests space on an existing block and then writes the // specified data. assertEquals(RPCResponse.Status.SUCCESS, response.getStatus()); verify(mBlockWorker).requestSpace(sessionId, blockId, length); assertEquals("ab", new String(blockWriter.getBytes(), Charsets.UTF_8)); } @Test public void blockWorkerExceptionCausesFailStatusOnWrite() throws Exception { long sessionId = 0; long blockId = 1; long offset = 0; long length = 2; when(mBlockWorker.getTempBlockWriterRemote(sessionId, blockId)) .thenThrow(new RuntimeException()); DataByteArrayChannel data = new DataByteArrayChannel("abc".getBytes(Charsets.UTF_8), 0, 3); RPCResponse response = request(new RPCBlockWriteRequest(sessionId, blockId, offset, length, data)); // Verify that the write request failed. assertEquals(RPCResponse.Status.WRITE_ERROR, response.getStatus()); } @Test public void readFile() throws Exception { long tempUfsFileId = 1; long offset = 0; long length = 3; when(mFileSystemWorker.getUfsInputStream(tempUfsFileId, offset)).thenReturn( new ByteArrayInputStream("abc".getBytes(Charsets.UTF_8))); RPCResponse response = request(new RPCFileReadRequest(tempUfsFileId, offset, length)); // Verify that the 3 bytes were read. assertEquals("abc", Charsets.UTF_8.decode(response.getPayloadDataBuffer().getReadOnlyByteBuffer()).toString()); } @Test public void fileSystemWorkerExceptionCausesFailStatusOnRead() throws Exception { when(mFileSystemWorker.getUfsInputStream(1, 0)) .thenThrow(new RuntimeException()); RPCResponse response = request(new RPCFileReadRequest(1, 0, 3)); // Verify that the write request failed. assertEquals(RPCResponse.Status.UFS_READ_FAILED, response.getStatus()); } @Test public void writeFile() throws Exception { long tempUfsFileId = 1; long offset = 0; long length = 3; DataByteArrayChannel data = new DataByteArrayChannel("abc".getBytes(Charsets.UTF_8), 0, 3); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); when(mFileSystemWorker.getUfsOutputStream(tempUfsFileId)).thenReturn(outStream); RPCResponse response = request(new RPCFileWriteRequest(tempUfsFileId, offset, length, data)); // Verify that the write request writes to the OutputStream returned by the worker. assertEquals(RPCResponse.Status.SUCCESS, response.getStatus()); assertEquals("abc", new String(outStream.toByteArray(), Charsets.UTF_8)); } @Test public void fileSystemWorkerExceptionCausesFailStatusOnWrite() throws Exception { DataByteArrayChannel data = new DataByteArrayChannel("abc".getBytes(Charsets.UTF_8), 0, 3); when(mFileSystemWorker.getUfsOutputStream(1)).thenThrow(new RuntimeException()); RPCResponse response = request(new RPCFileWriteRequest(1, 0, 3, data)); // Verify that the write request failed. assertEquals(RPCResponse.Status.UFS_WRITE_FAILED, response.getStatus()); } private RPCResponse request(RPCRequest rpcBlockWriteRequest) throws Exception { InetSocketAddress address = new InetSocketAddress(mNettyDataServer.getBindHost(), mNettyDataServer.getPort()); ClientHandler handler = new ClientHandler(); Bootstrap clientBootstrap = NettyClient.createClientBootstrap(handler); ChannelFuture f = clientBootstrap.connect(address).sync(); Channel channel = f.channel(); try { SingleResponseListener listener = new SingleResponseListener(); handler.addListener(listener); channel.writeAndFlush(rpcBlockWriteRequest); return listener.get(NettyClient.TIMEOUT_MS, TimeUnit.MILLISECONDS); } finally { channel.close().sync(); } } }
Fix slowness in Netty data server test
core/server/src/test/java/alluxio/worker/netty/NettyDataServerTest.java
Fix slowness in Netty data server test
Java
apache-2.0
4bff142d3a017c220fc1a69adc962535735758f6
0
mjwall/accumulo,milleruntime/accumulo,ivakegg/accumulo,phrocker/accumulo-1,ivakegg/accumulo,dhutchis/accumulo,adamjshook/accumulo,dhutchis/accumulo,keith-turner/accumulo,mikewalch/accumulo,mikewalch/accumulo,apache/accumulo,joshelser/accumulo,mjwall/accumulo,ivakegg/accumulo,dhutchis/accumulo,lstav/accumulo,keith-turner/accumulo,milleruntime/accumulo,ivakegg/accumulo,dhutchis/accumulo,joshelser/accumulo,joshelser/accumulo,ctubbsii/accumulo,ivakegg/accumulo,ivakegg/accumulo,joshelser/accumulo,apache/accumulo,joshelser/accumulo,apache/accumulo,milleruntime/accumulo,keith-turner/accumulo,apache/accumulo,mjwall/accumulo,dhutchis/accumulo,apache/accumulo,ctubbsii/accumulo,joshelser/accumulo,dhutchis/accumulo,adamjshook/accumulo,milleruntime/accumulo,mikewalch/accumulo,mjwall/accumulo,adamjshook/accumulo,ctubbsii/accumulo,ctubbsii/accumulo,milleruntime/accumulo,keith-turner/accumulo,dhutchis/accumulo,ctubbsii/accumulo,keith-turner/accumulo,apache/accumulo,phrocker/accumulo-1,lstav/accumulo,ctubbsii/accumulo,phrocker/accumulo-1,dhutchis/accumulo,adamjshook/accumulo,dhutchis/accumulo,phrocker/accumulo-1,adamjshook/accumulo,lstav/accumulo,mjwall/accumulo,mikewalch/accumulo,lstav/accumulo,keith-turner/accumulo,adamjshook/accumulo,mikewalch/accumulo,ctubbsii/accumulo,lstav/accumulo,ivakegg/accumulo,adamjshook/accumulo,milleruntime/accumulo,phrocker/accumulo-1,mikewalch/accumulo,mjwall/accumulo,joshelser/accumulo,adamjshook/accumulo,milleruntime/accumulo,phrocker/accumulo-1,lstav/accumulo,apache/accumulo,mikewalch/accumulo,keith-turner/accumulo,phrocker/accumulo-1,adamjshook/accumulo,joshelser/accumulo,mikewalch/accumulo,mjwall/accumulo,lstav/accumulo
/* * 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.accumulo.test.functional; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.accumulo.core.client.BatchWriter; import org.apache.accumulo.core.client.BatchWriterConfig; import org.apache.accumulo.core.client.Connector; import org.apache.accumulo.core.client.MutationsRejectedException; import org.apache.accumulo.core.client.Scanner; import org.apache.accumulo.core.client.TableNotFoundException; import org.apache.accumulo.core.conf.Property; import org.apache.accumulo.core.data.Key; import org.apache.accumulo.core.data.Mutation; import org.apache.accumulo.core.data.Value; import org.apache.accumulo.core.security.Authorizations; import org.junit.Assert; import org.junit.Test; /** * */ public class CloneTestIT extends SimpleMacIT { @Test(timeout = 120 * 1000) public void testProps() throws Exception { String table1 = makeTableName(); String table2 = makeTableName(); Connector c = getConnector(); c.tableOperations().create(table1); c.tableOperations().setProperty(table1, Property.TABLE_FILE_COMPRESSED_BLOCK_SIZE.getKey(), "1M"); c.tableOperations().setProperty(table1, Property.TABLE_FILE_COMPRESSED_BLOCK_SIZE_INDEX.getKey(), "2M"); c.tableOperations().setProperty(table1, Property.TABLE_FILE_MAX.getKey(), "23"); BatchWriter bw = writeData(table1, c); Map<String,String> props = new HashMap<String,String>(); props.put(Property.TABLE_FILE_COMPRESSED_BLOCK_SIZE.getKey(), "500K"); Set<String> exclude = new HashSet<String>(); exclude.add(Property.TABLE_FILE_MAX.getKey()); c.tableOperations().clone(table1, table2, true, props, exclude); Mutation m3 = new Mutation("009"); m3.put("data", "x", "1"); m3.put("data", "y", "2"); bw.addMutation(m3); bw.close(); checkData(table2, c); HashMap<String,String> tableProps = new HashMap<String,String>(); for (Entry<String,String> prop : c.tableOperations().getProperties(table2)) { tableProps.put(prop.getKey(), prop.getValue()); } Assert.assertEquals("500K", tableProps.get(Property.TABLE_FILE_COMPRESSED_BLOCK_SIZE.getKey())); Assert.assertEquals(Property.TABLE_FILE_MAX.getDefaultValue(), tableProps.get(Property.TABLE_FILE_MAX.getKey())); Assert.assertEquals("2M", tableProps.get(Property.TABLE_FILE_COMPRESSED_BLOCK_SIZE_INDEX.getKey())); c.tableOperations().delete(table1); c.tableOperations().delete(table2); } private void checkData(String table2, Connector c) throws TableNotFoundException { Scanner scanner = c.createScanner(table2, Authorizations.EMPTY); HashMap<String,String> expected = new HashMap<String,String>(); expected.put("001:x", "9"); expected.put("001:y", "7"); expected.put("008:x", "3"); expected.put("008:y", "4"); HashMap<String,String> actual = new HashMap<String,String>(); for (Entry<Key,Value> entry : scanner) actual.put(entry.getKey().getRowData().toString() + ":" + entry.getKey().getColumnQualifierData().toString(), entry.getValue().toString()); Assert.assertEquals(expected, actual); } private BatchWriter writeData(String table1, Connector c) throws TableNotFoundException, MutationsRejectedException { BatchWriter bw = c.createBatchWriter(table1, new BatchWriterConfig()); Mutation m1 = new Mutation("001"); m1.put("data", "x", "9"); m1.put("data", "y", "7"); Mutation m2 = new Mutation("008"); m2.put("data", "x", "3"); m2.put("data", "y", "4"); bw.addMutation(m1); bw.addMutation(m2); bw.flush(); return bw; } @Test(timeout = 120 * 1000) public void testDeleteClone() throws Exception { String table1 = makeTableName(); String table2 = makeTableName(); Connector c = getConnector(); c.tableOperations().create(table1); BatchWriter bw = writeData(table1, c); Map<String,String> props = new HashMap<String,String>(); props.put(Property.TABLE_FILE_COMPRESSED_BLOCK_SIZE.getKey(), "500K"); Set<String> exclude = new HashSet<String>(); exclude.add(Property.TABLE_FILE_MAX.getKey()); c.tableOperations().clone(table1, table2, true, props, exclude); Mutation m3 = new Mutation("009"); m3.put("data", "x", "1"); m3.put("data", "y", "2"); bw.addMutation(m3); bw.close(); // delete source table, should not affect clone c.tableOperations().delete(table1); checkData(table2, c); c.tableOperations().compact(table2, null, null, true, true); checkData(table2, c); c.tableOperations().delete(table2); } }
test/src/test/java/org/apache/accumulo/test/functional/CloneTestIT.java
/* * 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.accumulo.test.functional; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.accumulo.core.client.BatchWriter; import org.apache.accumulo.core.client.BatchWriterConfig; import org.apache.accumulo.core.client.Connector; import org.apache.accumulo.core.client.Scanner; import org.apache.accumulo.core.conf.Property; import org.apache.accumulo.core.data.Key; import org.apache.accumulo.core.data.Mutation; import org.apache.accumulo.core.data.Value; import org.apache.accumulo.core.security.Authorizations; import org.junit.Assert; import org.junit.Test; /** * */ public class CloneTestIT extends SimpleMacIT { @Test(timeout = 120 * 1000) public void run() throws Exception { String table1 = makeTableName(); String table2 = makeTableName(); Connector c = getConnector(); c.tableOperations().create(table1); c.tableOperations().setProperty(table1, Property.TABLE_FILE_COMPRESSED_BLOCK_SIZE.getKey(), "1M"); c.tableOperations().setProperty(table1, Property.TABLE_FILE_COMPRESSED_BLOCK_SIZE_INDEX.getKey(), "2M"); c.tableOperations().setProperty(table1, Property.TABLE_FILE_MAX.getKey(), "23"); BatchWriter bw = c.createBatchWriter(table1, new BatchWriterConfig()); Mutation m1 = new Mutation("001"); m1.put("data", "x", "9"); m1.put("data", "y", "7"); Mutation m2 = new Mutation("008"); m2.put("data", "x", "3"); m2.put("data", "y", "4"); bw.addMutation(m1); bw.addMutation(m2); bw.flush(); Map<String,String> props = new HashMap<String,String>(); props.put(Property.TABLE_FILE_COMPRESSED_BLOCK_SIZE.getKey(), "500K"); Set<String> exclude = new HashSet<String>(); exclude.add(Property.TABLE_FILE_MAX.getKey()); c.tableOperations().clone(table1, table2, true, props, exclude); Mutation m3 = new Mutation("009"); m3.put("data", "x", "1"); m3.put("data", "y", "2"); bw.addMutation(m3); bw.close(); Scanner scanner = c.createScanner(table2, Authorizations.EMPTY); HashMap<String,String> expected = new HashMap<String,String>(); expected.put("001:x", "9"); expected.put("001:y", "7"); expected.put("008:x", "3"); expected.put("008:y", "4"); HashMap<String,String> actual = new HashMap<String,String>(); for (Entry<Key,Value> entry : scanner) actual.put(entry.getKey().getRowData().toString() + ":" + entry.getKey().getColumnQualifierData().toString(), entry.getValue().toString()); Assert.assertEquals(expected, actual); HashMap<String,String> tableProps = new HashMap<String,String>(); for (Entry<String,String> prop : c.tableOperations().getProperties(table2)) { tableProps.put(prop.getKey(), prop.getValue()); } Assert.assertEquals("500K", tableProps.get(Property.TABLE_FILE_COMPRESSED_BLOCK_SIZE.getKey())); Assert.assertEquals(Property.TABLE_FILE_MAX.getDefaultValue(), tableProps.get(Property.TABLE_FILE_MAX.getKey())); Assert.assertEquals("2M", tableProps.get(Property.TABLE_FILE_COMPRESSED_BLOCK_SIZE_INDEX.getKey())); c.tableOperations().delete(table1); c.tableOperations().delete(table2); } }
ACCUMULO-1629 reproduced conetable bug seen in random walk in functional test
test/src/test/java/org/apache/accumulo/test/functional/CloneTestIT.java
ACCUMULO-1629 reproduced conetable bug seen in random walk in functional test
Java
apache-2.0
53ef0ceddaffd3e3c74785b1ae34760a69f67160
0
pqbyte/coherence
package com.pqbyte.coherence; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.Screen; import com.badlogic.gdx.ScreenAdapter; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Button; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; public class PauseMenuScreen extends ScreenAdapter { private Stage stage; private Coherence game; public PauseMenuScreen(Coherence game) { this.game = game; Skin skin = new Skin(Gdx.files.internal("skin/uiskin.json")); Button button = createButton(skin); Label titleLabel = createTitleLabel(skin); stage = new Stage(); stage.addActor(button); stage.addActor(titleLabel); Gdx.input.setInputProcessor(stage); } @Override public void render(float delta) { Gdx.gl.glClearColor(0, 0, 0, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); stage.draw(); } @Override public void dispose() { stage.dispose(); } private Label createTitleLabel(Skin skin) { Label label = new Label("Game paused", skin); // Double font size label.setSize(label.getWidth() * 2, label.getHeight()); label.setFontScale(2); int width = Gdx.graphics.getWidth(); int height = Gdx.graphics.getHeight(); label.setPosition( (width - label.getWidth()) / 2, (height - label.getHeight()) / 2 + height / 4 ); return label; } private Button createButton(Skin skin) { TextButton button = new TextButton("RESUME GAME", skin, "default"); int buttonWidth = 300; int buttonHeight = 60; button.setWidth(buttonWidth); button.setHeight(buttonHeight); int width = Gdx.graphics.getWidth(); int height = Gdx.graphics.getHeight(); button.setPosition( (width - buttonWidth) / 2, (height - buttonHeight) / 2 - height / 4 ); button.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float xPos, float yPos) { game.setScreen(game.getPreviousScreen()); dispose(); } }); return button; } }
core/src/com/pqbyte/coherence/PauseMenuScreen.java
package com.pqbyte.coherence; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.Screen; import com.badlogic.gdx.ScreenAdapter; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; public class PauseMenuScreen extends ScreenAdapter { final Coherence game; OrthographicCamera camera; public PauseMenuScreen(final Coherence game) { this.game = game; camera = new OrthographicCamera(); camera.setToOrtho(false, 800, 480); } @Override public void render(float delta) { Gdx.gl.glClearColor(0.09f, 0.28f, 0.2f, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); SpriteBatch batch = game.batch; BitmapFont font = game.font; camera.update(); batch.setProjectionMatrix(camera.combined); batch.begin(); font.draw(batch, "The game has been paused", 300, 350); font.draw(batch, "Tap anywhere to resume!", 300, 250); font.draw(batch, "Press Enter to return to main menu", 250, 200); font.draw(batch, "Press Delete to return to exit", 250, 150); batch.end(); if (Gdx.input.isTouched()) { game.setScreen(game.getPreviousScreen()); dispose(); } if (Gdx.input.isKeyPressed(Input.Keys.ENTER)) { game.setScreen(new MainMenuScreen(game)); } if (Gdx.input.isKeyPressed(Input.Keys.DEL)) { Gdx.app.exit(); } } }
Rewrite PauseMenuScreen to use stage
core/src/com/pqbyte/coherence/PauseMenuScreen.java
Rewrite PauseMenuScreen to use stage
Java
apache-2.0
4e4b5ac4428b31c95ca8b30c3c4cb008aaf3813d
0
abates/Windtalker
/* * LICENSE * * Copyright 2015 Andrew Bates 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 co.andrewbates.windtalker; /** * @author Andrew Bates * * The Codec interface defines the methods an implementor must create * for the Windtalker to use before sending messages over the air. * Messages can be encoded and decoded. As long as both the sender and * receiver have implemented the encoding and decoding the same way, the * messages should be understandable by both parties. * */ public interface Codec { /** * The decode method will take a message that has been previously encoded * and convert it back into the original message * * @param message * encoded string * @return the decoded message */ public String decode(String message); /** * The encode method will take a clear text message and encode it using the * secret algorithm. Once encoded the message can be translated and no one * in the middle should be able to understand the meaning of the message * * @param message * string to be encoded for sending * @return encoded message */ public String encode(String message); }
src/co/andrewbates/windtalker/Codec.java
/* * LICENSE * * Copyright 2015 Andrew Bates 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 co.andrewbates.windtalker; public interface Codec { public String encode(String message); public String decode(String message); }
Added javadoc for Codec class
src/co/andrewbates/windtalker/Codec.java
Added javadoc for Codec class
Java
apache-2.0
ba9ee93cd44eaf517395f860a391831c4e79f1ea
0
ummels/vavr,dx-pbuckley/vavr,amygithub/vavr,dx-pbuckley/vavr,amygithub/vavr,ummels/vavr
/* / \____ _ ______ _____ / \____ ____ _____ * / \__ \/ \ / \__ \ / __// \__ \ / \/ __ \ Javaslang * _/ // _\ \ \/ / _\ \\_ \/ // _\ \ /\ \__/ / Copyright 2014-2015 Daniel Dietrich * /___/ \_____/\____/\_____/____/\___\_____/_/ \_/____/ Licensed under the Apache License, Version 2.0 */ package javaslang.collection; import javaslang.Function1; import javaslang.Tuple2; import java.util.Comparator; import java.util.Iterator; import java.util.Objects; /** * Interface for sequential, traversable data structures. * <p>Mutation:</p> * <ul> * <li>{@link #append(Object)}</li> * <li>{@link #appendAll(Iterable)}</li> * <li>{@link #insert(int, Object)}</li> * <li>{@link #insertAll(int, Iterable)}</li> * <li>{@link #prepend(Object)}</li> * <li>{@link #prependAll(Iterable)}</li> * <li>{@link #set(int, Object)}</li> * </ul> * <p>Selection:</p> * <ul> * <li>{@link #get(int)}</li> * <li>{@link #indexOf(Object)}</li> * <li>{@link #lastIndexOf(Object)}</li> * <li>{@link #subsequence(int)}</li> * <li>{@link #subsequence(int, int)}</li> * </ul> * <p>Transformation:</p> * <ul> * <li>TODO(#111): permutations()</li> * <li>{@link #sort()}</li> * <li>{@link #sort(Comparator)}</li> * <li>{@link #splitAt(int)}</li> * </ul> * <p>Traversion:</p> * <ul> * <li>{@link #iterator(int)}</li> * </ul> * * @param <T> Component type * @since 1.1.0 */ public interface Seq<T> extends Traversable<T> { /** * Returns a Seq based on an Iterable. Returns the given Iterable, if it is already a Seq, * otherwise {@link Stream#of(Iterable)}. * * @param iterable An Iterable. * @param <T> Component type * @return A Seq */ static <T> Seq<T> of(Iterable<? extends T> iterable) { Objects.requireNonNull(iterable, "iterable is null"); if (iterable instanceof Seq) { @SuppressWarnings("unchecked") final Seq<T> seq = (Seq<T>) iterable; return seq; } else { return Stream.of(iterable); } } Seq<T> append(T element); Seq<T> appendAll(Iterable<? extends T> elements); @SuppressWarnings("unchecked") @Override default <U> Seq<U> flatten() { return (Seq<U>) Traversable.super.flatten(); } @Override <U> Seq<U> flatten(Function1<T, ? extends Iterable<? extends U>> f); T get(int index); int indexOf(T element); Seq<T> insert(int index, T element); Seq<T> insertAll(int index, Iterable<? extends T> elements); default Iterator<T> iterator(int index) { return subsequence(index).iterator(); } int lastIndexOf(T element); Seq<T> prepend(T element); Seq<T> prependAll(Iterable<? extends T> elements); Seq<T> set(int index, T element); Seq<T> sort(); Seq<T> sort(Comparator<? super T> c); /** * Splits a Traversable at the specified index. The result of {@code splitAt(n)} is equivalent to * {@code Tuple.of(take(n), drop(n))}. * * @param n An index. * @return A Tuple containing the first n and the remaining elements. */ Tuple2<? extends Seq<T>, ? extends Seq<T>> splitAt(int n); Seq<T> subsequence(int beginIndex); Seq<T> subsequence(int beginIndex, int endIndex); }
src/main/java/javaslang/collection/Seq.java
/* / \____ _ ______ _____ / \____ ____ _____ * / \__ \/ \ / \__ \ / __// \__ \ / \/ __ \ Javaslang * _/ // _\ \ \/ / _\ \\_ \/ // _\ \ /\ \__/ / Copyright 2014-2015 Daniel Dietrich * /___/ \_____/\____/\_____/____/\___\_____/_/ \_/____/ Licensed under the Apache License, Version 2.0 */ package javaslang.collection; import javaslang.Function1; import javaslang.Tuple2; import java.util.Comparator; import java.util.Iterator; import java.util.Objects; /** * Interface for sequential, traversable data structures. * <p>Mutation:</p> * <ul> * <li>{@link #append(Object)}</li> * <li>{@link #appendAll(Iterable)}</li> * <li>{@link #insert(int, Object)}</li> * <li>{@link #insertAll(int, Iterable)}</li> * <li>{@link #prepend(Object)}</li> * <li>{@link #prependAll(Iterable)}</li> * <li>{@link #set(int, Object)}</li> * </ul> * <p>Selection:</p> * <ul> * <li>{@link #get(int)}</li> * <li>{@link #indexOf(Object)}</li> * <li>{@link #lastIndexOf(Object)}</li> * <li>{@link #subsequence(int)}</li> * <li>{@link #subsequence(int, int)}</li> * </ul> * <p>Transformation:</p> * <ul> * <li>TODO(#111): permutations()</li> * <li>{@link #sort()}</li> * <li>{@link #sort(Comparator)}</li> * <li>{@link #splitAt(int)}</li> * </ul> * <p>Traversion:</p> * <ul> * <li>{@link #iterator(int)}</li> * </ul> * * @param <T> Component type * @since 1.1.0 */ public interface Seq<T> extends Traversable<T> { /** * Returns a Seq based on an Iterable. Returns the given Iterable, if it is already a Seq, * otherwise {@link Stream#of(Iterable)}. * * @param iterable An Iterable. * @param <T> Component type * @return A Seq */ static <T> Seq<T> of(Iterable<? extends T> iterable) { Objects.requireNonNull(iterable, "iterable is null"); if (iterable instanceof Seq) { @SuppressWarnings("unchecked") final Seq<T> seq = (Seq<T>) iterable; return seq; } else { return Stream.of(iterable); } } Seq<T> append(T element); Seq<T> appendAll(Iterable<? extends T> elements); @SuppressWarnings("unchecked") @Override default <U> Seq<U> flatten() { return (Seq<U>) Traversable.super.flatten(); } @Override <U> Seq<U> flatten(Function1<T, ? extends Iterable<? extends U>> f); T get(int index); int indexOf(T element); Seq<T> insert(int index, T element); Seq<T> insertAll(int index, Iterable<? extends T> elements); default Iterator<T> iterator(int index) { return subsequence(index).iterator(); } int lastIndexOf(T element); Seq<T> prepend(T element); Seq<T> prependAll(Iterable<? extends T> elements); Seq<T> set(int index, T element); Seq<T> sort(); Seq<T> sort(Comparator<? super T> c); /** * Splits a Traversable at the specified index. The result of {@code splitAt(n)} is equivalent to * {@code Tuple.of(take(n), drop(n))}. * * @param n An index. * @return A Tuple containing the first n and the remaining elements. */ Tuple2<? extends Traversable<T>, ? extends Traversable<T>> splitAt(int n); Seq<T> subsequence(int beginIndex); Seq<T> subsequence(int beginIndex, int endIndex); }
Towards #121: Because of type erasure these kind of 'bugs' cannot be found by reflection
src/main/java/javaslang/collection/Seq.java
Towards #121: Because of type erasure these kind of 'bugs' cannot be found by reflection
Java
bsd-3-clause
8e52e487dd5895a912816ee3c50cd56a0318487e
0
NCIP/rembrandt,NCIP/rembrandt,NCIP/rembrandt,NCIP/rembrandt,NCIP/rembrandt,NCIP/rembrandt
/* * @author: SahniH * Created on Sep 24, 2004 * @version $ Revision: 1.0 $ * * The caBIO Software License, Version 1.0 * * Copyright 2004 SAIC. This software was developed in conjunction with the National Cancer * Institute, and so to the extent government employees are co-authors, any rights in such works * shall be subject to Title 17 of the United States Code, section 105. * * 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 disclaimer of Article 3, below. 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. * * 2. The end-user documentation included with the redistribution, if any, must include the * following acknowledgment: * * "This product includes software developed by the SAIC and the National Cancer * Institute." * * If no such end-user documentation is to be included, this acknowledgment shall appear in the * software itself, wherever such third-party acknowledgments normally appear. * * 3. The names "The National Cancer Institute", "NCI" and "SAIC" must not be used to endorse or * promote products derived from this software. * * 4. This license does not authorize the incorporation of this software into any proprietary * programs. This license does not authorize the recipient to use any trademarks owned by either * NCI or SAIC-Frederick. * * * 5. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED 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 NATIONAL CANCER INSTITUTE, SAIC, OR * THEIR AFFILIATES 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 gov.nih.nci.nautilus.query; import gov.nih.nci.nautilus.view.ViewType; import gov.nih.nci.nautilus.view.Viewable; import java.util.*; /** * @author SahniH * Date: Sep 24, 2004 * */ public class CompoundQuery implements Queriable{ private Queriable leftQuery = null; private Queriable rightQuery = null; private OperatorType operatorType = null; private Viewable associatedView = null; /* * @see gov.nih.nci.nautilus.query.Queriable#getAssociatedView() * */ public CompoundQuery(OperatorType operator, Queriable leftQuery, Queriable rightQuery) throws Exception{ setOperatorType(operator); setLeftQuery(leftQuery); setRightQuery(rightQuery); } public CompoundQuery( Queriable rightQuery) throws Exception{ setRightQuery(rightQuery); setOperatorType( null); setLeftQuery(null); } public Viewable getAssociatedView() { return associatedView; } public void setAssociatedView(Viewable viewable) { associatedView = viewable; } /** * @return Returns the operatorType. */ public OperatorType getOperatorType() { return this.operatorType; } /** * @param operatorType The operatorType to set. */ public void setOperatorType(OperatorType operatorType) throws Exception{ //PROJECTS results by make sure the two views are different this.operatorType = operatorType; if(validateProjectResultsBy()==false){//if invalide Query throw new Exception ( "For ProjectResultsBy, both views need to be different"); } } /** * @return Returns the leftQuery. */ public Queriable getLeftQuery() { return this.leftQuery; } /** * @param leftQuery The leftQuery to set. */ public void setLeftQuery(Queriable leftQuery) throws Exception{ this.leftQuery = leftQuery; if(validateProjectResultsBy()==false){//if invalide Query throw new Exception ( "For ProjectResultsBy, both views need to be different"); } } /** * @return Returns the rightQuery. */ public Queriable getRightQuery() { return this.rightQuery; } /** * @param rightQuery The rightQuery to set. */ public void setRightQuery(Queriable rightQuery) throws Exception{ this.rightQuery = rightQuery; // The right query's AssociatedView is always the "winning view" if (rightQuery != null && rightQuery.getAssociatedView()!= null){ setAssociatedView(rightQuery.getAssociatedView()); } if(validateProjectResultsBy()==false){//if invalide Query throw new Exception ( "For ProjectResultsBy, both views need to be different"); } } /** * @return validationStatus as true or false * */ public boolean validateProjectResultsBy(){ //PROJECTS results by make sure the two views are different if((operatorType!= null && operatorType.equals(OperatorType.PROJECT_RESULTS_BY))&& (getRightQuery()!= null && getLeftQuery()!= null)){ if((getRightQuery().getAssociatedView() != null && getLeftQuery().getAssociatedView() != null)){ if((getRightQuery().getAssociatedView().equals(ViewType.GENE_GROUP_SAMPLE_VIEW) || getRightQuery().getAssociatedView().equals(ViewType.GENE_SINGLE_SAMPLE_VIEW)) && (!getLeftQuery().getAssociatedView().equals(ViewType.CLINICAL_VIEW)) || ((getLeftQuery().getAssociatedView().equals(ViewType.GENE_GROUP_SAMPLE_VIEW) || getLeftQuery().getAssociatedView().equals(ViewType.GENE_SINGLE_SAMPLE_VIEW)) && (!getRightQuery().getAssociatedView().equals(ViewType.CLINICAL_VIEW)))) { return false; } } } return true; } /** * toString() method to generate Compound query for display - pcs */ public String toString(){ Queriable leftQuery = this.getLeftQuery(); Queriable rightQuery = this.getRightQuery(); OperatorType operator = this.getOperatorType(); String leftString = ""; String rightString = ""; String outString = ""; try { if (leftQuery != null) { if (leftQuery instanceof CompoundQuery) { leftString += ((CompoundQuery) leftQuery).toString();} else if (leftQuery instanceof Query){ leftString += ((Query) leftQuery).getQueryName(); } } if (rightQuery != null) { if (rightQuery instanceof CompoundQuery) { rightString += ((CompoundQuery) rightQuery).toString();} else if (rightQuery instanceof Query){ rightString += ((Query) rightQuery).getQueryName(); } } }catch (Exception ex) { ex.printStackTrace(); System.out.println("Error "+ex.getMessage()); } if (operator != null) { outString += "( "+leftString+" "+operator.getOperatorType()+" "+rightString+" )"; } return outString; } public ViewType [] getValidViews(){ ViewType [] validViewTypes=null; ArrayList queryTypesCollection=null; boolean isGEQuery = false; boolean isCGHQuery = false; boolean isClinical = false; queryTypesCollection = getQueryTypes(this); for (Iterator iter = queryTypesCollection.iterator();iter.hasNext();) { QueryType thisQuery = (QueryType) iter.next(); if (thisQuery instanceof QueryType.GeneExprQueryType) isGEQuery = true; if (thisQuery instanceof QueryType.CGHQueryType) isCGHQuery = true; if (thisQuery instanceof QueryType.ClinicalQueryType) isClinical = true; } //Gene Expression Only if (isGEQuery && !isCGHQuery && !isClinical){ validViewTypes = new ViewType [] { ViewType.CLINICAL_VIEW, ViewType.GENE_SINGLE_SAMPLE_VIEW, ViewType.GENE_GROUP_SAMPLE_VIEW }; } // Genomic Only else if (!isGEQuery && isCGHQuery && !isClinical){ validViewTypes = new ViewType [] { ViewType.CLINICAL_VIEW, ViewType.COPYNUMBER_GROUP_SAMPLE_VIEW }; } // Clinical Only else if (!isGEQuery && !isCGHQuery && isClinical){ validViewTypes = new ViewType [] { ViewType.CLINICAL_VIEW }; } // The rest compound queries else { validViewTypes = new ViewType [] { ViewType.CLINICAL_VIEW, ViewType.GENE_SINGLE_SAMPLE_VIEW, ViewType.COPYNUMBER_GROUP_SAMPLE_VIEW }; } return validViewTypes; } public ArrayList getQueryTypes(CompoundQuery cQuery){ ArrayList queryType = new ArrayList(); Queriable lQuery; Queriable rQuery; lQuery = cQuery.getLeftQuery(); rQuery = cQuery.getRightQuery(); try { if (lQuery != null) { if (lQuery instanceof CompoundQuery) queryType.addAll(getQueryTypes((CompoundQuery) lQuery)); else if (lQuery instanceof Query){ queryType.add(((Query) lQuery).getQueryType()); } } if (rQuery != null) { if (rQuery instanceof CompoundQuery) queryType.addAll(getQueryTypes((CompoundQuery) rQuery)); else if (rQuery instanceof Query){ queryType.add(((Query) rQuery).getQueryType()); } } }catch(Exception ex){ ex.printStackTrace(); } return queryType; } }
src/gov/nih/nci/nautilus/query/CompoundQuery.java
/* * @author: SahniH * Created on Sep 24, 2004 * @version $ Revision: 1.0 $ * * The caBIO Software License, Version 1.0 * * Copyright 2004 SAIC. This software was developed in conjunction with the National Cancer * Institute, and so to the extent government employees are co-authors, any rights in such works * shall be subject to Title 17 of the United States Code, section 105. * * 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 disclaimer of Article 3, below. 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. * * 2. The end-user documentation included with the redistribution, if any, must include the * following acknowledgment: * * "This product includes software developed by the SAIC and the National Cancer * Institute." * * If no such end-user documentation is to be included, this acknowledgment shall appear in the * software itself, wherever such third-party acknowledgments normally appear. * * 3. The names "The National Cancer Institute", "NCI" and "SAIC" must not be used to endorse or * promote products derived from this software. * * 4. This license does not authorize the incorporation of this software into any proprietary * programs. This license does not authorize the recipient to use any trademarks owned by either * NCI or SAIC-Frederick. * * * 5. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED 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 NATIONAL CANCER INSTITUTE, SAIC, OR * THEIR AFFILIATES 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 gov.nih.nci.nautilus.query; import gov.nih.nci.nautilus.view.ViewType; import gov.nih.nci.nautilus.view.Viewable; import java.util.*; /** * @author SahniH * Date: Sep 24, 2004 * */ public class CompoundQuery implements Queriable{ private Queriable leftQuery = null; private Queriable rightQuery = null; private OperatorType operatorType = null; private Viewable associatedView = null; /* * @see gov.nih.nci.nautilus.query.Queriable#getAssociatedView() * */ public CompoundQuery(OperatorType operator, Queriable leftQuery, Queriable rightQuery) throws Exception{ setOperatorType(operator); setLeftQuery(leftQuery); setRightQuery(rightQuery); } public CompoundQuery( Queriable rightQuery) throws Exception{ setRightQuery(rightQuery); setOperatorType( null); setLeftQuery(null); } public Viewable getAssociatedView() { return associatedView; } public void setAssociatedView(Viewable viewable) { associatedView = viewable; } /** * @return Returns the operatorType. */ public OperatorType getOperatorType() { return this.operatorType; } /** * @param operatorType The operatorType to set. */ public void setOperatorType(OperatorType operatorType) throws Exception{ //PROJECTS results by make sure the two views are different this.operatorType = operatorType; if(validateProjectResultsBy()==false){//if invalide Query throw new Exception ( "For ProjectResultsBy, both views need to be different"); } } /** * @return Returns the leftQuery. */ public Queriable getLeftQuery() { return this.leftQuery; } /** * @param leftQuery The leftQuery to set. */ public void setLeftQuery(Queriable leftQuery) throws Exception{ this.leftQuery = leftQuery; if(validateProjectResultsBy()==false){//if invalide Query throw new Exception ( "For ProjectResultsBy, both views need to be different"); } } /** * @return Returns the rightQuery. */ public Queriable getRightQuery() { return this.rightQuery; } /** * @param rightQuery The rightQuery to set. */ public void setRightQuery(Queriable rightQuery) throws Exception{ this.rightQuery = rightQuery; // The right query's AssociatedView is always the "winning view" if (rightQuery != null && rightQuery.getAssociatedView()!= null){ setAssociatedView(rightQuery.getAssociatedView()); } if(validateProjectResultsBy()==false){//if invalide Query throw new Exception ( "For ProjectResultsBy, both views need to be different"); } } /** * @return validationStatus as true or false * */ public boolean validateProjectResultsBy(){ //PROJECTS results by make sure the two views are different if((operatorType!= null && operatorType.equals(OperatorType.PROJECT_RESULTS_BY))&& (getRightQuery()!= null && getLeftQuery()!= null)){ if((getRightQuery().getAssociatedView() != null && getLeftQuery().getAssociatedView() != null)){ if((getRightQuery().getAssociatedView().equals(ViewType.GENE_GROUP_SAMPLE_VIEW) || getRightQuery().getAssociatedView().equals(ViewType.GENE_SINGLE_SAMPLE_VIEW)) && (!getLeftQuery().getAssociatedView().equals(ViewType.CLINICAL_VIEW)) || ((getLeftQuery().getAssociatedView().equals(ViewType.GENE_GROUP_SAMPLE_VIEW) || getLeftQuery().getAssociatedView().equals(ViewType.GENE_SINGLE_SAMPLE_VIEW)) && (!getRightQuery().getAssociatedView().equals(ViewType.CLINICAL_VIEW)))) { return false; } } } return true; } /** * toString() method to generate Compound query for display - pcs */ public String toString(){ Queriable leftQuery = this.getLeftQuery(); Queriable rightQuery = this.getRightQuery(); OperatorType operator = this.getOperatorType(); String leftString = ""; String rightString = ""; String outString = ""; try { if (leftQuery != null) { if (leftQuery instanceof CompoundQuery) { leftString += ((CompoundQuery) leftQuery).toString();} else if (leftQuery instanceof Query){ leftString += ((Query) leftQuery).getQueryName(); } } if (rightQuery != null) { if (rightQuery instanceof CompoundQuery) { rightString += ((CompoundQuery) rightQuery).toString();} else if (rightQuery instanceof Query){ rightString += ((Query) rightQuery).getQueryName(); } } }catch (Exception ex) { ex.printStackTrace(); System.out.println("Error "+ex.getMessage()); } if (operator != null) { outString += "( "+leftString+" "+operator.getOperatorType()+" "+rightString+" )"; } return outString; } public ViewType [] getValidViews(){ ViewType [] validViewTypes=null; ArrayList queryTypesCollection=null; boolean isGEQuery = false; boolean isCGHQuery = false; boolean isClinical = false; queryTypesCollection = getQueryTypes(this); for (Iterator iter = queryTypesCollection.iterator();iter.hasNext();) { QueryType thisQuery = (QueryType) iter.next(); if (thisQuery instanceof QueryType.GeneExprQueryType) isGEQuery = true; if (thisQuery instanceof QueryType.CGHQueryType) isCGHQuery = true; if (thisQuery instanceof QueryType.ClinicalQueryType) isClinical = true; } //Gene Expression Only if (isGEQuery && !isCGHQuery && !isClinical){ validViewTypes = new ViewType [] { ViewType.GENE_SINGLE_SAMPLE_VIEW, ViewType.GENE_GROUP_SAMPLE_VIEW, ViewType.CLINICAL_VIEW }; } // Genomic Only else if (!isGEQuery && isCGHQuery && !isClinical){ validViewTypes = new ViewType [] { ViewType.COPYNUMBER_GROUP_SAMPLE_VIEW, ViewType.CLINICAL_VIEW }; } // Clinical Only else if (!isGEQuery && !isCGHQuery && isClinical){ validViewTypes = new ViewType [] { ViewType.CLINICAL_VIEW }; } // The rest compound queries else { validViewTypes = new ViewType [] { ViewType.GENE_SINGLE_SAMPLE_VIEW, ViewType.COPYNUMBER_GROUP_SAMPLE_VIEW, ViewType.CLINICAL_VIEW }; } return validViewTypes; } public ArrayList getQueryTypes(CompoundQuery cQuery){ ArrayList queryType = new ArrayList(); Queriable lQuery; Queriable rQuery; lQuery = cQuery.getLeftQuery(); rQuery = cQuery.getRightQuery(); try { if (lQuery != null) { if (lQuery instanceof CompoundQuery) queryType.addAll(getQueryTypes((CompoundQuery) lQuery)); else if (lQuery instanceof Query){ queryType.add(((Query) lQuery).getQueryType()); } } if (rQuery != null) { if (rQuery instanceof CompoundQuery) queryType.addAll(getQueryTypes((CompoundQuery) rQuery)); else if (rQuery instanceof Query){ queryType.add(((Query) rQuery).getQueryType()); } } }catch(Exception ex){ ex.printStackTrace(); } return queryType; } }
Make Clinical View to display as default. move to top - pcs SVN-Revision: 609
src/gov/nih/nci/nautilus/query/CompoundQuery.java
Make Clinical View to display as default. move to top - pcs
Java
bsd-3-clause
a2ac3c3fb5656f0acaaac6fe667f95be384486e3
0
NCIP/caaers,NCIP/caaers,CBIIT/caaers,NCIP/caaers,CBIIT/caaers,CBIIT/caaers,CBIIT/caaers,CBIIT/caaers,NCIP/caaers
package gov.nih.nci.cabig.caaers.rules.runtime.action; import gov.nih.nci.cabig.caaers.rules.RuleException; import gov.nih.nci.cabig.caaers.rules.brxml.Action; import gov.nih.nci.cabig.caaers.rules.brxml.Notification; import gov.nih.nci.cabig.caaers.rules.runtime.RuleContext; import java.util.logging.Level; import java.util.logging.Logger; import org.springframework.context.ApplicationContext; /** * * @author Sujith Vellat Thayyilthodi * */ public class ActionDispatcher { Logger log = Logger.getLogger(ActionDispatcher.class.toString()); private ApplicationContext applicationContext; public ActionDispatcher() { //Hard coding now...this value should be pluggable } public void dispatchAction(String actionId, RuleContext ruleContext) throws Exception{ try { //instantiate the Mock-ScheduleReport /* ReportSchedule schedule = MockObjectFactory.getReportSchedule(); NotificationCalendarTemplate template = MockObjectFactory.getNotificationCalendarTemplate(); schedule.applyNotificationCalendarTemplate(template); //Invoke the webservice of Scheduler String endPointOrg = (String.valueOf(System.getenv("OS")).contains("Win")) ? "http://localhost:8080/scheduler/services/SchedulerService" : "http://10.10.10.2:8031/scheduler/services/SchedulerService"; ObjectServiceFactory factory = new JaxbServiceFactory(); *//* Service serviceModel = factory.create(SchedulerService.class); SchedulerService service = (SchedulerService) new XFireProxyFactory().create(serviceModel, endPointOrg); service.scheduleNotification(schedule); */ } catch (Throwable e) { e.printStackTrace(); log.log(Level.SEVERE, "error", e); } } public void dispatchActionOld(String actionId, RuleContext ruleContext) { ActionContext actionContext = new ActionContext(); actionContext.setActionId(actionId); Action action = actionContext.getAction(); NotificationHandler notificationHandler = null; if(action instanceof Notification) { Notification notification = (Notification)action; String actionHandlerClass = notification.getActionHandlerClass(); if(actionHandlerClass == null) { //actionHandlerClass = DefaultEmailNotificationHandler.class.getName(); log.info("Could not find a actionHandler class. Using the Default class " + actionHandlerClass); //bean name .. hard coding now ...needs to be pluggable... notificationHandler = (NotificationHandler)this.applicationContext.getBean("defaultEmailNotificationHandler"); } else{ notificationHandler = (NotificationHandler)loadObject(actionHandlerClass); } notificationHandler.performNotify(actionContext, ruleContext); } } public Object loadObject(String className) { try { return loadClass(className).newInstance(); } catch (InstantiationException e) { throw new RuleException(e.getMessage(), e); } catch (IllegalAccessException e) { throw new RuleException(e.getMessage(), e); } } public Class loadClass(String className)throws RuleException { try { return Class.forName(className, true, Thread.currentThread().getContextClassLoader()); } catch (ClassNotFoundException e) { throw new RuleException(e.getMessage(), e); } } public ApplicationContext getApplicationContext() { return applicationContext; } public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } }
projects/rules/src/main/java/gov/nih/nci/cabig/caaers/rules/runtime/action/ActionDispatcher.java
package gov.nih.nci.cabig.caaers.rules.runtime.action; import gov.nih.nci.cabig.caaers.rules.RuleException; import gov.nih.nci.cabig.caaers.rules.brxml.Action; import gov.nih.nci.cabig.caaers.rules.brxml.Notification; import gov.nih.nci.cabig.caaers.rules.notification.MockObjectFactory; import gov.nih.nci.cabig.caaers.rules.notification.NotificationCalendarTemplate; import gov.nih.nci.cabig.caaers.rules.notification.ReportSchedule; import gov.nih.nci.cabig.caaers.rules.runtime.RuleContext; import java.util.logging.Level; import java.util.logging.Logger; import org.codehaus.xfire.jaxb2.JaxbServiceFactory; import org.codehaus.xfire.service.binding.ObjectServiceFactory; import org.springframework.context.ApplicationContext; /** * * @author Sujith Vellat Thayyilthodi * */ public class ActionDispatcher { Logger log = Logger.getLogger(ActionDispatcher.class.toString()); private ApplicationContext applicationContext; public ActionDispatcher() { //Hard coding now...this value should be pluggable } public void dispatchAction(String actionId, RuleContext ruleContext) throws Exception{ try { //instantiate the Mock-ScheduleReport ReportSchedule schedule = MockObjectFactory.getReportSchedule(); NotificationCalendarTemplate template = MockObjectFactory.getNotificationCalendarTemplate(); schedule.applyNotificationCalendarTemplate(template); //Invoke the webservice of Scheduler String endPointOrg = (String.valueOf(System.getenv("OS")).contains("Win")) ? "http://localhost:8080/scheduler/services/SchedulerService" : "http://10.10.10.2:8031/scheduler/services/SchedulerService"; ObjectServiceFactory factory = new JaxbServiceFactory(); /* Service serviceModel = factory.create(SchedulerService.class); SchedulerService service = (SchedulerService) new XFireProxyFactory().create(serviceModel, endPointOrg); service.scheduleNotification(schedule); */ } catch (Throwable e) { e.printStackTrace(); log.log(Level.SEVERE, "error", e); } } public void dispatchActionOld(String actionId, RuleContext ruleContext) { ActionContext actionContext = new ActionContext(); actionContext.setActionId(actionId); Action action = actionContext.getAction(); NotificationHandler notificationHandler = null; if(action instanceof Notification) { Notification notification = (Notification)action; String actionHandlerClass = notification.getActionHandlerClass(); if(actionHandlerClass == null) { //actionHandlerClass = DefaultEmailNotificationHandler.class.getName(); log.info("Could not find a actionHandler class. Using the Default class " + actionHandlerClass); //bean name .. hard coding now ...needs to be pluggable... notificationHandler = (NotificationHandler)this.applicationContext.getBean("defaultEmailNotificationHandler"); } else{ notificationHandler = (NotificationHandler)loadObject(actionHandlerClass); } notificationHandler.performNotify(actionContext, ruleContext); } } public Object loadObject(String className) { try { return loadClass(className).newInstance(); } catch (InstantiationException e) { throw new RuleException(e.getMessage(), e); } catch (IllegalAccessException e) { throw new RuleException(e.getMessage(), e); } } public Class loadClass(String className)throws RuleException { try { return Class.forName(className, true, Thread.currentThread().getContextClassLoader()); } catch (ClassNotFoundException e) { throw new RuleException(e.getMessage(), e); } } public ApplicationContext getApplicationContext() { return applicationContext; } public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } }
SVN-Revision: 1789
projects/rules/src/main/java/gov/nih/nci/cabig/caaers/rules/runtime/action/ActionDispatcher.java
Java
mit
bbab13ace57023ff0098c4bde762a2be4e8ccb6c
0
Blackrush/acara
package com.github.blackrush.acara; import com.github.blackrush.acara.dispatch.Dispatcher; import com.github.blackrush.acara.dispatch.DispatcherLookup; import com.github.blackrush.acara.supervisor.Supervisor; import com.github.blackrush.acara.supervisor.event.SupervisedEvent; import com.google.common.collect.ImmutableList; import com.google.common.collect.LinkedListMultimap; import com.google.common.collect.ListMultimap; import org.fungsi.Either; import org.fungsi.Throwables; import org.fungsi.concurrent.Future; import org.fungsi.concurrent.Futures; import org.fungsi.concurrent.Worker; import org.fungsi.function.UnsafeFunction; import org.slf4j.Logger; import java.util.*; import java.util.concurrent.locks.StampedLock; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.github.blackrush.acara.StreamUtils.asStream; import static java.util.Objects.requireNonNull; import static org.fungsi.Unit.unit; final class EventBusImpl implements EventBus { class Listener { final ListenerMetadata metadata; final Dispatcher dispatcher; final Object instance; Listener(ListenerMetadata metadata, Dispatcher dispatcher, Object instance) { this.metadata = metadata; this.dispatcher = dispatcher; this.instance = instance; } } class EventWithListeners { final Object event; final Collection<Listener> listeners; EventWithListeners(Object event, Collection<Listener> listeners) { this.event = event; this.listeners = listeners; } } private final Worker worker; private final boolean defaultAsync; private final ListenerMetadataLookup metadataLookup; private final DispatcherLookup dispatcherLookup; private final Supervisor supervisor; private final EventMetadataLookup eventMetadataLookup; private final Logger logger; final ListMultimap<EventMetadata, Listener> listeners = LinkedListMultimap.create(); private final StampedLock lock = new StampedLock(); EventBusImpl(Worker worker, boolean defaultAsync, ListenerMetadataLookup metadataLookup, DispatcherLookup dispatcherLookup, Supervisor supervisor, EventMetadataLookup eventMetadataLookup, Logger logger) { this.worker = requireNonNull(worker, "worker"); this.defaultAsync = defaultAsync; this.metadataLookup = requireNonNull(metadataLookup, "metadataLookup"); this.dispatcherLookup = requireNonNull(dispatcherLookup, "dispatcherLookup"); this.supervisor = requireNonNull(supervisor, "supervisor"); this.eventMetadataLookup = requireNonNull(eventMetadataLookup, "eventMetadataLookup"); this.logger = requireNonNull(logger, "logger"); } private static Stream<EventMetadata> resolveHierarchy(EventMetadata lowestEvent) { return StreamUtils.collect(Stream.of(lowestEvent), EventMetadata::getParent).distinct(); } @SuppressWarnings("unchecked") Future<List<Object>> doDispatch(Object event, Collection<Listener> listeners, boolean supervise) { List<Object> immediate = new LinkedList<>(); List<Future<Object>> futures = new LinkedList<>(); List<SupervisedEvent> supervisedEvents = new LinkedList<>(); for (Listener listener : listeners) { Either<Object, Throwable> result = listener.dispatcher.dispatch(listener.instance, event); if (result.isLeft()) { Object o = result.left(); if (o != null && o != unit()) { if (o instanceof Future) { futures.add((Future<Object>) o); } else { immediate.add(o); } } } else { Throwable failure = result.right(); if (!supervise) { throw Throwables.propagate(failure); } switch (supervisor.handle(failure)) { case ESCALATE: throw Throwables.propagate(failure); case IGNORE: logger.warn("uncaught exception", failure); break; case NEW_EVENT: supervisedEvents.add(new SupervisedEvent(event, failure)); break; } } } getMultipleListeners(supervisedEvents).forEach(x -> doDispatch(x.event, x.listeners, false)); return Futures.collect(futures).map(results -> { immediate.addAll(results); return immediate; }); } Stream<Listener> readListeners(Stream<EventMetadata> meta) { return meta.flatMap(it -> listeners.get(it).stream()); } List<Listener> getListeners(Object event) { EventMetadata meta = eventMetadataLookup.lookup(event) .orElseThrow(() -> new IllegalStateException("couldn't lookup metadata for event " + event)) ; List<EventMetadata> parents = resolveHierarchy(meta).collect(Collectors.toList()); if (parents.isEmpty()) return ImmutableList.of(); long stamp = lock.tryOptimisticRead(); List<Listener> res = readListeners(parents.stream()).collect(Collectors.toList()); if (lock.validate(stamp)) { return res; } stamp = lock.readLock(); try { return readListeners(parents.stream()).collect(Collectors.toList()); } finally { lock.unlockRead(stamp); } } List<EventWithListeners> getMultipleListeners(List<?> events) { if (events.isEmpty()) { return Collections.emptyList(); } long stamp = lock.readLock(); try { List<EventWithListeners> result = new LinkedList<>(); for (Object event : events) { List<Listener> listeners = resolveHierarchy(eventMetadataLookup.lookup(event).get()) .flatMap(meta -> this.listeners.get(meta).stream()) .collect(Collectors.toList()); if (!listeners.isEmpty()) { result.add(new EventWithListeners(event, listeners)); } } return result; } finally { lock.unlockRead(stamp); } } @Override public Future<List<Object>> publishAsync(Object event) { Collection<Listener> listeners = getListeners(event); return worker.submit(() -> doDispatch(event, listeners, true)).flatMap(UnsafeFunction.identity()); } @Override public List<Object> publishSync(Object event) { Collection<Listener> listeners = getListeners(event); return doDispatch(event, listeners, true).get(); } @Override public Future<List<Object>> publish(Object event) { if (defaultAsync) { return publishAsync(event); } else { try { return Futures.success(publishSync(event)); } catch (Throwable cause) { return Futures.failure(cause); // see SupervisorDirective.ESCALATE } } } private void addListeners(List<Listener> listeners) { long stamp = lock.writeLock(); try { for (Listener listener : listeners) { this.listeners.put(listener.metadata.getHandledEventMetadata(), listener); } } finally { lock.unlockWrite(stamp); } } private void removeListeners(Predicate<Listener> fn) { long stamp = lock.readLock(); try { boolean remove = false; Iterator<Listener> it = listeners.values().iterator(); while (it.hasNext()) { Listener listener = it.next(); if (fn.test(listener)) { if (!remove) { long writeLock = lock.tryConvertToWriteLock(stamp); if (writeLock != 0L) { stamp = writeLock; } else { lock.unlockRead(stamp); stamp = lock.writeLock(); } } it.remove(); remove = true; } } } finally { lock.unlock(stamp); } } private Stream<Listener> createListeners(Object subscriber) { return metadataLookup.lookup(subscriber) .flatMap(m -> asStream(dispatcherLookup.lookup(m)) .map(d -> new Listener(m, d, subscriber))) ; } @Override public EventBus subscribe(Object subscriber) { List<Listener> listeners = createListeners(subscriber).collect(Collectors.toList()); if (!listeners.isEmpty()) { addListeners(listeners); } return this; } @Override public EventBus subscribeMany(Collection<?> subscribers) { List<Listener> listeners = subscribers.stream().flatMap(this::createListeners).collect(Collectors.toList()); if (!listeners.isEmpty()) { addListeners(listeners); } return this; } @Override public void unsubscribe(Object subscriber) { removeListeners(it -> it.instance == subscriber); } @Override public void unsubscribeMany(Collection<?> listeners) { removeListeners(it -> listeners.contains(it.instance)); } }
core/src/main/java/com/github/blackrush/acara/EventBusImpl.java
package com.github.blackrush.acara; import com.github.blackrush.acara.dispatch.Dispatcher; import com.github.blackrush.acara.dispatch.DispatcherLookup; import com.github.blackrush.acara.supervisor.Supervisor; import com.github.blackrush.acara.supervisor.event.SupervisedEvent; import com.google.common.collect.ImmutableList; import com.google.common.collect.LinkedListMultimap; import com.google.common.collect.ListMultimap; import org.fungsi.Either; import org.fungsi.Throwables; import org.fungsi.concurrent.Future; import org.fungsi.concurrent.Futures; import org.fungsi.concurrent.Worker; import org.fungsi.function.UnsafeFunction; import org.slf4j.Logger; import java.util.*; import java.util.concurrent.locks.StampedLock; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.github.blackrush.acara.StreamUtils.asStream; import static java.util.Objects.requireNonNull; import static org.fungsi.Unit.unit; final class EventBusImpl implements EventBus { class Listener { final ListenerMetadata metadata; final Dispatcher dispatcher; final Object instance; Listener(ListenerMetadata metadata, Dispatcher dispatcher, Object instance) { this.metadata = metadata; this.dispatcher = dispatcher; this.instance = instance; } } class EventWithListeners { final Object event; final Collection<Listener> listeners; EventWithListeners(Object event, Collection<Listener> listeners) { this.event = event; this.listeners = listeners; } } private final Worker worker; private final boolean defaultAsync; private final ListenerMetadataLookup metadataLookup; private final DispatcherLookup dispatcherLookup; private final Supervisor supervisor; private final EventMetadataLookup eventMetadataLookup; private final Logger logger; final ListMultimap<EventMetadata, Listener> listeners = LinkedListMultimap.create(); private final StampedLock lock = new StampedLock(); EventBusImpl(Worker worker, boolean defaultAsync, ListenerMetadataLookup metadataLookup, DispatcherLookup dispatcherLookup, Supervisor supervisor, EventMetadataLookup eventMetadataLookup, Logger logger) { this.worker = requireNonNull(worker, "worker"); this.defaultAsync = defaultAsync; this.metadataLookup = requireNonNull(metadataLookup, "metadataLookup"); this.dispatcherLookup = requireNonNull(dispatcherLookup, "dispatcherLookup"); this.supervisor = requireNonNull(supervisor, "supervisor"); this.eventMetadataLookup = requireNonNull(eventMetadataLookup, "eventMetadataLookup"); this.logger = requireNonNull(logger, "logger"); } private static Stream<EventMetadata> resolveHierarchy(EventMetadata lowestEvent) { return StreamUtils.collect(Stream.of(lowestEvent), EventMetadata::getParent).distinct(); } @SuppressWarnings("unchecked") Future<List<Object>> doDispatch(Object event, Collection<Listener> listeners) { List<Object> immediate = new LinkedList<>(); List<Future<Object>> futures = new LinkedList<>(); List<SupervisedEvent> supervisedEvents = new LinkedList<>(); for (Listener listener : listeners) { Either<Object, Throwable> result = listener.dispatcher.dispatch(listener.instance, event); if (result.isLeft()) { Object o = result.left(); if (o != null && o != unit()) { if (o instanceof Future) { futures.add((Future<Object>) o); } else { immediate.add(o); } } } else { Throwable failure = result.right(); switch (supervisor.handle(failure)) { case ESCALATE: throw Throwables.propagate(failure); case IGNORE: logger.warn("uncaught exception", failure); break; case NEW_EVENT: supervisedEvents.add(new SupervisedEvent(event, failure)); break; } } } getMultipleListeners(supervisedEvents).forEach(x -> doDispatch(x.event, x.listeners)); return Futures.collect(futures).map(results -> { immediate.addAll(results); return immediate; }); } Stream<Listener> readListeners(Stream<EventMetadata> meta) { return meta.flatMap(it -> listeners.get(it).stream()); } List<Listener> getListeners(Object event) { EventMetadata meta = eventMetadataLookup.lookup(event) .orElseThrow(() -> new IllegalStateException("couldn't lookup metadata for event " + event)) ; List<EventMetadata> parents = resolveHierarchy(meta).collect(Collectors.toList()); if (parents.isEmpty()) return ImmutableList.of(); long stamp = lock.tryOptimisticRead(); List<Listener> res = readListeners(parents.stream()).collect(Collectors.toList()); if (lock.validate(stamp)) { return res; } stamp = lock.readLock(); try { return readListeners(parents.stream()).collect(Collectors.toList()); } finally { lock.unlockRead(stamp); } } List<EventWithListeners> getMultipleListeners(List<?> events) { if (events.isEmpty()) { return Collections.emptyList(); } long stamp = lock.readLock(); try { List<EventWithListeners> result = new LinkedList<>(); for (Object event : events) { List<Listener> listeners = resolveHierarchy(eventMetadataLookup.lookup(event).get()) .flatMap(meta -> this.listeners.get(meta).stream()) .collect(Collectors.toList()); if (!listeners.isEmpty()) { result.add(new EventWithListeners(event, listeners)); } } return result; } finally { lock.unlockRead(stamp); } } @Override public Future<List<Object>> publishAsync(Object event) { Collection<Listener> listeners = getListeners(event); return worker.submit(() -> doDispatch(event, listeners)).flatMap(UnsafeFunction.identity()); } @Override public List<Object> publishSync(Object event) { Collection<Listener> listeners = getListeners(event); return doDispatch(event, listeners).get(); } @Override public Future<List<Object>> publish(Object event) { if (defaultAsync) { return publishAsync(event); } else { try { return Futures.success(publishSync(event)); } catch (Throwable cause) { return Futures.failure(cause); // see SupervisorDirective.ESCALATE } } } private void addListeners(List<Listener> listeners) { long stamp = lock.writeLock(); try { for (Listener listener : listeners) { this.listeners.put(listener.metadata.getHandledEventMetadata(), listener); } } finally { lock.unlockWrite(stamp); } } private void removeListeners(Predicate<Listener> fn) { long stamp = lock.readLock(); try { boolean remove = false; Iterator<Listener> it = listeners.values().iterator(); while (it.hasNext()) { Listener listener = it.next(); if (fn.test(listener)) { if (!remove) { long writeLock = lock.tryConvertToWriteLock(stamp); if (writeLock != 0L) { stamp = writeLock; } else { lock.unlockRead(stamp); stamp = lock.writeLock(); } } it.remove(); remove = true; } } } finally { lock.unlock(stamp); } } private Stream<Listener> createListeners(Object subscriber) { return metadataLookup.lookup(subscriber) .flatMap(m -> asStream(dispatcherLookup.lookup(m)) .map(d -> new Listener(m, d, subscriber))) ; } @Override public EventBus subscribe(Object subscriber) { List<Listener> listeners = createListeners(subscriber).collect(Collectors.toList()); if (!listeners.isEmpty()) { addListeners(listeners); } return this; } @Override public EventBus subscribeMany(Collection<?> subscribers) { List<Listener> listeners = subscribers.stream().flatMap(this::createListeners).collect(Collectors.toList()); if (!listeners.isEmpty()) { addListeners(listeners); } return this; } @Override public void unsubscribe(Object subscriber) { removeListeners(it -> it.instance == subscriber); } @Override public void unsubscribeMany(Collection<?> listeners) { removeListeners(it -> listeners.contains(it.instance)); } }
only supervise top-level published events (ie. the one through #publish #publishAsync #publishSync)
core/src/main/java/com/github/blackrush/acara/EventBusImpl.java
only supervise top-level published events (ie. the one through #publish #publishAsync #publishSync)
Java
mit
353d706754db9fb54258b70a8cb99f93066bbca4
0
madumlao/oxCore,GluuFederation/oxCore
/* * oxCore is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text. * * Copyright (c) 2014, Gluu */package org.xdi.service.metric; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import org.gluu.site.ldap.persistence.LdapEntryManager; import org.gluu.site.ldap.persistence.exception.EntryPersistenceException; import org.jboss.seam.Component; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Logger; import org.jboss.seam.annotations.Observer; import org.jboss.seam.annotations.async.Asynchronous; import org.jboss.seam.contexts.Contexts; import org.jboss.seam.contexts.Lifecycle; import org.jboss.seam.log.Log; import org.xdi.ldap.model.SimpleBranch; import org.xdi.model.ApplicationType; import org.xdi.model.metric.MetricType; import org.xdi.model.metric.ldap.MetricEntry; import org.xdi.util.StringHelper; import com.codahale.metrics.Counter; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.Timer; import com.unboundid.ldap.sdk.Filter; /** * Metric service * * @author Yuriy Movchan Date: 07/27/2015 */ public abstract class MetricService implements Serializable { private static final long serialVersionUID = -3393618600428448743L; private static final String EVENT_TYPE = "MetricServiceTimerEvent"; private static final int DEFAULT_METRIC_REPORTER_INTERVAL = 60; private static final SimpleDateFormat PERIOD_DATE_FORMAT = new SimpleDateFormat("yyyyMM"); private static final AtomicLong initialId = new AtomicLong(System.currentTimeMillis()); private MetricRegistry metricRegistry; private Set<MetricType> registeredMetricTypes; @Logger private Log log; @In private LdapEntryManager ldapEntryManager; public void init(int metricInterval) { this.metricRegistry = new MetricRegistry(); this.registeredMetricTypes = new HashSet<MetricType>(); LdapEntryReporter ldapEntryReporter = LdapEntryReporter.forRegistry(this.metricRegistry, getComponentName()).build(); int metricReporterInterval = metricInterval; if (metricReporterInterval <= 0) { metricReporterInterval = DEFAULT_METRIC_REPORTER_INTERVAL; } ldapEntryReporter.start(metricReporterInterval, TimeUnit.SECONDS); } @Observer(EVENT_TYPE) @Asynchronous public void writeMetricEntries(List<MetricEntry> metricEntries, Date creationTime) { add(metricEntries, creationTime); } public void addBranch(String branchDn, String ou) { SimpleBranch branch = new SimpleBranch(); branch.setOrganizationalUnitName(ou); branch.setDn(branchDn); ldapEntryManager.persist(branch); } public boolean containsBranch(String branchDn) { return ldapEntryManager.contains(SimpleBranch.class, branchDn); } public void createBranch(String branchDn, String ou) { try { addBranch(branchDn, ou); } catch (EntryPersistenceException ex) { // Check if another process added this branch already if (!containsBranch(branchDn)) { throw ex; } } } public void prepareBranch(Date creationDate, ApplicationType applicationType) { String baseDn = buildDn(null, creationDate, applicationType); // Create ou=YYYY-MM branch if needed if (!containsBranch(baseDn)) { // Create ou=application_type branch if needed String applicationBaseDn = buildDn(null, null, applicationType); if (!containsBranch(applicationBaseDn)) { // Create ou=appliance_inum branch if needed String applianceBaseDn = buildDn(null, null, null); if (!containsBranch(applianceBaseDn)) { createBranch(applianceBaseDn, applianceInum()); } createBranch(applicationBaseDn, applicationType.getValue()); } createBranch(baseDn, PERIOD_DATE_FORMAT.format(creationDate)); } } @Asynchronous public void add(List<MetricEntry> metricEntries, Date creationTime) { prepareBranch(creationTime, ApplicationType.OX_AUTH); for (MetricEntry metricEntry : metricEntries) { ldapEntryManager.persist(metricEntry); } } public void add(MetricEntry metricEntry) { prepareBranch(metricEntry.getCreationDate(), metricEntry.getApplicationType()); ldapEntryManager.persist(metricEntry); } public void update(MetricEntry metricEntry) { prepareBranch(metricEntry.getCreationDate(), metricEntry.getApplicationType()); ldapEntryManager.merge(metricEntry); } public void remove(MetricEntry metricEntry) { prepareBranch(metricEntry.getCreationDate(), metricEntry.getApplicationType()); ldapEntryManager.remove(metricEntry); } public void removeBranch(String branchDn) { ldapEntryManager.removeWithSubtree(branchDn); } public MetricEntry getMetricEntryByDn(MetricType metricType, String metricEventDn) { return ldapEntryManager.find(metricType.getMetricEntryType(), metricEventDn); } public Map<MetricType, List<MetricEntry>> findMetricEntry(ApplicationType applicationType, String applianceInum, List<MetricType> metricTypes, Date startDate, Date endDate, String... returnAttributes) { prepareBranch(null, applicationType); Map<MetricType, List<MetricEntry>> result = new HashMap<MetricType, List<MetricEntry>>(); if ((metricTypes == null) || (metricTypes.size() == 0)) { return result; } // Prepare list of DNs Set<String> metricDns = getBaseDnForPeriod(applicationType, applianceInum, startDate, endDate); if (metricDns.size() == 0) { return result; } for (MetricType metricType : metricTypes) { List<MetricEntry> metricTypeResult = new LinkedList<MetricEntry>(); for (String metricDn : metricDns) { List<Filter> metricTypeFilters = new ArrayList<Filter>(); Filter applicationTypeFilter = Filter.createEqualityFilter("oxApplicationType", applicationType.getValue()); Filter eventTypeTypeFilter = Filter.createEqualityFilter("oxMetricType", metricType.getValue()); Filter startDateFilter = Filter.createGreaterOrEqualFilter("oxStartDate", ldapEntryManager.encodeGeneralizedTime((startDate))); Filter endDateFilter = Filter.createLessOrEqualFilter("oxEndDate", ldapEntryManager.encodeGeneralizedTime(endDate)); metricTypeFilters.add(applicationTypeFilter); metricTypeFilters.add(eventTypeTypeFilter); metricTypeFilters.add(startDateFilter); metricTypeFilters.add(endDateFilter); Filter filter = Filter.createANDFilter(metricTypeFilters); List<MetricEntry> metricTypeMonthResult = (List<MetricEntry>) ldapEntryManager.findEntries(metricDn, metricType.getMetricEntryType(), returnAttributes, filter); metricTypeResult.addAll(metricTypeMonthResult); } result.put(metricType, metricTypeResult); } return result; } public List<MetricEntry> getExpiredMetricEntries(String baseDnForPeriod, Date expirationDate) { Filter expiratioFilter = Filter.createLessOrEqualFilter("oxStartDate", ldapEntryManager.encodeGeneralizedTime(expirationDate)); List<MetricEntry> metricEntries = ldapEntryManager.findEntries(baseDnForPeriod, MetricEntry.class, new String[] { "uniqueIdentifier" }, expiratioFilter); return metricEntries; } public Set<String> findAllPeriodBranches(ApplicationType applicationType, String applianceInum) { String baseDn = buildDn(null, null, applicationType, applianceInum); Filter skipRootDnFilter = Filter.createNOTFilter(Filter.createEqualityFilter("ou", applicationType.getValue())); List<SimpleBranch> periodBranches = (List<SimpleBranch>) ldapEntryManager.findEntries(baseDn, SimpleBranch.class, new String[] { "ou" }, skipRootDnFilter); Set<String> periodBranchesStrings = new HashSet<String>(); for (SimpleBranch periodBranch: periodBranches) { if (!StringHelper.equalsIgnoreCase(baseDn, periodBranch.getDn())) { periodBranchesStrings.add(periodBranch.getDn()); } } return periodBranchesStrings; } public void removeExpiredMetricEntries(Date expirationDate, ApplicationType applicationType, String applianceInum) { Set<String> keepBaseDnForPeriod = getBaseDnForPeriod(applicationType, applianceInum, expirationDate, new Date()); Set<String> allBaseDnForPeriod = findAllPeriodBranches(applicationType, applianceInum); allBaseDnForPeriod.removeAll(keepBaseDnForPeriod); // Remove expired months for (String baseDnForPeriod : allBaseDnForPeriod) { removeBranch(baseDnForPeriod); } // Remove expired entries for (String baseDnForPeriod : keepBaseDnForPeriod) { List<MetricEntry> expiredMetricEntries = getExpiredMetricEntries(baseDnForPeriod, expirationDate); for (MetricEntry expiredMetricEntry : expiredMetricEntries) { remove(expiredMetricEntry); } } } private Set<String> getBaseDnForPeriod(ApplicationType applicationType, String applianceInum, Date startDate, Date endDate) { Calendar cal = Calendar.getInstance(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTime(startDate); Set<String> metricDns = new HashSet<String>(); while (cal.getTime().before(endDate) || cal.getTime().equals(endDate)) { Date currentStartDate = cal.getTime(); String baseDn = buildDn(null, currentStartDate, applicationType, applianceInum); if (!containsBranch(baseDn)) { cal.add(Calendar.DAY_OF_MONTH , 1); continue; } metricDns.add(baseDn); if (cal.getTime().equals(endDate)) { break; } else { cal.add(Calendar.DAY_OF_MONTH , 1); if (cal.getTime().after(endDate)) { cal.setTime(endDate); } } } return metricDns; } public String getuUiqueIdentifier() { return String.valueOf(initialId.incrementAndGet()); } public Counter getCounter(MetricType metricType) { if (!registeredMetricTypes.contains(metricType)) { registeredMetricTypes.add(metricType); } return metricRegistry.counter(metricType.getMetricName()); } public Timer getTimer(MetricType metricType) { if (!registeredMetricTypes.contains(metricType)) { registeredMetricTypes.add(metricType); } return metricRegistry.timer(metricType.getMetricName()); } public void incCounter(MetricType metricType) { Counter counter = getCounter(metricType); counter.inc(); } public String buildDn(String uniqueIdentifier, Date creationDate, ApplicationType applicationType) { return buildDn(uniqueIdentifier, creationDate, applicationType, null); } /* * Should return similar to this pattern DN: * uniqueIdentifier=id,ou=YYYY-MM,ou=application_type,ou=appliance_inum,ou=metric,ou=organization_name,o=gluu */ public String buildDn(String uniqueIdentifier, Date creationDate, ApplicationType applicationType, String currentApplianceInum) { final StringBuilder dn = new StringBuilder(); if (StringHelper.isNotEmpty(uniqueIdentifier) && (creationDate != null) && (applicationType != null)) { dn.append(String.format("uniqueIdentifier=%s,", uniqueIdentifier)); } if ((creationDate != null) && (applicationType != null)) { dn.append(String.format("ou=%s,", PERIOD_DATE_FORMAT.format(creationDate))); } if (applicationType != null) { dn.append(String.format("ou=%s,", applicationType.getValue())); } if (currentApplianceInum == null) { dn.append(String.format("ou=%s,", applianceInum())); } else { dn.append(String.format("ou=%s,", currentApplianceInum)); } dn.append(baseDn()); return dn.toString(); } public Set<MetricType> getRegisteredMetricTypes() { return registeredMetricTypes; } // Should return ou=metric,o=gluu public abstract String baseDn(); // Should return appliance Inum public abstract String applianceInum(); public abstract String getComponentName(); /** * Get MetricService instance * * @return MetricService instance */ public static MetricService instance() { if (!(Contexts.isEventContextActive() || Contexts.isApplicationContextActive())) { Lifecycle.beginCall(); } return (MetricService) Component.getInstance(MetricService.class); } }
oxService/src/main/java/org/xdi/service/metric/MetricService.java
/* * oxCore is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text. * * Copyright (c) 2014, Gluu */package org.xdi.service.metric; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import org.gluu.site.ldap.persistence.LdapEntryManager; import org.gluu.site.ldap.persistence.exception.EntryPersistenceException; import org.jboss.seam.Component; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Logger; import org.jboss.seam.annotations.Observer; import org.jboss.seam.annotations.async.Asynchronous; import org.jboss.seam.contexts.Contexts; import org.jboss.seam.contexts.Lifecycle; import org.jboss.seam.log.Log; import org.xdi.ldap.model.SimpleBranch; import org.xdi.model.ApplicationType; import org.xdi.model.metric.MetricType; import org.xdi.model.metric.ldap.MetricEntry; import org.xdi.util.StringHelper; import com.codahale.metrics.Counter; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.Timer; import com.unboundid.ldap.sdk.Filter; /** * Metric service * * @author Yuriy Movchan Date: 07/27/2015 */ public abstract class MetricService implements Serializable { private static final long serialVersionUID = -3393618600428448743L; private static final String EVENT_TYPE = "MetricServiceTimerEvent"; private static final int DEFAULT_METRIC_REPORTER_INTERVAL = 60; private static final SimpleDateFormat PERIOD_DATE_FORMAT = new SimpleDateFormat("yyyyMM"); private static final AtomicLong initialId = new AtomicLong(System.currentTimeMillis()); private MetricRegistry metricRegistry; private Set<MetricType> registeredMetricTypes; @Logger private Log log; @In private LdapEntryManager ldapEntryManager; public void init(int metricInterval) { this.metricRegistry = new MetricRegistry(); this.registeredMetricTypes = new HashSet<MetricType>(); LdapEntryReporter ldapEntryReporter = LdapEntryReporter.forRegistry(this.metricRegistry, getComponentName()).build(); int metricReporterInterval = metricInterval; if (metricReporterInterval <= 0) { metricReporterInterval = DEFAULT_METRIC_REPORTER_INTERVAL; } ldapEntryReporter.start(metricReporterInterval, TimeUnit.SECONDS); } @Observer(EVENT_TYPE) @Asynchronous public void writeMetricEntries(List<MetricEntry> metricEntries, Date creationTime) { add(metricEntries, creationTime); } public void addBranch(String branchDn, String ou) { SimpleBranch branch = new SimpleBranch(); branch.setOrganizationalUnitName(ou); branch.setDn(branchDn); ldapEntryManager.persist(branch); } public boolean containsBranch(String branchDn) { return ldapEntryManager.contains(SimpleBranch.class, branchDn); } public void createBranch(String branchDn, String ou) { try { addBranch(branchDn, ou); } catch (EntryPersistenceException ex) { // Check if another process added this branch already if (!containsBranch(branchDn)) { throw ex; } } } public void prepareBranch(Date creationDate, ApplicationType applicationType) { String baseDn = buildDn(null, creationDate, applicationType); // Create ou=YYYY-MM branch if needed if (!containsBranch(baseDn)) { // Create ou=application_type branch if needed String applicationBaseDn = buildDn(null, null, applicationType); if (!containsBranch(applicationBaseDn)) { // Create ou=appliance_inum branch if needed String applianceBaseDn = buildDn(null, null, null); if (!containsBranch(applianceBaseDn)) { createBranch(applianceBaseDn, applianceInum()); } createBranch(applicationBaseDn, applicationType.getValue()); } createBranch(baseDn, PERIOD_DATE_FORMAT.format(creationDate)); } } @Asynchronous public void add(List<MetricEntry> metricEntries, Date creationTime) { prepareBranch(creationTime, ApplicationType.OX_AUTH); for (MetricEntry metricEntry : metricEntries) { ldapEntryManager.persist(metricEntry); } } public void add(MetricEntry metricEntry) { prepareBranch(metricEntry.getCreationDate(), metricEntry.getApplicationType()); ldapEntryManager.persist(metricEntry); } public void update(MetricEntry metricEntry) { prepareBranch(metricEntry.getCreationDate(), metricEntry.getApplicationType()); ldapEntryManager.merge(metricEntry); } public void remove(MetricEntry metricEntry) { prepareBranch(metricEntry.getCreationDate(), metricEntry.getApplicationType()); ldapEntryManager.remove(metricEntry); } public void removeBranch(String branchDn) { ldapEntryManager.removeWithSubtree(branchDn); } public MetricEntry getMetricEntryByDn(MetricType metricType, String metricEventDn) { return ldapEntryManager.find(metricType.getMetricEntryType(), metricEventDn); } public Map<MetricType, List<MetricEntry>> findMetricEntry(ApplicationType applicationType, String applianceInum, List<MetricType> metricTypes, Date startDate, Date endDate, String... returnAttributes) { prepareBranch(null, applicationType); Map<MetricType, List<MetricEntry>> result = new HashMap<MetricType, List<MetricEntry>>(); if ((metricTypes == null) || (metricTypes.size() == 0)) { return result; } // Prepare list of DNs Set<String> metricDns = getBaseDnForPeriod(applicationType, applianceInum, startDate, endDate); if (metricDns.size() == 0) { return result; } for (MetricType metricType : metricTypes) { List<MetricEntry> metricTypeResult = new LinkedList<MetricEntry>(); for (String metricDn : metricDns) { List<Filter> metricTypeFilters = new ArrayList<Filter>(); Filter applicationTypeFilter = Filter.createEqualityFilter("oxApplicationType", applicationType.getValue()); Filter eventTypeTypeFilter = Filter.createEqualityFilter("oxMetricType", metricType.getValue()); Filter startDateFilter = Filter.createGreaterOrEqualFilter("oxStartDate", ldapEntryManager.encodeGeneralizedTime((startDate))); Filter endDateFilter = Filter.createLessOrEqualFilter("oxEndDate", ldapEntryManager.encodeGeneralizedTime(endDate)); metricTypeFilters.add(applicationTypeFilter); metricTypeFilters.add(eventTypeTypeFilter); metricTypeFilters.add(startDateFilter); metricTypeFilters.add(endDateFilter); Filter filter = Filter.createANDFilter(metricTypeFilters); List<MetricEntry> metricTypeMonthResult = (List<MetricEntry>) ldapEntryManager.findEntries(metricDn, metricType.getMetricEntryType(), returnAttributes, filter); metricTypeResult.addAll(metricTypeMonthResult); } result.put(metricType, metricTypeResult); } return result; } public List<MetricEntry> getExpiredMetricEntries(String baseDnForPeriod, Date expirationDate) { Filter expiratioFilter = Filter.createLessOrEqualFilter("oxStartDate", ldapEntryManager.encodeGeneralizedTime(expirationDate)); List<MetricEntry> metricEntries = ldapEntryManager.findEntries(baseDnForPeriod, MetricEntry.class, new String[] { "uniqueIdentifier" }, expiratioFilter); return metricEntries; } public Set<String> findAllPeriodBranches(ApplicationType applicationType, String applianceInum) { String baseDn = buildDn(null, null, applicationType, applianceInum); Filter skipRootDnFilter = Filter.createNOTFilter(Filter.createEqualityFilter("ou", applicationType.getValue())); List<SimpleBranch> periodBranches = (List<SimpleBranch>) ldapEntryManager.findEntries(baseDn, SimpleBranch.class, new String[] { "ou" }, skipRootDnFilter); Set<String> periodBranchesStrings = new HashSet<String>(); for (SimpleBranch periodBranch: periodBranches) { if (!StringHelper.equalsIgnoreCase(baseDn, periodBranch.getDn())) { periodBranchesStrings.add(periodBranch.getDn()); } } return periodBranchesStrings; } public void removeExpiredMetricEntries(Date expirationDate, ApplicationType applicationType, String applianceInum) { Set<String> keepBaseDnForPeriod = getBaseDnForPeriod(applicationType, applianceInum, expirationDate, new Date()); Set<String> allBaseDnForPeriod = findAllPeriodBranches(applicationType, applianceInum); allBaseDnForPeriod.removeAll(keepBaseDnForPeriod); // Remove expired months for (String baseDnForPeriod : allBaseDnForPeriod) { removeBranch(baseDnForPeriod); } // Remove expired entries for (String baseDnForPeriod : keepBaseDnForPeriod) { List<MetricEntry> expiredMetricEntries = getExpiredMetricEntries(baseDnForPeriod, expirationDate); for (MetricEntry expiredMetricEntry : expiredMetricEntries) { remove(expiredMetricEntry); } } } private Set<String> getBaseDnForPeriod(ApplicationType applicationType, String applianceInum, Date startDate, Date endDate) { Calendar cal = Calendar.getInstance(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTime(startDate); Set<String> metricDns = new HashSet<String>(); while (cal.getTime().before(endDate) || cal.getTime().equals(endDate)) { Date currentStartDate = cal.getTime(); String baseDn = buildDn(null, currentStartDate, applicationType, applianceInum); if (!containsBranch(baseDn)) { continue; } metricDns.add(baseDn); if (cal.getTime().equals(endDate)) { break; } else { cal.add(Calendar.MONTH , 1); if (cal.getTime().after(endDate)) { cal.setTime(endDate); } } } return metricDns; } public String getuUiqueIdentifier() { return String.valueOf(initialId.incrementAndGet()); } public Counter getCounter(MetricType metricType) { if (!registeredMetricTypes.contains(metricType)) { registeredMetricTypes.add(metricType); } return metricRegistry.counter(metricType.getMetricName()); } public Timer getTimer(MetricType metricType) { if (!registeredMetricTypes.contains(metricType)) { registeredMetricTypes.add(metricType); } return metricRegistry.timer(metricType.getMetricName()); } public void incCounter(MetricType metricType) { Counter counter = getCounter(metricType); counter.inc(); } public String buildDn(String uniqueIdentifier, Date creationDate, ApplicationType applicationType) { return buildDn(uniqueIdentifier, creationDate, applicationType, null); } /* * Should return similar to this pattern DN: * uniqueIdentifier=id,ou=YYYY-MM,ou=application_type,ou=appliance_inum,ou=metric,ou=organization_name,o=gluu */ public String buildDn(String uniqueIdentifier, Date creationDate, ApplicationType applicationType, String currentApplianceInum) { final StringBuilder dn = new StringBuilder(); if (StringHelper.isNotEmpty(uniqueIdentifier) && (creationDate != null) && (applicationType != null)) { dn.append(String.format("uniqueIdentifier=%s,", uniqueIdentifier)); } if ((creationDate != null) && (applicationType != null)) { dn.append(String.format("ou=%s,", PERIOD_DATE_FORMAT.format(creationDate))); } if (applicationType != null) { dn.append(String.format("ou=%s,", applicationType.getValue())); } if (currentApplianceInum == null) { dn.append(String.format("ou=%s,", applianceInum())); } else { dn.append(String.format("ou=%s,", currentApplianceInum)); } dn.append(baseDn()); return dn.toString(); } public Set<MetricType> getRegisteredMetricTypes() { return registeredMetricTypes; } // Should return ou=metric,o=gluu public abstract String baseDn(); // Should return appliance Inum public abstract String applianceInum(); public abstract String getComponentName(); /** * Get MetricService instance * * @return MetricService instance */ public static MetricService instance() { if (!(Contexts.isEventContextActive() || Contexts.isApplicationContextActive())) { Lifecycle.beginCall(); } return (MetricService) Component.getInstance(MetricService.class); } }
repeated bug
oxService/src/main/java/org/xdi/service/metric/MetricService.java
repeated bug
Java
mit
469ac1ea89db6a84e08ed390ffd0508d9899ab6b
0
tobiatesan/serleena-android,tobiatesan/serleena-android
/////////////////////////////////////////////////////////////////////////////// // // This file is part of Serleena. // // The MIT License (MIT) // // Copyright (C) 2015 Antonio Cavestro, Gabriele Pozzan, Matteo Lisotto, // Nicola Mometto, Filippo Sestini, Tobia Tesan, Sebastiano Valle. // // 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. // /////////////////////////////////////////////////////////////////////////////// /** * Name: ITelemetry * Package: com.hitchikers.serleena.model * Author: Tobia Tesan <[email protected]> * Date: 2015-05-05 * * History: * Version Programmer Date Changes * 1.0 Tobia Tesan 2015-05-05 Creazione del file */ package com.kyloth.serleena.model; import com.kyloth.serleena.common.GeoPoint; import com.kyloth.serleena.common.LocationTelemetryEvent; import com.kyloth.serleena.common.TelemetryEvent; import com.kyloth.serleena.common.TelemetryEventType; /** * Interfaccia realizzata da oggetti che rappresentano un * Tracciamento * * @author Tobia Tesan <[email protected]> * @version 1.0 * @since 1.0 */ public interface ITelemetry { /** * Restituisce gli eventi che costituiscono il Tracciamento. * * @return Un Iterable che contiene tutti gli eventi del Tracciamento. * @version 1.0 */ public Iterable<TelemetryEvent> getEvents(); /** * Restituisce gli eventi che costituiscono il Tracciamento, filtrati * secondo un intervallo di tempo specificato. * * @return Insieme enumerabile che contiene tutti gli eventi del * Tracciamento compresi nell'intervallo di secondi specificato. * @param from L'inizio dell'intervallo, comprensivo degli * eventi da restituire, espresso in secondi dall'avvio del * Tracciamento. * Se from > to, viene sollevata un'eccezione * IllegalArgumentException. * @param to L'inizio dell'intervallo, comprensivo degli * eventi da restituire, espresso in secondi dall'avvio del * Tracciamento. * Se from > to, viene sollevata un'eccezione * IllegalArgumentException. * @version 1.0 */ public Iterable<TelemetryEvent> getEvents(int from, int to) throws IllegalArgumentException; /** * Restituisce gli eventi che costituiscono il Tracciamento, filtrati in * base a uno specifico tipo di evento. * * @return Insieme enumerabile che contiene tutti e soli gli eventi del * Tracciamento di tipo specificato. * @param type Tipo di eventi da restituire. * @return Insieme enumerabile di eventi di Tracciamento. */ public Iterable<TelemetryEvent> getEvents(TelemetryEventType type) throws NoSuchTelemetryEventException; /** * Restituisce l'evento del Tracciamento registrato in prossimità dellal * posizione specificata, secondo una tolleranza. * Se non è possibile trovare un evento che soddisfi i valori * specificati, viene sollevata un'eccezione NoSuchTelemetryEventException. * * @param loc Posizione campionata dall'evento che si vuole ottenere. Se * null, viene sollevata un'eccezione IllegalArgumentException. * @param tolerance Tolleranza, in metri, indicante quanto la posizione * registrata dall'evento restituito può discostarsi dal * valore richiesto. Se < 0, viene sollevata * un'eccezione IllegalOperationException. * @return Evento di Tracciamento. * @throws NoSuchTelemetryEventException * @throws IllegalArgumentException */ public LocationTelemetryEvent getEventAtLocation(GeoPoint loc, int tolerance) throws NoSuchTelemetryEventException, IllegalArgumentException; /** * Restituisce la durata totale del Tracciamento. * * @return Durata temporale in secondi del Tracciamento. * @version 1.0 */ public int getDuration(); }
serleena/app/src/main/java/com/kyloth/serleena/model/ITelemetry.java
/////////////////////////////////////////////////////////////////////////////// // // This file is part of Serleena. // // The MIT License (MIT) // // Copyright (C) 2015 Antonio Cavestro, Gabriele Pozzan, Matteo Lisotto, // Nicola Mometto, Filippo Sestini, Tobia Tesan, Sebastiano Valle. // // 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. // /////////////////////////////////////////////////////////////////////////////// /** * Name: ITelemetry * Package: com.hitchikers.serleena.model * Author: Tobia Tesan <[email protected]> * Date: 2015-05-05 * * History: * Version Programmer Date Changes * 1.0 Tobia Tesan 2015-05-05 Creazione del file */ package com.kyloth.serleena.model; import com.kyloth.serleena.common.TelemetryEvent; import com.kyloth.serleena.common.TelemetryEventType; /** * Interfaccia realizzata da oggetti che rappresentano un * Tracciamento * * @author Tobia Tesan <[email protected]> * @version 1.0 * @since 1.0 */ public interface ITelemetry { /** * Restituisce gli eventi che costituiscono il Tracciamento. * * @return Un Iterable che contiene tutti gli eventi del Tracciamento. * @version 1.0 */ public Iterable<TelemetryEvent> getEvents(); /** * Restituisce gli eventi che costituiscono il Tracciamento, filtrati * secondo un intervallo di tempo specificato. * * @return Insieme enumerabile che contiene tutti gli eventi del * Tracciamento compresi nell'intervallo di secondi specificato. * @param from L'inizio dell'intervallo, comprensivo degli * eventi da restituire, espresso in secondi dall'avvio del * Tracciamento. * Se from > to, viene sollevata un'eccezione * IllegalArgumentException. * @param to L'inizio dell'intervallo, comprensivo degli * eventi da restituire, espresso in secondi dall'avvio del * Tracciamento. * Se from > to, viene sollevata un'eccezione * IllegalArgumentException. * @version 1.0 */ public Iterable<TelemetryEvent> getEvents(int from, int to) throws IllegalArgumentException; /** * Restituisce gli eventi che costituiscono il Tracciamento, filtrati in * base a uno specifico tipo di evento. * * @return Insieme enumerabile che contiene tutti e soli gli eventi del * Tracciamento di tipo specificato. * @param type Tipo di eventi da restituire. * @return Insieme enumerabile di eventi di Tracciamento. */ public Iterable<TelemetryEvent> getEvents(TelemetryEventType type) throws NoSuchTelemetryEventException; /** * Restituisce la durata totale del Tracciamento. * * @return Durata temporale in secondi del Tracciamento. * @version 1.0 */ public int getDuration(); }
MODEL: Aggiungi ITelemetry.getEventAtLocation() Related to SHANDROID-24
serleena/app/src/main/java/com/kyloth/serleena/model/ITelemetry.java
MODEL: Aggiungi ITelemetry.getEventAtLocation()
Java
mit
a7b00b3e64cbeb345ae061089a19ba5f793d3cc8
0
FlightOfStairs/ADirStat
package org.flightofstairs.adirstat.model; import android.os.AsyncTask; import android.util.Log; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Optional; import com.google.common.base.Stopwatch; import com.google.common.collect.ImmutableSortedSet; import com.google.inject.Inject; import com.squareup.otto.Bus; import lombok.SneakyThrows; import org.flightofstairs.adirstat.Tree; import java.io.File; import java.util.SortedSet; import static com.google.common.base.Verify.verifyNotNull; import static com.google.common.collect.ImmutableList.copyOf; import static com.google.common.collect.Iterables.transform; import static java.util.Locale.UK; import static java.util.concurrent.TimeUnit.SECONDS; public class Scanner extends AsyncTask<File, Void, Optional<Tree<FilesystemSummary>>> { private static final int MIN_FILE_BYTES = 1; private final Bus bus; @Inject public Scanner(Bus bus) { this.bus = bus; } @Override @SneakyThrows protected Optional<Tree<FilesystemSummary>> doInBackground(File... params) { File root = verifyNotNull(params[0]); Stopwatch stopwatch = Stopwatch.createStarted(); Optional<Tree<FilesystemSummary>> node = recursiveList(root.getCanonicalFile()); String logMessage = node.isPresent() ? String.format(UK, "Found %d files (%dmb) in %ds.", node.get().getValue().getSubTreeCount(), node.get().getValue().getSubTreeBytes() / (int) Math.pow(1024, 2), stopwatch.elapsed(SECONDS)) : "Failed to list files."; Log.d(getClass().getSimpleName(), logMessage); return node; } @Override public void onPostExecute(Optional<Tree<FilesystemSummary>> result) { bus.post(result); } @Override public void onCancelled() { bus.post(Optional.<Tree<FilesystemSummary>>absent()); } @VisibleForTesting static Optional<Tree<FilesystemSummary>> recursiveList(File path) { if (path.isDirectory()) { long subTreeBytes = 0; long subTreeCount = 0; Iterable<Optional<Tree<FilesystemSummary>>> possibleChildren = transform(copyOf(path.listFiles()), Scanner::recursiveList); SortedSet<Tree<FilesystemSummary>> children = ImmutableSortedSet.copyOf(Optional.presentInstances(possibleChildren)); for (Tree<FilesystemSummary> child : children) { subTreeBytes += child.getValue().getSubTreeBytes(); subTreeCount += child.getValue().getSubTreeCount(); } return Optional.of(new Tree<>(new FilesystemSummary(path, subTreeBytes, subTreeCount), children)); } else if (path.isFile()) { return Optional.of(new Tree<>(new FilesystemSummary(path, Math.max(path.length(), MIN_FILE_BYTES), 1), ImmutableSortedSet.<Tree<FilesystemSummary>>of())); } return Optional.absent(); } }
adirstat/src/main/java/org/flightofstairs/adirstat/model/Scanner.java
package org.flightofstairs.adirstat.model; import android.os.AsyncTask; import android.util.Log; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Optional; import com.google.common.base.Stopwatch; import com.google.common.collect.ImmutableSortedSet; import com.google.inject.Inject; import com.squareup.otto.Bus; import lombok.SneakyThrows; import org.flightofstairs.adirstat.Tree; import java.io.File; import java.util.SortedSet; import static com.google.common.base.Verify.verifyNotNull; import static com.google.common.collect.ImmutableList.copyOf; import static com.google.common.collect.Iterables.transform; import static java.util.Locale.UK; import static java.util.concurrent.TimeUnit.SECONDS; public class Scanner extends AsyncTask<File, Void, Optional<Tree<FilesystemSummary>>> { private final Bus bus; @Inject public Scanner(Bus bus) { this.bus = bus; } @Override @SneakyThrows protected Optional<Tree<FilesystemSummary>> doInBackground(File... params) { File root = verifyNotNull(params[0]); Stopwatch stopwatch = Stopwatch.createStarted(); Optional<Tree<FilesystemSummary>> node = recursiveList(root.getCanonicalFile()); String logMessage = node.isPresent() ? String.format(UK, "Found %d files (%dmb) in %ds.", node.get().getValue().getSubTreeCount(), node.get().getValue().getSubTreeBytes() / (int) Math.pow(1024, 2), stopwatch.elapsed(SECONDS)) : "Failed to list files."; Log.d(getClass().getSimpleName(), logMessage); return node; } @Override public void onPostExecute(Optional<Tree<FilesystemSummary>> result) { bus.post(result); } @Override public void onCancelled() { bus.post(Optional.<Tree<FilesystemSummary>>absent()); } @VisibleForTesting static Optional<Tree<FilesystemSummary>> recursiveList(File path) { if (path.isDirectory()) { long subTreeBytes = 0; long subTreeCount = 0; Iterable<Optional<Tree<FilesystemSummary>>> possibleChildren = transform(copyOf(path.listFiles()), Scanner::recursiveList); SortedSet<Tree<FilesystemSummary>> children = ImmutableSortedSet.copyOf(Optional.presentInstances(possibleChildren)); for (Tree<FilesystemSummary> child : children) { subTreeBytes += child.getValue().getSubTreeBytes(); subTreeCount += child.getValue().getSubTreeCount(); } return Optional.of(new Tree<>(new FilesystemSummary(path, subTreeBytes, subTreeCount), children)); } else if (path.isFile()) { return Optional.of(new Tree<>(new FilesystemSummary(path, path.length(), 1), ImmutableSortedSet.<Tree<FilesystemSummary>>of())); } return Optional.absent(); } }
HACK LOL. Making min recorded size of a file 1 byte. Avoids lots of division errors.
adirstat/src/main/java/org/flightofstairs/adirstat/model/Scanner.java
HACK LOL. Making min recorded size of a file 1 byte. Avoids lots of division errors.
Java
mit
16a4c4a29180c738b9e66fdd66681f22b6066e4e
0
jedrz/slisp,jedrz/slisp
public class FnForm implements SpecialForm { @Override public LispObject call(List<LispObject> args, Interpreter.Evaluator evaluator) { // Obsługa parametrów. List<Sym> argList = new LinkedList<>(); Vec argVec = (Vec) args.get(0); for (LispObject arg : argVec) { argList.add((Sym) arg); } // Ciało funkcji. List<LispObject> body = args.subList(1, args.size()); return new Function(argList, body, evaluator.getScope()); } }
doc/impl/FnForm.java
public class FnForm implements SpecialForm { @Override public LispObject call(List<LispObject> args, Interpreter.Evaluator evaluator) { // Obsługa parametrów. List<Sym> argList = new LinkedList<>(); if (args.get(0) instanceof Vec) { Vec argVec = (Vec) args.get(0); for (LispObject arg : argVec) { if (arg instanceof Sym) { argList.add((Sym) arg); } else { // Nazwy argumentów powinny być symbolami. } } } else { // Pierwszym argumentem powinien być wektor. } List<LispObject> body = args.subList(1, args.size()); // Ciało funkcji. return new Function(argList, body, evaluator.getScope()); } }
doc: simplify fn form
doc/impl/FnForm.java
doc: simplify fn form
Java
mit
d3447ed46a4ece467a6ba0ad58a00851b9dd23ba
0
adessoAG/JenkinsHue
package de.adesso.jenkinshue.service; import java.awt.Color; 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.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.joda.time.DateTime; import org.json.hue.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.TestRestTemplate; import org.springframework.context.annotation.Primary; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import com.philips.lighting.hue.listener.PHHTTPListener; import com.philips.lighting.hue.sdk.PHAccessPoint; import com.philips.lighting.hue.sdk.PHHueSDK; import com.philips.lighting.hue.sdk.PHMessageType; import com.philips.lighting.hue.sdk.PHSDKListener; import com.philips.lighting.hue.sdk.utilities.PHUtilities; import com.philips.lighting.model.PHBridge; import com.philips.lighting.model.PHBridgeResourcesCache; import com.philips.lighting.model.PHHueError; import com.philips.lighting.model.PHHueParsingError; import com.philips.lighting.model.PHLight; import com.philips.lighting.model.PHLight.PHLightAlertMode; import com.philips.lighting.model.PHLightState; import de.adesso.jenkinshue.Scheduler; import de.adesso.jenkinshue.common.dto.bridge.BridgeDTO; import de.adesso.jenkinshue.common.dto.lamp.LampHueDTO; import de.adesso.jenkinshue.common.dto.lamp.LampNameDTO; import de.adesso.jenkinshue.common.dto.lamp.LampTestDTO; import de.adesso.jenkinshue.common.dto.lamp.LampTurnOffDTO; import de.adesso.jenkinshue.common.dto.lamp.LampWithHueUniqueId; import de.adesso.jenkinshue.common.dto.scenario_config.ScenarioConfigDTO; import de.adesso.jenkinshue.common.hue.dto.FoundBridgeDTO; import de.adesso.jenkinshue.common.service.HueService; import de.adesso.jenkinshue.constant.HueConstants; import de.adesso.jenkinshue.entity.Bridge; import de.adesso.jenkinshue.repository.BridgeRepository; import lombok.extern.log4j.Log4j2; /** * * @author wennier * */ @Log4j2 @Primary @Service public class HueServiceImpl implements HueService { private static final String PRESS_PUSH_LINK_BUTTON = "Push-Link-Taste drücken"; private static final String CONNECTED = "Verbunden"; private static final String CONNECTION_LOST = "Verbindung verloren"; private static final String LAST_CONTACT = "letzter Kontakt"; private static final String REPLACE_PORT_REGEX = ":.*"; @Autowired private BridgeRepository bridgeRepository; private PHHueSDK phHueSDK; private PHSDKListener listener; private Map<String, String> bridgeStates = Collections.synchronizedMap(new HashMap<>()); private List<PHBridge> bridges = Collections.synchronizedList(new ArrayList<PHBridge>()); @PostConstruct public void init() { this.phHueSDK = PHHueSDK.getInstance(); phHueSDK.setAppName("JenkinsHue"); phHueSDK.setDeviceName("Server"); initListener(); phHueSDK.getNotificationManager().registerSDKListener(listener); } @PreDestroy public void destroy() { for (PHBridge bridge : bridges) { phHueSDK.disableHeartbeat(bridge); phHueSDK.disconnect(bridge); updateState(bridge, CONNECTION_LOST); } } private void updateState(PHBridge bridge, String state) { log.debug("updateState(" + removePortAndToLowerCase(bridge.getResourceCache().getBridgeConfiguration().getIpAddress()) + ", " + state + ") [bridge]"); bridgeStates.put(removePortAndToLowerCase(bridge.getResourceCache().getBridgeConfiguration().getIpAddress()), state); } private void updateState(String ip, String state) { log.debug("updateState(" + removePortAndToLowerCase(ip) + ", " + state + ") [ip]"); bridgeStates.put(removePortAndToLowerCase(ip), state); } public void initListener() { listener = new PHSDKListener() { @Override public void onAccessPointsFound(List<PHAccessPoint> accessPoint) { log.debug("onAccessPointsFound Es wird nie nach Bridges gesucht -> nicht benötigt"); } @Override public void onAuthenticationRequired(PHAccessPoint accessPoint) { phHueSDK.startPushlinkAuthentication(accessPoint); log.debug("onAuthenticationRequired(" + accessPoint.getIpAddress() + ")"); // IP ohne Port updateState(accessPoint.getIpAddress(), PRESS_PUSH_LINK_BUTTON); } @Override public void onBridgeConnected(PHBridge bridge, String username) { String bridgeIpWithoutPort = removePortAndToLowerCase(bridge.getResourceCache().getBridgeConfiguration().getIpAddress()); log.debug("onBridgeConnected(" + bridgeIpWithoutPort + ", " + username + ")"); bridges.add(bridge); updateState(bridge, CONNECTED); Bridge b = bridgeRepository.findByIp(bridgeIpWithoutPort); b.setHueUserName(username); b = bridgeRepository.save(b); phHueSDK.enableHeartbeat(bridge, PHHueSDK.HB_INTERVAL); // 10000 Millis } @Override public void onCacheUpdated(List cacheNotificationsList, PHBridge bridge) { if (cacheNotificationsList.contains(PHMessageType.LIGHTS_CACHE_UPDATED)) { log.debug("Lights Cache Updated"); } } @Override public void onConnectionLost(PHAccessPoint accessPoint) { updateState(accessPoint.getIpAddress(), CONNECTION_LOST + " (" + DateTime.now().toString("HH:mm") + " Uhr)"); } @Override public void onConnectionResumed(PHBridge bridge) { updateState(bridge, CONNECTED + " (" + LAST_CONTACT + ": " + DateTime.now().toString("HH:mm") + " Uhr)"); } @Override public void onError(int code, final String message) { log.debug(message + " " + code); if (code == PHHueError.BRIDGE_NOT_RESPONDING) { log.debug("BRIDGE_NOT_RESPONDING"); } else if (code == PHMessageType.PUSHLINK_BUTTON_NOT_PRESSED) { log.debug("PUSHLINK_BUTTON_NOT_PRESSED"); } else if (code == PHHueError.AUTHENTICATION_FAILED || code == PHMessageType.PUSHLINK_AUTHENTICATION_FAILED) { log.debug("AUTHENTICATION_FAILED"); for(Map.Entry<String, String> entry : bridgeStates.entrySet()) { if(entry.getValue().equals(PRESS_PUSH_LINK_BUTTON)) { bridgeStates.put(entry.getKey(), "Push-Link-Button nicht gedrückt. Bridge entfernen und neu hinzufügen!"); } } } else if (code == PHMessageType.BRIDGE_NOT_FOUND) { log.debug("BRIDGE_NOT_FOUND"); } } @Override public void onParsingErrors(List<PHHueParsingError> parsingErrorsList) { for (PHHueParsingError parsingError : parsingErrorsList) { log.debug("ParsingError : " + parsingError.getMessage()); } } }; } @Override public void connectToBridgeIfNotAlreadyConnected(BridgeDTO bridge) { for (PHBridge b : bridges) { if (ipAreEqual(b.getResourceCache().getBridgeConfiguration().getIpAddress(), bridge.getIp())) { return; } } PHAccessPoint accessPoint = new PHAccessPoint(); accessPoint.setIpAddress(bridge.getIp()); if (bridge.getHueUserName() != null && !bridge.getHueUserName().isEmpty()) { accessPoint.setUsername(bridge.getHueUserName()); } phHueSDK.connect(accessPoint); } @Override public void disconnectFromBridge(BridgeDTO bridge) { for(int i = 0; i < bridges.size(); i++) { PHBridge b = bridges.get(i); if(ipAreEqual(bridge.getIp(), b.getResourceCache().getBridgeConfiguration().getIpAddress())) { bridgeStates.remove(removePortAndToLowerCase(b.getResourceCache().getBridgeConfiguration().getIpAddress())); phHueSDK.disableHeartbeat(b); phHueSDK.disconnect(b); bridges.remove(i); break; } } } @Override public void showRandomColorsOnAllLamps() { for (PHBridge bridge : bridges) { PHBridgeResourcesCache resourceCache = bridge.getResourceCache(); List<PHLight> allLights = resourceCache.getAllLights(); Random rand = new Random(); for (PHLight light : allLights) { PHLightState lightState = new PHLightState(); lightState.setBrightness(HueConstants.MAX_BRI); lightState.setSaturation(HueConstants.MAX_SAT); lightState.setHue(rand.nextInt(HueConstants.MAX_HUE + 1)); bridge.updateLightState(light, lightState); } } } @Async @Override public void updateLamp(LampWithHueUniqueId lamp, ScenarioConfigDTO config) { if(config != null) { for (PHBridge bridge : bridges) { PHBridgeResourcesCache resourceCache = bridge.getResourceCache(); List<PHLight> allLights = resourceCache.getAllLights(); String url = "http://" + bridge.getResourceCache().getBridgeConfiguration().getIpAddress() + "/api/" + bridge.getResourceCache().getBridgeConfiguration().getUsername() + "/lights"; bridge.doHTTPGet(url, new PHHTTPListener() { @Override public void onHTTPResponse(String jsonResponse) { JSONObject object = new JSONObject(jsonResponse); for (PHLight light : allLights) { light.setUniqueId(object.optJSONObject(light.getIdentifier()).optString("uniqueid")); if (light.getUniqueId().equals(lamp.getHueUniqueId())) { updateLamp(bridge, light, config); } } } }); } } } private void updateLamp(PHBridge bridge, PHLight light, ScenarioConfigDTO config) { PHLightState oldLightState = light.getLastKnownLightState(); float oldX = oldLightState.getX(); float oldY = oldLightState.getY(); log.debug("---- old light state: -------"); log.debug("x: " + oldLightState.getX()); log.debug("y: " + oldLightState.getY()); log.debug("on: " + oldLightState.isOn()); log.debug("brightness: " + oldLightState.getBrightness()); log.debug("-----------------------------"); PHLightState lightState = new PHLightState(); lightState.setOn(config.isLampOn()); if(config.isLampOn()) { if (config.isOnetimePulsationEnabled()) { if (config.isOnetimePulsationColorChangeEnabled()) { updateLightStateColor(lightState, light.getModelNumber(), config.getOnetimePulsationColorHex()); } else if(config.isColorChangeEnabled()) { updateLightStateColor(lightState, light.getModelNumber(), config.getColorHex()); } lightState.setAlertMode(PHLightAlertMode.ALERT_SELECT); for(int i = 0; i < 3; i++) { bridge.updateLightState(light, lightState); try { Thread.sleep(1333); } catch (InterruptedException e) { log.error(e); } } } lightState = new PHLightState(); lightState.setOn(config.isLampOn()); if(config.isColorChangeEnabled()) { updateLightStateColor(lightState, light.getModelNumber(), config.getColorHex()); } else { lightState.setX(oldX); lightState.setY(oldY); } if (config.isBrightnessChangeEnabled()) { lightState.setBrightness(config.getBrightness()); } } bridge.updateLightState(light, lightState); log.debug("---- new light state: -------"); log.debug("x: " + lightState.getX()); log.debug("y: " + lightState.getY()); log.debug("on: " + lightState.isOn()); log.debug("brightness: " + lightState.getBrightness()); log.debug("-----------------------------"); } @Override public List<LampHueDTO> findAllLamps() { List<LampHueDTO> lamps = new ArrayList<>(); final CountDownLatch latch; if(bridges.size() > 0) { latch = new CountDownLatch(bridges.size()); } else { latch = null; } for (PHBridge bridge : bridges) { PHBridgeResourcesCache resourceCache = bridge.getResourceCache(); List<PHLight> allLights = resourceCache.getAllLights(); String url = "http://" + bridge.getResourceCache().getBridgeConfiguration().getIpAddress() + "/api/" + bridge.getResourceCache().getBridgeConfiguration().getUsername() + "/lights"; bridge.doHTTPGet(url, new PHHTTPListener() { @Override public void onHTTPResponse(String jsonResponse) { JSONObject object = new JSONObject(jsonResponse); for (PHLight light : allLights) { boolean lampOn = light.getLastKnownLightState().isOn(); lamps.add(new LampHueDTO(object.optJSONObject(light.getIdentifier()).optString("uniqueid"), light.getName(), light.getLightType().toString(), light.getManufacturerName(), lampOn)); } latch.countDown(); } }); } if(latch != null) { try { latch.await(Scheduler.LATCH_TIMEOUT, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { e.printStackTrace(); } } return lamps; } @Override public List<FoundBridgeDTO> findAllBridges() { return new ArrayList<>(Arrays.asList(new TestRestTemplate().getForObject("https://www.meethue.com/api/nupnp", FoundBridgeDTO[].class))); } private void updateLightStateColor(PHLightState lightState, String lightModelNumber, String colorHex) { Color color = Color.decode(colorHex); // AWT ist auch OK float[] xy = PHUtilities.calculateXYFromRGB(color.getRed(), color.getGreen(), color.getBlue(), lightModelNumber); lightState.setX(xy[0]); lightState.setY(xy[1]); } @Override public void testScenario(LampTestDTO lamp) { if(lamp.getLamps() != null) { for(LampNameDTO l : lamp.getLamps()) { updateLamp(l, lamp.getScenarioConfig()); } } } // TODO TESTEN @Override public void pulseOnce(String hueUniqueId) { updateLamp(new LampWithHueUniqueId() { @Override public String getHueUniqueId() { return hueUniqueId; } }, new ScenarioConfigDTO(-1, null, true, true, true, "#FFF", false, null, false, 0)); } @Override public void turnOff(LampTurnOffDTO lamp) { if(lamp.getLamps() != null) { for(LampNameDTO l : lamp.getLamps()) { updateLamp(l, new ScenarioConfigDTO(-1, null, false, false, false, null, false, null, false, 0)); } } } @Override public void updateBridgeState(List<BridgeDTO> bridgeDTOs) { for(BridgeDTO dto : bridgeDTOs) { String state = bridgeStates.get(removePortAndToLowerCase(dto.getIp())); if(state != null) { dto.setState(state); } } } @Override public boolean ipAreEqual(String ip1, String ip2) { if(removePortAndToLowerCase(ip1).equals(removePortAndToLowerCase(ip2))) { return true; } else { return false; } } public String removePortAndToLowerCase(String ip) { return ip.replaceAll(REPLACE_PORT_REGEX, "").toLowerCase(); } }
main/src/main/java/de/adesso/jenkinshue/service/HueServiceImpl.java
package de.adesso.jenkinshue.service; import java.awt.Color; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.joda.time.DateTime; import org.json.hue.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.TestRestTemplate; import org.springframework.context.annotation.Primary; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import com.philips.lighting.hue.listener.PHHTTPListener; import com.philips.lighting.hue.sdk.PHAccessPoint; import com.philips.lighting.hue.sdk.PHHueSDK; import com.philips.lighting.hue.sdk.PHMessageType; import com.philips.lighting.hue.sdk.PHSDKListener; import com.philips.lighting.hue.sdk.utilities.PHUtilities; import com.philips.lighting.model.PHBridge; import com.philips.lighting.model.PHBridgeResourcesCache; import com.philips.lighting.model.PHHueError; import com.philips.lighting.model.PHHueParsingError; import com.philips.lighting.model.PHLight; import com.philips.lighting.model.PHLight.PHLightAlertMode; import com.philips.lighting.model.PHLightState; import de.adesso.jenkinshue.Scheduler; import de.adesso.jenkinshue.common.dto.bridge.BridgeDTO; import de.adesso.jenkinshue.common.dto.lamp.LampHueDTO; import de.adesso.jenkinshue.common.dto.lamp.LampNameDTO; import de.adesso.jenkinshue.common.dto.lamp.LampTestDTO; import de.adesso.jenkinshue.common.dto.lamp.LampTurnOffDTO; import de.adesso.jenkinshue.common.dto.lamp.LampWithHueUniqueId; import de.adesso.jenkinshue.common.dto.scenario_config.ScenarioConfigDTO; import de.adesso.jenkinshue.common.hue.dto.FoundBridgeDTO; import de.adesso.jenkinshue.common.service.HueService; import de.adesso.jenkinshue.constant.HueConstants; import de.adesso.jenkinshue.entity.Bridge; import de.adesso.jenkinshue.repository.BridgeRepository; import lombok.extern.log4j.Log4j2; /** * * @author wennier * */ @Log4j2 @Primary @Service public class HueServiceImpl implements HueService { private static final String PRESS_PUSH_LINK_BUTTON = "Push-Link-Taste drücken"; private static final String CONNECTED = "Verbunden"; private static final String CONNECTION_LOST = "Verbindung verloren"; private static final String LAST_CONTACT = "letzter Kontakt"; private static final String REPLACE_PORT_REGEX = ":.*"; @Autowired private BridgeRepository bridgeRepository; private PHHueSDK phHueSDK; private PHSDKListener listener; private Map<String, String> bridgeStates = Collections.synchronizedMap(new HashMap<>()); private List<PHBridge> bridges = Collections.synchronizedList(new ArrayList<PHBridge>()); @PostConstruct public void init() { this.phHueSDK = PHHueSDK.getInstance(); phHueSDK.setAppName("JenkinsHue"); phHueSDK.setDeviceName("Server"); initListener(); phHueSDK.getNotificationManager().registerSDKListener(listener); } @PreDestroy public void destroy() { for (PHBridge bridge : bridges) { phHueSDK.disableHeartbeat(bridge); phHueSDK.disconnect(bridge); updateState(bridge, CONNECTION_LOST); } } private void updateState(PHBridge bridge, String state) { log.debug("updateState(" + removePortAndToLowerCase(bridge.getResourceCache().getBridgeConfiguration().getIpAddress()) + ", " + state + ") [bridge]"); bridgeStates.put(removePortAndToLowerCase(bridge.getResourceCache().getBridgeConfiguration().getIpAddress()), state); } private void updateState(String ip, String state) { log.debug("updateState(" + removePortAndToLowerCase(ip) + ", " + state + ") [ip]"); bridgeStates.put(removePortAndToLowerCase(ip), state); } public void initListener() { listener = new PHSDKListener() { @Override public void onAccessPointsFound(List<PHAccessPoint> accessPoint) { log.debug("onAccessPointsFound Es wird nie nach Bridges gesucht -> nicht benötigt"); } @Override public void onAuthenticationRequired(PHAccessPoint accessPoint) { phHueSDK.startPushlinkAuthentication(accessPoint); log.debug("onAuthenticationRequired(" + accessPoint.getIpAddress() + ")"); // IP ohne Port updateState(accessPoint.getIpAddress(), PRESS_PUSH_LINK_BUTTON); } @Override public void onBridgeConnected(PHBridge bridge, String username) { String bridgeIpWithoutPort = removePortAndToLowerCase(bridge.getResourceCache().getBridgeConfiguration().getIpAddress()); log.debug("onBridgeConnected(" + bridgeIpWithoutPort + ", " + username + ")"); bridges.add(bridge); updateState(bridge, CONNECTED); Bridge b = bridgeRepository.findByIp(bridgeIpWithoutPort); b.setHueUserName(username); b = bridgeRepository.save(b); phHueSDK.enableHeartbeat(bridge, PHHueSDK.HB_INTERVAL); // 10000 Millis } @Override public void onCacheUpdated(List cacheNotificationsList, PHBridge bridge) { if (cacheNotificationsList.contains(PHMessageType.LIGHTS_CACHE_UPDATED)) { log.debug("Lights Cache Updated"); } } @Override public void onConnectionLost(PHAccessPoint accessPoint) { updateState(accessPoint.getIpAddress(), CONNECTION_LOST + " (" + DateTime.now().toString("HH:mm") + " Uhr)"); } @Override public void onConnectionResumed(PHBridge bridge) { updateState(bridge, CONNECTED + " (" + LAST_CONTACT + ": " + DateTime.now().toString("HH:mm") + " Uhr)"); } @Override public void onError(int code, final String message) { log.debug(message + " " + code); if (code == PHHueError.BRIDGE_NOT_RESPONDING) { log.debug("BRIDGE_NOT_RESPONDING"); } else if (code == PHMessageType.PUSHLINK_BUTTON_NOT_PRESSED) { log.debug("PUSHLINK_BUTTON_NOT_PRESSED"); } else if (code == PHHueError.AUTHENTICATION_FAILED || code == PHMessageType.PUSHLINK_AUTHENTICATION_FAILED) { log.debug("AUTHENTICATION_FAILED"); for(Map.Entry<String, String> entry : bridgeStates.entrySet()) { if(entry.getValue().equals(PRESS_PUSH_LINK_BUTTON)) { bridgeStates.put(entry.getKey(), "Push-Link-Button nicht gedrückt. Bridge entfernen und neu hinzufügen!"); } } } else if (code == PHMessageType.BRIDGE_NOT_FOUND) { log.debug("BRIDGE_NOT_FOUND"); } } @Override public void onParsingErrors(List<PHHueParsingError> parsingErrorsList) { for (PHHueParsingError parsingError : parsingErrorsList) { log.debug("ParsingError : " + parsingError.getMessage()); } } }; } @Override public void connectToBridgeIfNotAlreadyConnected(BridgeDTO bridge) { for (PHBridge b : bridges) { if (ipAreEqual(b.getResourceCache().getBridgeConfiguration().getIpAddress(), bridge.getIp())) { return; } } PHAccessPoint accessPoint = new PHAccessPoint(); accessPoint.setIpAddress(bridge.getIp()); if (bridge.getHueUserName() != null && !bridge.getHueUserName().isEmpty()) { accessPoint.setUsername(bridge.getHueUserName()); } phHueSDK.connect(accessPoint); } @Override public void disconnectFromBridge(BridgeDTO bridge) { for(int i = 0; i < bridges.size(); i++) { PHBridge b = bridges.get(i); if(ipAreEqual(bridge.getIp(), b.getResourceCache().getBridgeConfiguration().getIpAddress())) { bridgeStates.remove(removePortAndToLowerCase(b.getResourceCache().getBridgeConfiguration().getIpAddress())); phHueSDK.disableHeartbeat(b); phHueSDK.disconnect(b); bridges.remove(i); break; } } } @Override public void showRandomColorsOnAllLamps() { for (PHBridge bridge : bridges) { PHBridgeResourcesCache resourceCache = bridge.getResourceCache(); List<PHLight> allLights = resourceCache.getAllLights(); Random rand = new Random(); for (PHLight light : allLights) { PHLightState lightState = new PHLightState(); lightState.setBrightness(HueConstants.MAX_BRI); lightState.setSaturation(HueConstants.MAX_SAT); lightState.setHue(rand.nextInt(HueConstants.MAX_HUE + 1)); bridge.updateLightState(light, lightState); } } } @Async @Override public void updateLamp(LampWithHueUniqueId lamp, ScenarioConfigDTO config) { if(config != null) { for (PHBridge bridge : bridges) { PHBridgeResourcesCache resourceCache = bridge.getResourceCache(); List<PHLight> allLights = resourceCache.getAllLights(); String url = "http://" + bridge.getResourceCache().getBridgeConfiguration().getIpAddress() + "/api/" + bridge.getResourceCache().getBridgeConfiguration().getUsername() + "/lights"; bridge.doHTTPGet(url, new PHHTTPListener() { @Override public void onHTTPResponse(String jsonResponse) { JSONObject object = new JSONObject(jsonResponse); for (PHLight light : allLights) { light.setUniqueId(object.optJSONObject(light.getIdentifier()).optString("uniqueid")); if (light.getUniqueId().equals(lamp.getHueUniqueId())) { updateLamp(bridge, light, config); } } } }); } } } private void updateLamp(PHBridge bridge, PHLight light, ScenarioConfigDTO config) { PHLightState oldLightState = light.getLastKnownLightState(); float oldX = oldLightState.getX(); float oldY = oldLightState.getY(); log.debug("---- old light state: -------"); log.debug("x: " + oldLightState.getX()); log.debug("y: " + oldLightState.getY()); log.debug("on: " + oldLightState.isOn()); log.debug("brightness: " + oldLightState.getBrightness()); log.debug("-----------------------------"); PHLightState lightState = new PHLightState(); lightState.setOn(config.isLampOn()); if(config.isLampOn()) { if (config.isOnetimePulsationEnabled()) { if (config.isOnetimePulsationColorChangeEnabled()) { updateLightStateColor(lightState, light.getModelNumber(), config.getOnetimePulsationColorHex()); } else if(config.isColorChangeEnabled()) { updateLightStateColor(lightState, light.getModelNumber(), config.getColorHex()); } lightState.setAlertMode(PHLightAlertMode.ALERT_SELECT); for(int i = 0; i < 3; i++) { bridge.updateLightState(light, lightState); try { Thread.sleep(1333); } catch (InterruptedException e) { log.error(e); } } } lightState = new PHLightState(); lightState.setOn(config.isLampOn()); if(config.isColorChangeEnabled()) { updateLightStateColor(lightState, light.getModelNumber(), config.getColorHex()); } else { lightState.setX(oldX); lightState.setY(oldY); } if (config.isBrightnessChangeEnabled()) { lightState.setBrightness(config.getBrightness()); } } bridge.updateLightState(light, lightState); log.debug("---- new light state: -------"); log.debug("x: " + lightState.getX()); log.debug("y: " + lightState.getY()); log.debug("on: " + lightState.isOn()); log.debug("brightness: " + lightState.getBrightness()); log.debug("-----------------------------"); } @Override public List<LampHueDTO> findAllLamps() { List<LampHueDTO> lamps = new ArrayList<>(); final CountDownLatch latch; if(bridges.size() > 0) { latch = new CountDownLatch(bridges.size()); } else { latch = null; } for (PHBridge bridge : bridges) { PHBridgeResourcesCache resourceCache = bridge.getResourceCache(); List<PHLight> allLights = resourceCache.getAllLights(); String url = "http://" + bridge.getResourceCache().getBridgeConfiguration().getIpAddress() + "/api/" + bridge.getResourceCache().getBridgeConfiguration().getUsername() + "/lights"; bridge.doHTTPGet(url, new PHHTTPListener() { @Override public void onHTTPResponse(String jsonResponse) { JSONObject object = new JSONObject(jsonResponse); for (PHLight light : allLights) { boolean lampOn = light.getLastKnownLightState().isOn(); lamps.add(new LampHueDTO(object.optJSONObject(light.getIdentifier()).optString("uniqueid"), light.getName(), light.getLightType().toString(), light.getManufacturerName(), lampOn)); } latch.countDown(); } }); } if(latch != null) { try { latch.await(Scheduler.LATCH_TIMEOUT, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { e.printStackTrace(); } } return lamps; } @Override public List<FoundBridgeDTO> findAllBridges() { return new ArrayList<>(new TestRestTemplate().getForObject("https://www.meethue.com/api/nupnp", FoundBridgeDTO[].class)); } private void updateLightStateColor(PHLightState lightState, String lightModelNumber, String colorHex) { Color color = Color.decode(colorHex); // AWT ist auch OK float[] xy = PHUtilities.calculateXYFromRGB(color.getRed(), color.getGreen(), color.getBlue(), lightModelNumber); lightState.setX(xy[0]); lightState.setY(xy[1]); } @Override public void testScenario(LampTestDTO lamp) { if(lamp.getLamps() != null) { for(LampNameDTO l : lamp.getLamps()) { updateLamp(l, lamp.getScenarioConfig()); } } } // TODO TESTEN @Override public void pulseOnce(String hueUniqueId) { updateLamp(new LampWithHueUniqueId() { @Override public String getHueUniqueId() { return hueUniqueId; } }, new ScenarioConfigDTO(-1, null, true, true, true, "#FFF", false, null, false, 0)); } @Override public void turnOff(LampTurnOffDTO lamp) { if(lamp.getLamps() != null) { for(LampNameDTO l : lamp.getLamps()) { updateLamp(l, new ScenarioConfigDTO(-1, null, false, false, false, null, false, null, false, 0)); } } } @Override public void updateBridgeState(List<BridgeDTO> bridgeDTOs) { for(BridgeDTO dto : bridgeDTOs) { String state = bridgeStates.get(removePortAndToLowerCase(dto.getIp())); if(state != null) { dto.setState(state); } } } @Override public boolean ipAreEqual(String ip1, String ip2) { if(removePortAndToLowerCase(ip1).equals(removePortAndToLowerCase(ip2))) { return true; } else { return false; } } public String removePortAndToLowerCase(String ip) { return ip.replaceAll(REPLACE_PORT_REGEX, "").toLowerCase(); } }
fix returning immutable list error
main/src/main/java/de/adesso/jenkinshue/service/HueServiceImpl.java
fix returning immutable list error
Java
epl-1.0
95cb3f5d54f82b90f7328d05674b55ba82d9dfae
0
forge/core,ivannov/core,agoncal/core,pplatek/core,pplatek/core,ivannov/core,D9110/core,agoncal/core,forge/core,agoncal/core,agoncal/core,D9110/core,pplatek/core,D9110/core,jerr/jbossforge-core,D9110/core,forge/core,D9110/core,pplatek/core,forge/core,ivannov/core,agoncal/core,jerr/jbossforge-core,agoncal/core,agoncal/core,forge/core,forge/core,jerr/jbossforge-core,ivannov/core,pplatek/core,D9110/core,pplatek/core,forge/core,jerr/jbossforge-core,ivannov/core,forge/core,ivannov/core,ivannov/core,jerr/jbossforge-core,agoncal/core,jerr/jbossforge-core,jerr/jbossforge-core,jerr/jbossforge-core,D9110/core,jerr/jbossforge-core,agoncal/core,ivannov/core,D9110/core,D9110/core,forge/core,ivannov/core,ivannov/core,pplatek/core,pplatek/core,jerr/jbossforge-core,pplatek/core,forge/core,D9110/core,agoncal/core,pplatek/core
/* * Copyright 2013 Red Hat, Inc. and/or its affiliates. * * Licensed under the Eclipse Public License version 1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ package org.jboss.forge.addon.ui.impl.facets; import java.util.concurrent.Callable; import org.jboss.forge.addon.environment.Environment; import org.jboss.forge.addon.facets.AbstractFacet; import org.jboss.forge.addon.ui.facets.HintsFacet; import org.jboss.forge.addon.ui.hints.HintsLookup; import org.jboss.forge.addon.ui.input.InputComponent; import org.jboss.forge.furnace.util.Callables; /** * @author <a href="mailto:[email protected]">Lincoln Baxter, III</a> * */ public class HintsFacetImpl extends AbstractFacet<InputComponent<?, ?>>implements HintsFacet { private HintsLookup hintsLookup; private String inputType; private Callable<Boolean> promptInInteractiveMode; public HintsFacetImpl(InputComponent<?, ?> origin, Environment environment) { super.setFaceted(origin); if (environment == null) { throw new IllegalStateException("Environment must not be null."); } this.hintsLookup = new HintsLookup(environment); } @Override public boolean install() { return true; } @Override public boolean isInstalled() { return getFaceted().hasFacet(this.getClass()); } @Override public String getInputType() { if (inputType == null) { inputType = hintsLookup.getInputType(getFaceted().getValueType()); } return inputType; } @Override public HintsFacet setInputType(String type) { inputType = type; return this; } @Override public boolean isPromptInInteractiveMode() { if (promptInInteractiveMode == null) return (origin.isRequired() && !(origin.hasDefaultValue() || origin.hasValue())); return Callables.call(promptInInteractiveMode); } @Override public HintsFacet setPromptInInteractiveMode(boolean prompt) { this.promptInInteractiveMode = Callables.returning(prompt); return this; } @Override public HintsFacet setPromptInInteractiveMode(Callable<Boolean> prompt) { this.promptInInteractiveMode = prompt; return this; } @Override public String toString() { return "HintsFacetImpl [inputType=" + getInputType() + ", promptInInteractiveMode=" + isPromptInInteractiveMode() + "]"; } }
ui/impl/src/main/java/org/jboss/forge/addon/ui/impl/facets/HintsFacetImpl.java
/* * Copyright 2013 Red Hat, Inc. and/or its affiliates. * * Licensed under the Eclipse Public License version 1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ package org.jboss.forge.addon.ui.impl.facets; import java.util.concurrent.Callable; import org.jboss.forge.addon.environment.Environment; import org.jboss.forge.addon.facets.AbstractFacet; import org.jboss.forge.addon.ui.facets.HintsFacet; import org.jboss.forge.addon.ui.hints.HintsLookup; import org.jboss.forge.addon.ui.input.InputComponent; import org.jboss.forge.furnace.util.Callables; /** * @author <a href="mailto:[email protected]">Lincoln Baxter, III</a> * */ public class HintsFacetImpl extends AbstractFacet<InputComponent<?, ?>> implements HintsFacet { private HintsLookup hintsLookup; private String inputType; private Callable<Boolean> promptInInteractiveMode; public HintsFacetImpl(InputComponent<?, ?> origin, Environment environment) { super.setFaceted(origin); if (environment == null) { throw new IllegalStateException("Environment must not be null."); } this.hintsLookup = new HintsLookup(environment); } @Override public boolean install() { return true; } @Override public boolean isInstalled() { return getFaceted().hasFacet(this.getClass()); } @Override public String getInputType() { if (inputType == null) { inputType = hintsLookup.getInputType(getFaceted().getValueType()); } return inputType; } @Override public HintsFacet setInputType(String type) { inputType = type; return this; } @Override public boolean isPromptInInteractiveMode() { if (promptInInteractiveMode == null) return (origin.isRequired() && !(origin.hasDefaultValue() || origin.hasValue())); return Callables.call(promptInInteractiveMode); } @Override public HintsFacet setPromptInInteractiveMode(boolean prompt) { this.promptInInteractiveMode = Callables.returning(prompt); return this; } @Override public HintsFacet setPromptInInteractiveMode(Callable<Boolean> prompt) { this.promptInInteractiveMode = prompt; return this; } }
Added toString to HintsFacetImpl
ui/impl/src/main/java/org/jboss/forge/addon/ui/impl/facets/HintsFacetImpl.java
Added toString to HintsFacetImpl
Java
agpl-3.0
a3e22d573ff13208dad10b86ef50aea1922a0d4b
0
Freeyourgadget/Gadgetbridge,Freeyourgadget/Gadgetbridge,Freeyourgadget/Gadgetbridge,Freeyourgadget/Gadgetbridge
/* Copyright (C) 2017-2018 Andreas Shimokawa, Carsten Pfeiffer This file is part of Gadgetbridge. Gadgetbridge is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Gadgetbridge 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package nodomain.freeyourgadget.gadgetbridge.service.devices.huami.amazfitbip; import java.util.HashMap; import java.util.Map; import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice; import nodomain.freeyourgadget.gadgetbridge.model.DeviceType; import nodomain.freeyourgadget.gadgetbridge.service.devices.huami.HuamiFirmwareInfo; import nodomain.freeyourgadget.gadgetbridge.service.devices.huami.HuamiFirmwareType; import nodomain.freeyourgadget.gadgetbridge.util.ArrayUtils; import nodomain.freeyourgadget.gadgetbridge.util.Version; public class AmazfitBipFirmwareInfo extends HuamiFirmwareInfo { // gps detection is totally bogus, just the first 16 bytes private static final byte[] GPS_HEADER = new byte[]{ (byte) 0xcb, 0x51, (byte) 0xc1, 0x30, 0x41, (byte) 0x9e, 0x5e, (byte) 0xd3, 0x51, 0x35, (byte) 0xdf, 0x66, (byte) 0xed, (byte) 0xd9, 0x5f, (byte) 0xa7 }; private static final byte[] GPS_HEADER2 = new byte[]{ 0x10, 0x50, 0x26, 0x76, (byte) 0x8f, 0x4a, (byte) 0xa1, 0x49, (byte) 0xa7, 0x26, (byte) 0xd0, (byte) 0xe6, 0x4a, 0x21, (byte) 0x88, (byte) 0xd4 }; private static final byte[] GPS_HEADER3 = new byte[]{ (byte) 0xeb, (byte) 0xfa, (byte) 0xc5, (byte) 0x89, (byte) 0xf0, 0x5c, 0x2e, (byte) 0xcc, (byte) 0xfa, (byte) 0xf3, 0x62, (byte) 0xeb, (byte) 0x92, (byte) 0xc6, (byte) 0xa1, (byte) 0xbb }; private static final byte[] GPS_HEADER4 = new byte[]{ 0x0b, 0x61, 0x53, (byte) 0xed, (byte) 0x83, (byte) 0xac, 0x07, 0x21, (byte) 0x8c, 0x36, 0x2e, (byte) 0x8c, (byte) 0x9c, 0x08, 0x54, (byte) 0xa6 }; // this is the same as Cor private static final byte[] FW_HEADER = new byte[]{ 0x00, (byte) 0x98, 0x00, 0x20, (byte) 0xA5, 0x04, 0x00, 0x20, (byte) 0xAD, 0x04, 0x00, 0x20, (byte) 0xC5, 0x04, 0x00, 0x20 }; private static final byte[] GPS_ALMANAC_HEADER = new byte[]{ // probably wrong (byte) 0xa0, (byte) 0x80, 0x08, 0x00, (byte) 0x8b, 0x07 }; private static final byte[] GPS_CEP_HEADER = new byte[]{ // probably wrong 0x2a, 0x12, (byte) 0xa0, 0x02 }; private static Map<Integer, String> crcToVersion = new HashMap<>(); static { // firmware crcToVersion.put(25257, "0.0.8.74"); crcToVersion.put(57724, "0.0.8.88"); crcToVersion.put(27668, "0.0.8.96"); crcToVersion.put(60173, "0.0.8.97"); crcToVersion.put(3462, "0.0.8.98"); crcToVersion.put(55420, "0.0.9.14"); crcToVersion.put(39465, "0.0.9.26"); crcToVersion.put(27394, "0.0.9.40"); crcToVersion.put(24736, "0.0.9.49"); crcToVersion.put(49555, "0.0.9.59"); crcToVersion.put(28586, "0.1.0.08"); crcToVersion.put(26714, "0.1.0.11"); crcToVersion.put(64160, "0.1.0.17"); crcToVersion.put(21992, "0.1.0.26"); crcToVersion.put(43028, "0.1.0.27"); crcToVersion.put(59462, "0.1.0.33"); crcToVersion.put(55277, "0.1.0.39"); crcToVersion.put(47685, "0.1.0.43"); crcToVersion.put(2839, "0.1.0.44"); crcToVersion.put(30229, "0.1.0.45"); crcToVersion.put(24302, "0.1.0.70"); crcToVersion.put(1333, "0.1.0.80"); crcToVersion.put(12017, "0.1.0.86"); crcToVersion.put(8276, "0.1.1.14"); crcToVersion.put(5914, "0.1.1.17"); crcToVersion.put(6228, "0.1.1.29"); crcToVersion.put(44223, "0.1.1.31"); crcToVersion.put(39726, "0.1.1.36"); crcToVersion.put(11062, "0.1.1.39"); crcToVersion.put(56670, "0.1.1.41"); crcToVersion.put(58736, "0.1.1.45"); crcToVersion.put(2602, "1.0.2.00"); // resources crcToVersion.put(12586, "0.0.8.74"); crcToVersion.put(34068, "0.0.8.88"); crcToVersion.put(59839, "0.0.8.96-98"); crcToVersion.put(50401, "0.0.9.14-26"); crcToVersion.put(22051, "0.0.9.40"); crcToVersion.put(46233, "0.0.9.49-0.1.0.11"); crcToVersion.put(12098, "0.1.0.17"); crcToVersion.put(28696, "0.1.0.26-27"); crcToVersion.put(5650, "0.1.0.33"); crcToVersion.put(16117, "0.1.0.39-45"); crcToVersion.put(22506, "0.1.0.66-70"); crcToVersion.put(42264, "0.1.0.77-80"); crcToVersion.put(55934, "0.1.0.86-89"); crcToVersion.put(26587, "0.1.1.14-25"); crcToVersion.put(7446, "0.1.1.29"); crcToVersion.put(47887, "0.1.1.31-36"); crcToVersion.put(14334, "0.1.1.39"); crcToVersion.put(21109, "0.1.1.41"); crcToVersion.put(23073, "0.1.1.45"); crcToVersion.put(59245, "1.0.2.00"); // gps crcToVersion.put(61520, "9367,8f79a91,0,0,"); crcToVersion.put(8784, "9565,dfbd8fa,0,0,"); crcToVersion.put(16716, "9565,dfbd8faf42,0"); crcToVersion.put(54154, "9567,8b05506,0,0,"); // font crcToVersion.put(61054, "8"); crcToVersion.put(62291, "9 (Latin)"); } public AmazfitBipFirmwareInfo(byte[] bytes) { super(bytes); } @Override protected HuamiFirmwareType determineFirmwareType(byte[] bytes) { if (ArrayUtils.startsWith(bytes, RES_HEADER) || ArrayUtils.startsWith(bytes, NEWRES_HEADER)) { if ((bytes.length <= 100000) || (bytes.length > 700000)) { // dont know how to distinguish from Cor/Mi Band 3 .res return HuamiFirmwareType.INVALID; } return HuamiFirmwareType.RES; } if (ArrayUtils.startsWith(bytes, GPS_HEADER) || ArrayUtils.startsWith(bytes, GPS_HEADER2) || ArrayUtils.startsWith(bytes, GPS_HEADER3) || ArrayUtils.startsWith(bytes, GPS_HEADER4)) { return HuamiFirmwareType.GPS; } if (ArrayUtils.startsWith(bytes, GPS_ALMANAC_HEADER)) { return HuamiFirmwareType.GPS_ALMANAC; } if (ArrayUtils.startsWith(bytes, GPS_CEP_HEADER)) { return HuamiFirmwareType.GPS_CEP; } if (ArrayUtils.startsWith(bytes, FW_HEADER)) { String foundVersion = searchFirmwareVersion(bytes); if (foundVersion != null) { Version version = new Version(foundVersion); if ((version.compareTo(new Version("0.0.8.00")) >= 0) && (version.compareTo(new Version("1.0.5.00")) < 0)) { return HuamiFirmwareType.FIRMWARE; } } return HuamiFirmwareType.INVALID; } if (ArrayUtils.startsWith(bytes, WATCHFACE_HEADER)) { return HuamiFirmwareType.WATCHFACE; } if (ArrayUtils.startsWith(bytes, NEWFT_HEADER)) { if (bytes[10] == 0x01) { return HuamiFirmwareType.FONT; } else if (bytes[10] == 0x02) { return HuamiFirmwareType.FONT_LATIN; } } return HuamiFirmwareType.INVALID; } @Override public boolean isGenerallyCompatibleWith(GBDevice device) { return isHeaderValid() && device.getType() == DeviceType.AMAZFITBIP; } @Override protected Map<Integer, String> getCrcMap() { return crcToVersion; } }
app/src/main/java/nodomain/freeyourgadget/gadgetbridge/service/devices/huami/amazfitbip/AmazfitBipFirmwareInfo.java
/* Copyright (C) 2017-2018 Andreas Shimokawa, Carsten Pfeiffer This file is part of Gadgetbridge. Gadgetbridge is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Gadgetbridge 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package nodomain.freeyourgadget.gadgetbridge.service.devices.huami.amazfitbip; import java.util.HashMap; import java.util.Map; import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice; import nodomain.freeyourgadget.gadgetbridge.model.DeviceType; import nodomain.freeyourgadget.gadgetbridge.service.devices.huami.HuamiFirmwareInfo; import nodomain.freeyourgadget.gadgetbridge.service.devices.huami.HuamiFirmwareType; import nodomain.freeyourgadget.gadgetbridge.util.ArrayUtils; import nodomain.freeyourgadget.gadgetbridge.util.Version; public class AmazfitBipFirmwareInfo extends HuamiFirmwareInfo { // gps detection is totally bogus, just the first 16 bytes private static final byte[] GPS_HEADER = new byte[]{ (byte) 0xcb, 0x51, (byte) 0xc1, 0x30, 0x41, (byte) 0x9e, 0x5e, (byte) 0xd3, 0x51, 0x35, (byte) 0xdf, 0x66, (byte) 0xed, (byte) 0xd9, 0x5f, (byte) 0xa7 }; private static final byte[] GPS_HEADER2 = new byte[]{ 0x10, 0x50, 0x26, 0x76, (byte) 0x8f, 0x4a, (byte) 0xa1, 0x49, (byte) 0xa7, 0x26, (byte) 0xd0, (byte) 0xe6, 0x4a, 0x21, (byte) 0x88, (byte) 0xd4 }; private static final byte[] GPS_HEADER3 = new byte[]{ (byte) 0xeb, (byte) 0xfa, (byte) 0xc5, (byte) 0x89, (byte) 0xf0, 0x5c, 0x2e, (byte) 0xcc, (byte) 0xfa, (byte) 0xf3, 0x62, (byte) 0xeb, (byte) 0x92, (byte) 0xc6, (byte) 0xa1, (byte) 0xbb }; private static final byte[] GPS_HEADER4 = new byte[]{ 0x0b, 0x61, 0x53, (byte) 0xed, (byte) 0x83, (byte) 0xac, 0x07, 0x21, (byte) 0x8c, 0x36, 0x2e, (byte) 0x8c, (byte) 0x9c, 0x08, 0x54, (byte) 0xa6 }; // this is the same as Cor private static final byte[] FW_HEADER = new byte[]{ 0x00, (byte) 0x98, 0x00, 0x20, (byte) 0xA5, 0x04, 0x00, 0x20, (byte) 0xAD, 0x04, 0x00, 0x20, (byte) 0xC5, 0x04, 0x00, 0x20 }; private static final byte[] GPS_ALMANAC_HEADER = new byte[]{ // probably wrong (byte) 0xa0, (byte) 0x80, 0x08, 0x00, (byte) 0x8b, 0x07 }; private static final byte[] GPS_CEP_HEADER = new byte[]{ // probably wrong 0x2a, 0x12, (byte) 0xa0, 0x02 }; private static Map<Integer, String> crcToVersion = new HashMap<>(); static { // firmware crcToVersion.put(25257, "0.0.8.74"); crcToVersion.put(57724, "0.0.8.88"); crcToVersion.put(27668, "0.0.8.96"); crcToVersion.put(60173, "0.0.8.97"); crcToVersion.put(3462, "0.0.8.98"); crcToVersion.put(55420, "0.0.9.14"); crcToVersion.put(39465, "0.0.9.26"); crcToVersion.put(27394, "0.0.9.40"); crcToVersion.put(24736, "0.0.9.49"); crcToVersion.put(49555, "0.0.9.59"); crcToVersion.put(28586, "0.1.0.08"); crcToVersion.put(26714, "0.1.0.11"); crcToVersion.put(64160, "0.1.0.17"); crcToVersion.put(21992, "0.1.0.26"); crcToVersion.put(43028, "0.1.0.27"); crcToVersion.put(59462, "0.1.0.33"); crcToVersion.put(55277, "0.1.0.39"); crcToVersion.put(47685, "0.1.0.43"); crcToVersion.put(2839, "0.1.0.44"); crcToVersion.put(30229, "0.1.0.45"); crcToVersion.put(24302, "0.1.0.70"); crcToVersion.put(1333, "0.1.0.80"); crcToVersion.put(12017, "0.1.0.86"); crcToVersion.put(8276, "0.1.1.14"); crcToVersion.put(5914, "0.1.1.17"); crcToVersion.put(6228, "0.1.1.29"); crcToVersion.put(44223, "0.1.1.31"); crcToVersion.put(39726, "0.1.1.36"); crcToVersion.put(11062, "0.1.1.39"); crcToVersion.put(56670, "0.1.1.41"); crcToVersion.put(58736, "0.1.1.45"); // resources crcToVersion.put(12586, "0.0.8.74"); crcToVersion.put(34068, "0.0.8.88"); crcToVersion.put(59839, "0.0.8.96-98"); crcToVersion.put(50401, "0.0.9.14-26"); crcToVersion.put(22051, "0.0.9.40"); crcToVersion.put(46233, "0.0.9.49-0.1.0.11"); crcToVersion.put(12098, "0.1.0.17"); crcToVersion.put(28696, "0.1.0.26-27"); crcToVersion.put(5650, "0.1.0.33"); crcToVersion.put(16117, "0.1.0.39-45"); crcToVersion.put(22506, "0.1.0.66-70"); crcToVersion.put(42264, "0.1.0.77-80"); crcToVersion.put(55934, "0.1.0.86-89"); crcToVersion.put(26587, "0.1.1.14-25"); crcToVersion.put(7446, "0.1.1.29"); crcToVersion.put(47887, "0.1.1.31-36"); crcToVersion.put(14334, "0.1.1.39"); crcToVersion.put(21109, "0.1.1.41"); crcToVersion.put(23073, "0.1.1.45"); // gps crcToVersion.put(61520, "9367,8f79a91,0,0,"); crcToVersion.put(8784, "9565,dfbd8fa,0,0,"); crcToVersion.put(16716, "9565,dfbd8faf42,0"); crcToVersion.put(54154, "9567,8b05506,0,0,"); // font crcToVersion.put(61054, "8"); crcToVersion.put(62291, "9 (Latin)"); } public AmazfitBipFirmwareInfo(byte[] bytes) { super(bytes); } @Override protected HuamiFirmwareType determineFirmwareType(byte[] bytes) { if (ArrayUtils.startsWith(bytes, RES_HEADER) || ArrayUtils.startsWith(bytes, NEWRES_HEADER)) { if ((bytes.length <= 100000) || (bytes.length > 700000)) { // dont know how to distinguish from Cor/Mi Band 3 .res return HuamiFirmwareType.INVALID; } return HuamiFirmwareType.RES; } if (ArrayUtils.startsWith(bytes, GPS_HEADER) || ArrayUtils.startsWith(bytes, GPS_HEADER2) || ArrayUtils.startsWith(bytes, GPS_HEADER3) || ArrayUtils.startsWith(bytes, GPS_HEADER4)) { return HuamiFirmwareType.GPS; } if (ArrayUtils.startsWith(bytes, GPS_ALMANAC_HEADER)) { return HuamiFirmwareType.GPS_ALMANAC; } if (ArrayUtils.startsWith(bytes, GPS_CEP_HEADER)) { return HuamiFirmwareType.GPS_CEP; } if (ArrayUtils.startsWith(bytes, FW_HEADER)) { String foundVersion = searchFirmwareVersion(bytes); if (foundVersion != null) { Version version = new Version(foundVersion); if ((version.compareTo(new Version("0.0.8.00")) >= 0) && (version.compareTo(new Version("1.0.5.00")) < 0)) { return HuamiFirmwareType.FIRMWARE; } } return HuamiFirmwareType.INVALID; } if (ArrayUtils.startsWith(bytes, WATCHFACE_HEADER)) { return HuamiFirmwareType.WATCHFACE; } if (ArrayUtils.startsWith(bytes, NEWFT_HEADER)) { if (bytes[10] == 0x01) { return HuamiFirmwareType.FONT; } else if (bytes[10] == 0x02) { return HuamiFirmwareType.FONT_LATIN; } } return HuamiFirmwareType.INVALID; } @Override public boolean isGenerallyCompatibleWith(GBDevice device) { return isHeaderValid() && device.getType() == DeviceType.AMAZFITBIP; } @Override protected Map<Integer, String> getCrcMap() { return crcToVersion; } }
Amazfit Bip: Whitelist FW 1.0.2.00
app/src/main/java/nodomain/freeyourgadget/gadgetbridge/service/devices/huami/amazfitbip/AmazfitBipFirmwareInfo.java
Amazfit Bip: Whitelist FW 1.0.2.00
Java
agpl-3.0
e433cc3efb9e985260ecebce6804f4133c759171
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
a33a8604-2e5f-11e5-9284-b827eb9e62be
hello.java
a3351ee4-2e5f-11e5-9284-b827eb9e62be
a33a8604-2e5f-11e5-9284-b827eb9e62be
hello.java
a33a8604-2e5f-11e5-9284-b827eb9e62be
Java
agpl-3.0
b2371c65a73ffdaea73e66d897beb83f4824ea99
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
b87f6cee-2e61-11e5-9284-b827eb9e62be
hello.java
b879e832-2e61-11e5-9284-b827eb9e62be
b87f6cee-2e61-11e5-9284-b827eb9e62be
hello.java
b87f6cee-2e61-11e5-9284-b827eb9e62be
Java
agpl-3.0
86039d4f8c575bcbc3e7e930e85fab3a049368ee
0
animotron/core,animotron/core
/* * Copyright (C) 2011 The Animo Project * http://animotron.org * * 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, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package org.animotron.exist.index; import org.exist.dom.ElementAtExist; /** * @author <a href="mailto:[email protected]">Dmitriy Shabanov</a> * */ public class Utils { protected static String getUniqNodeId(ElementAtExist element) { return String.valueOf( element.getDocumentAtExist().getDocId() ) + "-" + String.valueOf( element.getNodeId().units() ); } }
src/main/java/org/animotron/exist/index/Utils.java
/* * Copyright (C) 2011 The Animo Project * http://animotron.org * * 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, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package org.animotron.exist.index; import org.exist.dom.ElementAtExist; /** * @author <a href="mailto:[email protected]">Dmitriy Shabanov</a> * */ public class Utils { protected static String getUniqNodeId(ElementAtExist element) { return String.valueOf( element.getDocumentAtExist().getDocId() ) + String.valueOf( element.getNodeId().units() ); } }
Add separator
src/main/java/org/animotron/exist/index/Utils.java
Add separator
Java
agpl-3.0
98f06817b76e8d7c428486f92888641cef947e1c
0
digitalbazaar/monarch,digitalbazaar/monarch,digitalbazaar/monarch,digitalbazaar/monarch,digitalbazaar/monarch
/* * Copyright (c) 2008 Digital Bazaar, Inc. All rights reserved. */ package com.db.data; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; /** * A JsonWriter provides an interface for serializing objects to * JSON (JavaScript Object Notation) (RFC 4627). * * A JsonWriter writes out a whole object at once and can be used again. * The compact setting should be used to minimize extra whitespace when not * needed. * * @author David I. Lehn * @author Dave Longley */ public class JsonWriter { /** * Compact mode to minimize whitespace. */ protected boolean mCompact; /** * The starting indentation level. */ protected int mIndentLevel; /** * The number of spaces per indentation level. */ protected int mIndentSpaces; /** * Creates a new JsonWriter. */ public JsonWriter() { // Initialize to compact representation setCompact(true); setIndentation(0, 3); } /** * Writes out indentation. None if in compact mode. * * @param os the OutputStream to write to. * @param level indentation level. * * @exception IOException thrown if an IO error occurs. */ protected void writeIndentation(OutputStream os, int level) throws IOException { int indent = mCompact ? 0 : (level * mIndentSpaces); // write out indentation if(indent > 0) { byte[] temp = new byte[indent]; byte c = ' '; Arrays.fill(temp, c); os.write(temp, 0, indent); } } /** * Recursively serializes an object to JSON using the passed DynamicObject. * * @param dyno the DynamicObject to serialize. * @param os the OutputStream to write the JSON to. * @param level current level of indentation (-1 to initialize with default). * * @exception IOException thrown if an IO error occurs. */ protected void write(DynamicObject dyno, OutputStream os, int level) throws IOException { if(level < 0) { level = mIndentLevel; } if(dyno == null) { os.write(new String("null").getBytes("ASCII")); } else { switch(dyno.getType()) { case String: { String temp = dyno.getString(); int length = temp.length(); // UTF-8 has a maximum of 7-bytes per character when // encoded in json format StringBuilder encoded = new StringBuilder(length * 7 + 2); encoded.append('"'); for(int i = 0; i < length; i++) { char c = temp.charAt(i); if((c >= 0x5d /* && c <= 0x10FFFF */) || (c >= 0x23 && c <= 0x5B) || (c == 0x21) || (c == 0x20)) { // TODO: check this handles UTF-* properly encoded.append(c); } else { encoded.append('\\'); switch(c) { case '"': /* 0x22 */ case '\\': /* 0x5C */ encoded.append(c); break; // '/' is in the RFC but not required to be escaped //case '/': /* 0x2F */ // encoded[n++] = '/'; // break; case '\b': /* 0x08 */ encoded.append('b'); break; case '\f': /* 0x0C */ encoded.append('f'); break; case '\n': /* 0x0A */ encoded.append('n'); break; case '\r': /* 0x0D */ encoded.append('r'); break; case '\t': /* 0x09 */ encoded.append('t'); break; default: encoded.append(String.format("u%04x", (int)c)); break; } } } // end string serialization and write encoded string encoded.append('"'); os.write(encoded.toString().getBytes("ASCII")); } break; case Boolean: case Number: { os.write(dyno.getString().getBytes("ASCII")); } break; case Map: { // start map serialization if(mCompact) { byte b = '{'; os.write(b); } else { byte[] b = {'{','\n'}; os.write(b); } // serialize each map member byte b; byte[] compactEndName = {'"',':'}; byte[] endName = {'"',' ',':',' '}; DynamicObjectIterator i = dyno.getIterator(); while(i.hasNext()) { DynamicObject next = i.next(); // serialize indentation and start serializing member name writeIndentation(os, level + 1); b = '"'; os.write(b); os.write(i.getName().getBytes("UTF-8")); // end serializing member name, serialize member value if(mCompact) { os.write(compactEndName); } else { os.write(endName); } // write object write(next, os, level + 1); // serialize delimiter if appropriate if(i.hasNext()) { b = ','; os.write(b); } // add formatting if appropriate if(!mCompact) { b = '\n'; os.write(b); } } // end map serialization writeIndentation(os, level); b = '}'; os.write(b); } break; case Array: { // start array serialization if(mCompact) { byte b = '['; os.write(b); } else { byte[] b = {'[','\n'}; os.write(b); } // serialize each array element byte b; DynamicObjectIterator i = dyno.getIterator(); while(i.hasNext()) { // serialize indentation and array value writeIndentation(os, level + 1); write(i.next(), os, level + 1); // serialize delimiter if appropriate if(i.hasNext()) { b = ','; os.write(b); } // add formatting if appropriate if(!mCompact) { b = '\n'; os.write(b); } } // end array serialization writeIndentation(os, level); b = ']'; os.write(b); } break; } } } /** * Serializes an object to JSON using the passed DynamicObject. * * @param dyno the DynamicObject to serialize. * @param os the OutputStream to write the JSON to. * * @exception IOException thrown if an IO error occurs. */ public void write(DynamicObject dyno, OutputStream os) throws IOException { BufferedOutputStream bos = new BufferedOutputStream(os); write(dyno, bos, mIndentLevel); bos.flush(); } /** * Sets the starting indentation level and the number of spaces * per indentation level. * * @param level the starting indentation level. * @param spaces the number of spaces per indentation level. */ public void setIndentation(int level, int spaces) { mIndentLevel = level; mIndentSpaces = spaces; } /** * Sets the writer to use compact mode and not output unneeded whitespace. * * @param compact true to minimize whitespace, false not to. */ public void setCompact(boolean compact) { mCompact = compact; } }
data/java/src/com/db/data/JsonWriter.java
/* * Copyright (c) 2008 Digital Bazaar, Inc. All rights reserved. */ package com.db.data; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; /** * A JsonWriter provides an interface for serializing objects to * JSON (JavaScript Object Notation) (RFC 4627). * * A JsonWriter writes out a whole object at once and can be used again. * The compact setting should be used to minimize extra whitespace when not * needed. * * @author David I. Lehn * @author Dave Longley */ public class JsonWriter { /** * Compact mode to minimize whitespace. */ protected boolean mCompact; /** * The starting indentation level. */ protected int mIndentLevel; /** * The number of spaces per indentation level. */ protected int mIndentSpaces; /** * Creates a new JsonWriter. */ public JsonWriter() { // Initialize to compact representation setCompact(true); setIndentation(0, 3); } /** * Writes out indentation. None if in compact mode. * * @param os the OutputStream to write to. * @param level indentation level. * * @exception IOException thrown if an IO error occurs. */ protected void writeIndentation(OutputStream os, int level) throws IOException { int indent = mCompact ? 0 : (level * mIndentSpaces); // write out indentation if(indent > 0) { byte[] temp = new byte[indent]; byte c = ' '; Arrays.fill(temp, c); os.write(temp, 0, indent); } } /** * Recursively serializes an object to JSON using the passed DynamicObject. * * @param dyno the DynamicObject to serialize. * @param os the OutputStream to write the JSON to. * @param level current level of indentation (-1 to initialize with default). * * @exception IOException thrown if an IO error occurs. */ protected void write(DynamicObject dyno, OutputStream os, int level) throws IOException { if(level < 0) { level = mIndentLevel; } if(dyno == null) { os.write(new String("null").getBytes("UTF-8")); } else { switch(dyno.getType()) { case String: { String temp = dyno.getString(); int length = temp.length(); // UTF-8 has a maximum of 7-bytes per character when // encoded in json format StringBuilder encoded = new StringBuilder(length * 7 + 2); encoded.append('"'); for(int i = 0; i < length; i++) { char c = temp.charAt(i); if((c >= 0x5d /* && c <= 0x10FFFF */) || (c >= 0x23 && c <= 0x5B) || (c == 0x21) || (c == 0x20)) { // TODO: check this handles UTF-* properly encoded.append(c); } else { encoded.append('\\'); switch(c) { case '"': /* 0x22 */ case '\\': /* 0x5C */ encoded.append(c); break; // '/' is in the RFC but not required to be escaped //case '/': /* 0x2F */ // encoded[n++] = '/'; // break; case '\b': /* 0x08 */ encoded.append('b'); break; case '\f': /* 0x0C */ encoded.append('f'); break; case '\n': /* 0x0A */ encoded.append('n'); break; case '\r': /* 0x0D */ encoded.append('r'); break; case '\t': /* 0x09 */ encoded.append('t'); break; default: encoded.append(String.format("u%04x", (int)c)); break; } } } // end string serialization and write encoded string encoded.append('"'); os.write(encoded.toString().getBytes("UTF-8")); } break; case Boolean: case Number: { os.write(dyno.getString().getBytes("UTF-8")); } break; case Map: { // start map serialization if(mCompact) { byte b = '{'; os.write(b); } else { byte[] b = {'{','\n'}; os.write(b); } // serialize each map member byte b; byte[] compactEndName = {'"',':'}; byte[] endName = {'"',' ',':',' '}; DynamicObjectIterator i = dyno.getIterator(); while(i.hasNext()) { DynamicObject next = i.next(); // serialize indentation and start serializing member name writeIndentation(os, level + 1); b = '"'; os.write(b); os.write(i.getName().getBytes("UTF-8")); // end serializing member name, serialize member value if(mCompact) { os.write(compactEndName); } else { os.write(endName); } // write object write(next, os, level + 1); // serialize delimiter if appropriate if(i.hasNext()) { b = ','; os.write(b); } // add formatting if appropriate if(!mCompact) { b = '\n'; os.write(b); } } // end map serialization writeIndentation(os, level); b = '}'; os.write(b); } break; case Array: { // start array serialization if(mCompact) { byte b = '['; os.write(b); } else { byte[] b = {'[','\n'}; os.write(b); } // serialize each array element byte b; DynamicObjectIterator i = dyno.getIterator(); while(i.hasNext()) { // serialize indentation and array value writeIndentation(os, level + 1); write(i.next(), os, level + 1); // serialize delimiter if appropriate if(i.hasNext()) { b = ','; os.write(b); } // add formatting if appropriate if(!mCompact) { b = '\n'; os.write(b); } } // end array serialization writeIndentation(os, level); b = ']'; os.write(b); } break; } } } /** * Serializes an object to JSON using the passed DynamicObject. * * @param dyno the DynamicObject to serialize. * @param os the OutputStream to write the JSON to. * * @exception IOException thrown if an IO error occurs. */ public void write(DynamicObject dyno, OutputStream os) throws IOException { BufferedOutputStream bos = new BufferedOutputStream(os); write(dyno, bos, mIndentLevel); bos.flush(); } /** * Sets the starting indentation level and the number of spaces * per indentation level. * * @param level the starting indentation level. * @param spaces the number of spaces per indentation level. */ public void setIndentation(int level, int spaces) { mIndentLevel = level; mIndentSpaces = spaces; } /** * Sets the writer to use compact mode and not output unneeded whitespace. * * @param compact true to minimize whitespace, false not to. */ public void setCompact(boolean compact) { mCompact = compact; } }
Changed UTF-8 encoding to ASCII in some places.
data/java/src/com/db/data/JsonWriter.java
Changed UTF-8 encoding to ASCII in some places.
Java
lgpl-2.1
7d20d25a1e81e07ee49910f5368ca9d975f3334d
0
golovnin/wildfly,rhusar/wildfly,jstourac/wildfly,xasx/wildfly,jstourac/wildfly,rhusar/wildfly,iweiss/wildfly,99sono/wildfly,iweiss/wildfly,tomazzupan/wildfly,tomazzupan/wildfly,iweiss/wildfly,wildfly/wildfly,rhusar/wildfly,tadamski/wildfly,99sono/wildfly,tomazzupan/wildfly,iweiss/wildfly,xasx/wildfly,jstourac/wildfly,wildfly/wildfly,rhusar/wildfly,jstourac/wildfly,wildfly/wildfly,tadamski/wildfly,pferraro/wildfly,golovnin/wildfly,pferraro/wildfly,wildfly/wildfly,xasx/wildfly,tadamski/wildfly,golovnin/wildfly,99sono/wildfly,pferraro/wildfly,pferraro/wildfly
/* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This 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 2.1 of * the License, or (at your option) any later version. * * This software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.server.deployment; /** * An enumeration of the phases of a deployment unit's processing cycle. * * @author <a href="mailto:[email protected]">David M. Lloyd</a> */ public enum Phase { /* == TEMPLATE == * Upon entry, this phase performs the following actions: * <ul> * <li></li> * </ul> * <p> * Processors in this phase have access to the following phase attachments: * <ul> * <li>{@link Attachments#BLAH} - description here</li> * </ul> * <p> * Processors in this phase have access to the following deployment unit attachments, in addition to those defined * for the previous phase: * <ul> * <li>{@link Attachments#BLAH} - description here</li> * </ul> * <p> * In this phase, these phase attachments may be modified: * <ul> * <li>{@link Attachments#BLAH} - description here</li> * </ul> * <p> */ /** * This phase creates the initial root structure. Depending on the service for this phase will ensure that the * deployment unit's initial root structure is available and accessible. * <p> * Upon entry, this phase performs the following actions: * <ul> * <li>The primary deployment root is mounted (during {@link #STRUCTURE_MOUNT})</li> * <li>Other internal deployment roots are mounted (during {@link #STRUCTURE_NESTED_JAR})</li> * </ul> * <p> * Processors in this phase have access to the following phase attachments: * <ul> * <li><i>N/A</i></li> * </ul> * <p> * Processors in this phase have access to the following deployment unit attachments: * <ul> * <li>{@link Attachments#DEPLOYMENT_ROOT} - the mounted deployment root for this deployment unit</li> * </ul> * <p> * In this phase, these phase attachments may be modified: * <ul> * </ul> * <p> */ STRUCTURE(null), /** * This phase assembles information from the root structure to prepare for adding and processing additional external * structure, such as from class path entries and other similar mechanisms. * <p> * Upon entry, this phase performs the following actions: * <ul> * <li>The root content's MANIFEST is read and made available during {@link #PARSE_MANIFEST}.</li> * <li>The annotation index for the root structure is calculated during {@link #STRUCTURE_ANNOTATION_INDEX}.</li> * </ul> * <p> * Processors in this phase have access to the following phase attachments: * <ul> * <li>{@link Attachments#MANIFEST} - the parsed manifest of the root structure</li> * </ul> * <p> * Processors in this phase have access to the following deployment unit attachments, in addition to those defined * for the previous phase: * <ul> * <li><i>N/A</i></li> * </ul> * <p> * In this phase, these phase attachments may be modified: * <ul> * <li>{@link Attachments#CLASS_PATH_ENTRIES} - class path entries found in the manifest and elsewhere.</li> * <li>{@link Attachments#EXTENSION_LIST_ENTRIES} - extension-list entries found in the manifest and elsewhere.</li> * </ul> * <p> */ PARSE(null), /** * In this phase, the full structure of the deployment unit is made available and module dependencies may be assembled. * <p> * Upon entry, this phase performs the following actions: * <ul> * <li>Any additional external structure is mounted during {@link #XXX}</li> * <li></li> * </ul> * <p> * Processors in this phase have access to the following phase attachments: * <ul> * <li>{@link Attachments#BLAH} - description here</li> * </ul> * <p> * Processors in this phase have access to the following deployment unit attachments, in addition to those defined * for the previous phase: * <ul> * <li>{@link Attachments#BLAH} - description here</li> * </ul> * <p> * In this phase, these phase attachments may be modified: * <ul> * <li>{@link Attachments#BLAH} - description here</li> * </ul> * <p> */ DEPENDENCIES(null), CONFIGURE_MODULE(null), MODULARIZE(null), POST_MODULE(null), INSTALL(null), CLEANUP(null), ; /** * This is the key for the attachment to use as the phase's "value". The attachment is taken from * the deployment unit. If a phase doesn't have a single defining "value", {@code null} is specified. */ private final AttachmentKey<?> phaseKey; private Phase(final AttachmentKey<?> key) { phaseKey = key; } /** * Get the next phase, or {@code null} if none. * * @return the next phase, or {@code null} if there is none */ public Phase next() { final int ord = ordinal() + 1; final Phase[] phases = Phase.values(); return ord == phases.length ? null : phases[ord]; } /** * Get the attachment key of the {@code DeploymentUnit} attachment that represents the result value * of this phase. * * @return the key */ public AttachmentKey<?> getPhaseKey() { return phaseKey; } // STRUCTURE public static final int STRUCTURE_MOUNT = 0x0000; public static final int STRUCTURE_MANIFEST = 0x0100; public static final int STRUCTURE_OSGI_MANIFEST = 0x0200; public static final int STRUCTURE_RAR = 0x0300; public static final int STRUCTURE_WAR_DEPLOYMENT_INIT = 0x0400; public static final int STRUCTURE_WAR = 0x0500; public static final int STRUCTURE_EAR_DEPLOYMENT_INIT = 0x0600; public static final int STRUCTURE_EAR_APP_XML_PARSE = 0x0700; public static final int STRUCTURE_EAR_JBOSS_APP_XML_PARSE = 0x0800; public static final int STRUCTURE_EAR = 0x0900; public static final int STRUCTURE_DEPLOYMENT_MODULE_LOADER = 0x0A00; public static final int STRUCTURE_ANNOTATION_INDEX = 0x0B00; public static final int STRUCTURE_MANAGED_BEAN_SUB_DEPLOY_CHECK = 0x0C00; public static final int STRUCTURE_SAR_SUB_DEPLOY_CHECK = 0x0D00; public static final int STRUCTURE_SUB_DEPLOYMENT = 0x0E00; // PARSE public static final int PARSE_COMPOSITE_ANNOTATION_INDEX = 0x0100; public static final int PARSE_CLASS_PATH = 0x0200; public static final int PARSE_EXTENSION_LIST = 0x0300; public static final int PARSE_OSGI_BUNDLE_INFO = 0x0400; public static final int PARSE_OSGI_PROPERTIES = 0x0500; public static final int PARSE_WEB_DEPLOYMENT = 0x0600; public static final int PARSE_WEB_DEPLOYMENT_FRAGMENT = 0x0700; public static final int PARSE_JBOSS_WEB_DEPLOYMENT = 0x0800; public static final int PARSE_TLD_DEPLOYMENT = 0x0900; public static final int PARSE_RA_DEPLOYMENT = 0x0A00; public static final int PARSE_SERVICE_LOADER_DEPLOYMENT = 0x0B00; public static final int PARSE_SERVICE_DEPLOYMENT = 0x0C00; public static final int PARSE_MC_BEAN_DEPLOYMENT = 0x0D00; public static final int PARSE_IRON_JACAMAR_DEPLOYMENT = 0x0E00; public static final int PARSE_RESOURCE_ADAPTERS = 0x0F00; public static final int PARSE_DATA_SOURCES = 0x1000; public static final int PARSE_ARQUILLIAN_RUNWITH = 0x1100; public static final int PARSE_MANAGED_BEAN_ANNOTATION = 0x1200; public static final int PARSE_BEAN_LIEFCYCLE_ANNOTATION = 0x1300; public static final int PARSE_BEAN_INTERCEPTOR_ANNOTATION = 0x1400; public static final int PARSE_BEAN_RESOURCE_INJECTION_ANNOTATION = 0x1500; public static final int PARSE_MANAGED_BEAN_RESOURCE_TARGET = 0x1600; // DEPENDENCIES public static final int DEPENDENCIES_MODULE = 0x100; public static final int DEPENDENCIES_DS = 0x200; public static final int DEPENDENCIES_RAR_CONFIG = 0x300; public static final int DEPENDENCIES_MANAGED_BEAN = 0x400; public static final int DEPENDENCIES_SAR_MODULE = 0x500; public static final int DEPENDENCIES_WAR_MODULE = 0x600; public static final int DEPENDENCIES_ARQUILLIAN = 0x700; public static final int DEPENDENCIES_CLASS_PATH = 0x800; public static final int DEPENDENCIES_EXTENSION_LIST = 0x900; // CONFIGURE_MODULE public static final int CONFIGURE_MODULE_WAR = 0x100; public static final int CONFIGURE_MODULE_SPEC = 0x200; // MODULARIZE public static final int MODULARIZE_DEPLOYMENT = 0x100; // POST_MODULE public static final int POST_MODULE_ANNOTATION_WAR = 0x100; public static final int POST_MODULE_ANNOTATION_ARQUILLIAN_JUNIT = 0x200; // INSTALL public static final int INSTALL_REFLECTION_INDEX = 0x0100; public static final int INSTALL_APP_CONTEXT = 0x0200; public static final int INSTALL_MODULE_CONTEXT = 0x0300; public static final int INSTALL_SERVICE_ACTIVATOR = 0x0400; public static final int INSTALL_OSGI_DEPLOYMENT = 0x0500; public static final int INSTALL_WAR_METADATA = 0x0600; public static final int INSTALL_RA_DEPLOYMENT = 0x0700; public static final int INSTALL_SERVICE_DEPLOYMENT = 0x0800; public static final int INSTALL_MC_BEAN_DEPLOYMENT = 0x0900; public static final int INSTALL_RA_XML_DEPLOYMENT = 0x0A00; public static final int INSTALL_DS_DEPLOYMENT = 0x0B00; public static final int INSTALL_MANAGED_BEAN_DEPLOYMENT = 0x0C00; public static final int INSTALL_BEAN_CONTAINER = 0x0D00; public static final int INSTALL_SERVLET_INIT_DEPLOYMENT = 0x0E00; public static final int INSTALL_WAR_DEPLOYMENT = 0x0F00; public static final int INSTALL_ARQUILLIAN_DEPLOYMENT = 0x1000; // CLEANUP public static final int CLEANUP_REFLECTION_INDEX = 0x100; }
server/src/main/java/org/jboss/as/server/deployment/Phase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This 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 2.1 of * the License, or (at your option) any later version. * * This software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.server.deployment; /** * An enumeration of the phases of a deployment unit's processing cycle. * * @author <a href="mailto:[email protected]">David M. Lloyd</a> */ public enum Phase { /* == TEMPLATE == * Upon entry, this phase performs the following actions: * <ul> * <li></li> * </ul> * <p> * Processors in this phase have access to the following phase attachments: * <ul> * <li>{@link Attachments#BLAH} - description here</li> * </ul> * <p> * Processors in this phase have access to the following deployment unit attachments, in addition to those defined * for the previous phase: * <ul> * <li>{@link Attachments#BLAH} - description here</li> * </ul> * <p> * In this phase, these phase attachments may be modified: * <ul> * <li>{@link Attachments#BLAH} - description here</li> * </ul> * <p> */ /** * This phase creates the initial root structure. Depending on the service for this phase will ensure that the * deployment unit's initial root structure is available and accessible. * <p> * Upon entry, this phase performs the following actions: * <ul> * <li>The primary deployment root is mounted (during {@link #STRUCTURE_MOUNT})</li> * <li>Other internal deployment roots are mounted (during {@link #STRUCTURE_NESTED_JAR})</li> * </ul> * <p> * Processors in this phase have access to the following phase attachments: * <ul> * <li><i>N/A</i></li> * </ul> * <p> * Processors in this phase have access to the following deployment unit attachments: * <ul> * <li>{@link Attachments#DEPLOYMENT_ROOT} - the mounted deployment root for this deployment unit</li> * </ul> * <p> * In this phase, these phase attachments may be modified: * <ul> * </ul> * <p> */ STRUCTURE(null), /** * This phase assembles information from the root structure to prepare for adding and processing additional external * structure, such as from class path entries and other similar mechanisms. * <p> * Upon entry, this phase performs the following actions: * <ul> * <li>The root content's MANIFEST is read and made available during {@link #PARSE_MANIFEST}.</li> * <li>The annotation index for the root structure is calculated during {@link #STRUCTURE_ANNOTATION_INDEX}.</li> * </ul> * <p> * Processors in this phase have access to the following phase attachments: * <ul> * <li>{@link Attachments#MANIFEST} - the parsed manifest of the root structure</li> * </ul> * <p> * Processors in this phase have access to the following deployment unit attachments, in addition to those defined * for the previous phase: * <ul> * <li><i>N/A</i></li> * </ul> * <p> * In this phase, these phase attachments may be modified: * <ul> * <li>{@link Attachments#CLASS_PATH_ENTRIES} - class path entries found in the manifest and elsewhere.</li> * <li>{@link Attachments#EXTENSION_LIST_ENTRIES} - extension-list entries found in the manifest and elsewhere.</li> * </ul> * <p> */ PARSE(null), /** * In this phase, the full structure of the deployment unit is made available and module dependencies may be assembled. * <p> * Upon entry, this phase performs the following actions: * <ul> * <li>Any additional external structure is mounted during {@link #XXX}</li> * <li></li> * </ul> * <p> * Processors in this phase have access to the following phase attachments: * <ul> * <li>{@link Attachments#BLAH} - description here</li> * </ul> * <p> * Processors in this phase have access to the following deployment unit attachments, in addition to those defined * for the previous phase: * <ul> * <li>{@link Attachments#BLAH} - description here</li> * </ul> * <p> * In this phase, these phase attachments may be modified: * <ul> * <li>{@link Attachments#BLAH} - description here</li> * </ul> * <p> */ DEPENDENCIES(null), CONFIGURE_MODULE(null), MODULARIZE(null), POST_MODULE(null), INSTALL(null), CLEANUP(null), ; /** * This is the key for the attachment to use as the phase's "value". The attachment is taken from * the deployment unit. If a phase doesn't have a single defining "value", {@code null} is specified. */ private final AttachmentKey<?> phaseKey; private Phase(final AttachmentKey<?> key) { phaseKey = key; } /** * Get the next phase, or {@code null} if none. * * @return the next phase, or {@code null} if there is none */ public Phase next() { final int ord = ordinal() + 1; final Phase[] phases = Phase.values(); return ord == phases.length ? null : phases[ord]; } /** * Get the attachment key of the {@code DeploymentUnit} attachment that represents the result value * of this phase. * * @return the key */ public AttachmentKey<?> getPhaseKey() { return phaseKey; } // STRUCTURE public static final int STRUCTURE_MOUNT = 0x0000; public static final int STRUCTURE_MANIFEST = 0x0100; public static final int STRUCTURE_OSGI_MANIFEST = 0x0200; public static final int STRUCTURE_RAR = 0x0300; public static final int STRUCTURE_WAR_DEPLOYMENT_INIT = 0x0400; public static final int STRUCTURE_WAR = 0x0500; public static final int STRUCTURE_EAR_DEPLOYMENT_INIT = 0x0600; public static final int STRUCTURE_EAR_APP_XML_PARSE = 0x0700; public static final int STRUCTURE_EAR_JBOSS_APP_XML_PARSE = 0x0800; public static final int STRUCTURE_EAR = 0x0900; public static final int STRUCTURE_DEPLOYMENT_MODULE_LOADER = 0x0A00; public static final int STRUCTURE_ANNOTATION_INDEX = 0x0B00; public static final int STRUCTURE_MANAGED_BEAN_SUB_DEPLOY_CHECK = 0x0C00; public static final int STRUCTURE_SAR_SUB_DEPLOY_CHECK = 0x0D00; public static final int STRUCTURE_SUB_DEPLOYMENT = 0x0E00; // PARSE public static final int PARSE_COMPOSITE_ANNOTATION_INDEX = 0x0100; public static final int PARSE_CLASS_PATH = 0x0200; public static final int PARSE_EXTENSION_LIST = 0x0300; public static final int PARSE_OSGI_BUNDLE_INFO = 0x0400; public static final int PARSE_OSGI_PROPERTIES = 0x0500; public static final int PARSE_WEB_DEPLOYMENT = 0x0600; public static final int PARSE_WEB_DEPLOYMENT_FRAGMENT = 0x0700; public static final int PARSE_JBOSS_WEB_DEPLOYMENT = 0x0800; public static final int PARSE_TLD_DEPLOYMENT = 0x0900; public static final int PARSE_RA_DEPLOYMENT = 0x0A00; public static final int PARSE_SERVICE_LOADER_DEPLOYMENT = 0x0A50; public static final int PARSE_SERVICE_DEPLOYMENT = 0x0B00; public static final int PARSE_MC_BEAN_DEPLOYMENT = 0x0C00; public static final int PARSE_IRON_JACAMAR_DEPLOYMENT = 0x0D00; public static final int PARSE_RESOURCE_ADAPTERS = 0x0E00; public static final int PARSE_DATA_SOURCES = 0x0F00; public static final int PARSE_ARQUILLIAN_RUNWITH = 0x1000; public static final int PARSE_MANAGED_BEAN_ANNOTATION = 0x1100; public static final int PARSE_BEAN_LIEFCYCLE_ANNOTATION = 0x1200; public static final int PARSE_BEAN_INTERCEPTOR_ANNOTATION = 0x1300; public static final int PARSE_BEAN_RESOURCE_INJECTION_ANNOTATION = 0x1400; public static final int PARSE_MANAGED_BEAN_RESOURCE_TARGET = 0x1500; // DEPENDENCIES public static final int DEPENDENCIES_MODULE = 0x100; public static final int DEPENDENCIES_DS = 0x200; public static final int DEPENDENCIES_RAR_CONFIG = 0x300; public static final int DEPENDENCIES_MANAGED_BEAN = 0x400; public static final int DEPENDENCIES_SAR_MODULE = 0x500; public static final int DEPENDENCIES_WAR_MODULE = 0x600; public static final int DEPENDENCIES_ARQUILLIAN = 0x700; public static final int DEPENDENCIES_CLASS_PATH = 0x800; public static final int DEPENDENCIES_EXTENSION_LIST = 0x900; // CONFIGURE_MODULE public static final int CONFIGURE_MODULE_WAR = 0x100; public static final int CONFIGURE_MODULE_SPEC = 0x200; // MODULARIZE public static final int MODULARIZE_DEPLOYMENT = 0x100; // POST_MODULE public static final int POST_MODULE_ANNOTATION_WAR = 0x100; public static final int POST_MODULE_ANNOTATION_ARQUILLIAN_JUNIT = 0x200; // INSTALL public static final int INSTALL_REFLECTION_INDEX = 0x0100; public static final int INSTALL_APP_CONTEXT = 0x0200; public static final int INSTALL_MODULE_CONTEXT = 0x0300; public static final int INSTALL_SERVICE_ACTIVATOR = 0x0400; public static final int INSTALL_OSGI_DEPLOYMENT = 0x0500; public static final int INSTALL_WAR_METADATA = 0x0600; public static final int INSTALL_RA_DEPLOYMENT = 0x0700; public static final int INSTALL_SERVICE_DEPLOYMENT = 0x0800; public static final int INSTALL_MC_BEAN_DEPLOYMENT = 0x0900; public static final int INSTALL_RA_XML_DEPLOYMENT = 0x0A00; public static final int INSTALL_DS_DEPLOYMENT = 0x0B00; public static final int INSTALL_MANAGED_BEAN_DEPLOYMENT = 0x0C00; public static final int INSTALL_BEAN_CONTAINER = 0x0D00; public static final int INSTALL_SERVLET_INIT_DEPLOYMENT = 0x0E00; public static final int INSTALL_WAR_DEPLOYMENT = 0x0F00; public static final int INSTALL_ARQUILLIAN_DEPLOYMENT = 0x1000; // CLEANUP public static final int CLEANUP_REFLECTION_INDEX = 0x100; }
Clean up numbering
server/src/main/java/org/jboss/as/server/deployment/Phase.java
Clean up numbering
Java
lgpl-2.1
7ee7051373be6b72ad604097d69eae57b7a08dc8
0
majenkotech/chipKIT32-MAX,ricklon/chipKIT32-MAX,chipKIT32/chipKIT32-MAX,tintin304/chipKIT32-MAX,chipKIT32/chipKIT32-MAX,majenkotech/chipKIT32-MAX,majenkotech/chipKIT32-MAX,EmbeddedMan/chipKIT32-MAX,chipKIT32/chipKIT32-MAX,majenkotech/chipKIT32-MAX,tintin304/chipKIT32-MAX,EmbeddedMan/chipKIT32-MAX,ricklon/chipKIT32-MAX,adamwolf/chipKIT32-MAX,adamwolf/chipKIT32-MAX,chipKIT32/chipKIT32-MAX,majenkotech/chipKIT32-MAX,EmbeddedMan/chipKIT32-MAX,adamwolf/chipKIT32-MAX,ricklon/chipKIT32-MAX,majenkotech/chipKIT32-MAX,adamwolf/chipKIT32-MAX,ricklon/chipKIT32-MAX,EmbeddedMan/chipKIT32-MAX,tintin304/chipKIT32-MAX,EmbeddedMan/chipKIT32-MAX,EmbeddedMan/chipKIT32-MAX,ricklon/chipKIT32-MAX,adamwolf/chipKIT32-MAX,adamwolf/chipKIT32-MAX,tintin304/chipKIT32-MAX,adamwolf/chipKIT32-MAX,EmbeddedMan/chipKIT32-MAX,ricklon/chipKIT32-MAX,ricklon/chipKIT32-MAX,tintin304/chipKIT32-MAX,chipKIT32/chipKIT32-MAX,tintin304/chipKIT32-MAX,chipKIT32/chipKIT32-MAX,chipKIT32/chipKIT32-MAX,tintin304/chipKIT32-MAX,majenkotech/chipKIT32-MAX
/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* Part of the Processing project - http://processing.org Copyright (c) 2004-05 Ben Fry and Casey Reas Copyright (c) 2001-04 Massachusetts Institute of Technology This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package processing.app; import processing.app.preproc.*; //import processing.core.*; import java.awt.*; import java.io.*; import java.util.*; import java.util.zip.*; import javax.swing.JOptionPane; import com.oroinc.text.regex.*; /** * Stores information about files in the current sketch */ public class Sketch { static File tempBuildFolder; Editor editor; /** * Name of sketch, which is the name of main file * (without .pde or .java extension) */ String name; /** * Name of 'main' file, used by load(), such as sketch_04040.pde */ String mainFilename; /** * true if any of the files have been modified. */ boolean modified; public File folder; public File dataFolder; public File codeFolder; static final int PDE = 0; static final int CPP = 1; static final int C = 2; static final int HEADER = 3; static final String flavorExtensionsReal[] = new String[] { ".pde", ".cpp", ".c", ".h" }; static final String flavorExtensionsShown[] = new String[] { "", ".cpp", ".c", ".h" }; public SketchCode current; int codeCount; SketchCode code[]; int hiddenCount; SketchCode hidden[]; Hashtable zipFileContents; // all these set each time build() is called String mainClassName; String classPath; String libraryPath; boolean externalRuntime; public Vector importedLibraries; // vec of Library objects /** * path is location of the main .pde file, because this is also * simplest to use when opening the file from the finder/explorer. */ public Sketch(Editor editor, String path) throws IOException { this.editor = editor; File mainFile = new File(path); //System.out.println("main file is " + mainFile); mainFilename = mainFile.getName(); //System.out.println("main file is " + mainFilename); // get the name of the sketch by chopping .pde or .java // off of the main file name if (mainFilename.endsWith(".pde")) { name = mainFilename.substring(0, mainFilename.length() - 4); } else if (mainFilename.endsWith(".c")) { name = mainFilename.substring(0, mainFilename.length() - 2); } else if (mainFilename.endsWith(".h")) { name = mainFilename.substring(0, mainFilename.length() - 2); } else if (mainFilename.endsWith(".cpp")) { name = mainFilename.substring(0, mainFilename.length() - 4); } // lib/build must exist when the application is started // it is added to the CLASSPATH by default, but if it doesn't // exist when the application is started, then java will remove // the entry from the CLASSPATH, causing Runner to fail. // /* tempBuildFolder = new File(TEMP_BUILD_PATH); if (!tempBuildFolder.exists()) { tempBuildFolder.mkdirs(); Base.showError("Required folder missing", "A required folder was missing from \n" + "from your installation of Processing.\n" + "It has now been replaced, please restart \n" + "the application to complete the repair.", null); } */ tempBuildFolder = Base.getBuildFolder(); //Base.addBuildFolderToClassPath(); folder = new File(new File(path).getParent()); //System.out.println("sketch dir is " + folder); load(); } /** * Build the list of files. * * Generally this is only done once, rather than * each time a change is made, because otherwise it gets to be * a nightmare to keep track of what files went where, because * not all the data will be saved to disk. * * This also gets called when the main sketch file is renamed, * because the sketch has to be reloaded from a different folder. * * Another exception is when an external editor is in use, * in which case the load happens each time "run" is hit. */ public void load() { codeFolder = new File(folder, "code"); dataFolder = new File(folder, "data"); // get list of files in the sketch folder String list[] = folder.list(); for (int i = 0; i < list.length; i++) { if (list[i].endsWith(".pde")) codeCount++; else if (list[i].endsWith(".c")) codeCount++; else if (list[i].endsWith(".h")) codeCount++; else if (list[i].endsWith(".cpp")) codeCount++; else if (list[i].endsWith(".pde.x")) hiddenCount++; else if (list[i].endsWith(".c.x")) hiddenCount++; else if (list[i].endsWith(".h.x")) hiddenCount++; else if (list[i].endsWith(".cpp.x")) hiddenCount++; } code = new SketchCode[codeCount]; hidden = new SketchCode[hiddenCount]; int codeCounter = 0; int hiddenCounter = 0; for (int i = 0; i < list.length; i++) { if (list[i].endsWith(".pde")) { code[codeCounter++] = new SketchCode(list[i].substring(0, list[i].length() - 4), new File(folder, list[i]), PDE); } else if (list[i].endsWith(".c")) { code[codeCounter++] = new SketchCode(list[i].substring(0, list[i].length() - 2), new File(folder, list[i]), C); } else if (list[i].endsWith(".h")) { code[codeCounter++] = new SketchCode(list[i].substring(0, list[i].length() - 2), new File(folder, list[i]), HEADER); } else if (list[i].endsWith(".cpp")) { code[codeCounter++] = new SketchCode(list[i].substring(0, list[i].length() - 4), new File(folder, list[i]), CPP); } else if (list[i].endsWith(".pde.x")) { hidden[hiddenCounter++] = new SketchCode(list[i].substring(0, list[i].length() - 6), new File(folder, list[i]), PDE); } else if (list[i].endsWith(".c.x")) { hidden[hiddenCounter++] = new SketchCode(list[i].substring(0, list[i].length() - 4), new File(folder, list[i]), C); } else if (list[i].endsWith(".h.x")) { hidden[hiddenCounter++] = new SketchCode(list[i].substring(0, list[i].length() - 4), new File(folder, list[i]), HEADER); } else if (list[i].endsWith(".cpp.x")) { hidden[hiddenCounter++] = new SketchCode(list[i].substring(0, list[i].length() - 6), new File(folder, list[i]), CPP); } } // remove any entries that didn't load properly int index = 0; while (index < codeCount) { if ((code[index] == null) || (code[index].program == null)) { for (int i = index+1; i < codeCount; i++) { code[i-1] = code[i]; } codeCount--; } else { index++; } } // move the main class to the first tab // start at 1, if it's at zero, don't bother for (int i = 1; i < codeCount; i++) { if (code[i].file.getName().equals(mainFilename)) { SketchCode temp = code[0]; code[0] = code[i]; code[i] = temp; break; } } // sort the entries at the top sortCode(); // set the main file to be the current tab setCurrent(0); } protected void insertCode(SketchCode newCode) { // make sure the user didn't hide the sketch folder ensureExistence(); // add file to the code/codeCount list, resort the list if (codeCount == code.length) { SketchCode temp[] = new SketchCode[codeCount+1]; System.arraycopy(code, 0, temp, 0, codeCount); code = temp; } code[codeCount++] = newCode; } protected void sortCode() { // cheap-ass sort of the rest of the files // it's a dumb, slow sort, but there shouldn't be more than ~5 files for (int i = 1; i < codeCount; i++) { int who = i; for (int j = i + 1; j < codeCount; j++) { if (code[j].name.compareTo(code[who].name) < 0) { who = j; // this guy is earlier in the alphabet } } if (who != i) { // swap with someone if changes made SketchCode temp = code[who]; code[who] = code[i]; code[i] = temp; } } } boolean renamingCode; public void newCode() { // make sure the user didn't hide the sketch folder ensureExistence(); // if read-only, give an error if (isReadOnly()) { // if the files are read-only, need to first do a "save as". Base.showMessage("Sketch is Read-Only", "Some files are marked \"read-only\", so you'll\n" + "need to re-save the sketch in another location,\n" + "and try again."); return; } renamingCode = false; editor.status.edit("Name for new file:", ""); } public void renameCode() { // make sure the user didn't hide the sketch folder ensureExistence(); // if read-only, give an error if (isReadOnly()) { // if the files are read-only, need to first do a "save as". Base.showMessage("Sketch is Read-Only", "Some files are marked \"read-only\", so you'll\n" + "need to re-save the sketch in another location,\n" + "and try again."); return; } // ask for new name of file (internal to window) // TODO maybe just popup a text area? renamingCode = true; String prompt = (current == code[0]) ? "New name for sketch:" : "New name for file:"; String oldName = current.name + flavorExtensionsShown[current.flavor]; editor.status.edit(prompt, oldName); } /** * This is called upon return from entering a new file name. * (that is, from either newCode or renameCode after the prompt) * This code is almost identical for both the newCode and renameCode * cases, so they're kept merged except for right in the middle * where they diverge. */ public void nameCode(String newName) { // make sure the user didn't hide the sketch folder ensureExistence(); // if renaming to the same thing as before, just ignore. // also ignoring case here, because i don't want to write // a bunch of special stuff for each platform // (osx is case insensitive but preserving, windows insensitive, // *nix is sensitive and preserving.. argh) if (renamingCode && newName.equalsIgnoreCase(current.name)) { // exit quietly for the 'rename' case. // if it's a 'new' then an error will occur down below return; } // don't allow blank names if (newName.trim().equals("")) { return; } if (newName.trim().equals(".c") || newName.trim().equals(".h") || newName.trim().equals(".pde") || newName.trim().equals(".cpp")) { return; } String newFilename = null; int newFlavor = 0; // separate into newName (no extension) and newFilename (with ext) // add .pde to file if it has no extension if (newName.endsWith(".pde")) { newFilename = newName; newName = newName.substring(0, newName.length() - 4); newFlavor = PDE; } else if (newName.endsWith(".c") || newName.endsWith(".cpp") || newName.endsWith(".h")) { // don't show this error if creating a new tab if (renamingCode && (code[0] == current)) { Base.showWarning("Problem with rename", "The main .pde file cannot be .c, .cpp, or .h file.\n" + "(It may be time for your to graduate to a\n" + "\"real\" programming environment)", null); return; } newFilename = newName; if(newName.endsWith(".c")) { newName = newName.substring(0, newName.length() - 2); newFlavor = C; } if(newName.endsWith(".h")) { newName = newName.substring(0, newName.length() - 2); newFlavor = HEADER; } else if(newName.endsWith(".cpp")) { newName = newName.substring(0, newName.length() - 4); newFlavor = CPP; } } else { newFilename = newName + ".pde"; newFlavor = PDE; } // dots are allowed for the .pde and .java, but not in the name // make sure the user didn't name things poo.time.pde // or something like that (nothing against poo time) if (newName.indexOf('.') != -1) { newName = Sketchbook.sanitizedName(newName); newFilename = newName + ((newFlavor == PDE) ? ".pde" : ".cpp"); } // create the new file, new SketchCode object and load it File newFile = new File(folder, newFilename); if (newFile.exists()) { // yay! users will try anything Base.showMessage("Nope", "A file named \"" + newFile + "\" already exists\n" + "in \"" + folder.getAbsolutePath() + "\""); return; } File newFileHidden = new File(folder, newFilename + ".x"); if (newFileHidden.exists()) { // don't let them get away with it if they try to create something // with the same name as something hidden Base.showMessage("No Way", "A hidden tab with the same name already exists.\n" + "Use \"Unhide\" to bring it back."); return; } if (renamingCode) { if (current == code[0]) { // get the new folder name/location File newFolder = new File(folder.getParentFile(), newName); if (newFolder.exists()) { Base.showWarning("Cannot Rename", "Sorry, a sketch (or folder) named " + "\"" + newName + "\" already exists.", null); return; } // unfortunately this can't be a "save as" because that // only copies the sketch files and the data folder // however this *will* first save the sketch, then rename // first get the contents of the editor text area if (current.modified) { current.program = editor.getText(); try { // save this new SketchCode current.save(); } catch (Exception e) { Base.showWarning("Error", "Could not rename the sketch. (0)", e); return; } } if (!current.file.renameTo(newFile)) { Base.showWarning("Error", "Could not rename \"" + current.file.getName() + "\" to \"" + newFile.getName() + "\"", null); return; } // save each of the other tabs because this is gonna be re-opened try { for (int i = 1; i < codeCount; i++) { //if (code[i].modified) code[i].save(); code[i].save(); } } catch (Exception e) { Base.showWarning("Error", "Could not rename the sketch. (1)", e); return; } // now rename the sketch folder and re-open boolean success = folder.renameTo(newFolder); if (!success) { Base.showWarning("Error", "Could not rename the sketch. (2)", null); return; } // if successful, set base properties for the sketch File mainFile = new File(newFolder, newName + ".pde"); mainFilename = mainFile.getAbsolutePath(); // having saved everything and renamed the folder and the main .pde, // use the editor to re-open the sketch to re-init state // (unfortunately this will kill positions for carets etc) editor.handleOpenUnchecked(mainFilename); /* // backtrack and don't rename the sketch folder success = newFolder.renameTo(folder); if (!success) { String msg = "Started renaming sketch and then ran into\n" + "nasty trouble. Try to salvage with Copy & Paste\n" + "or attempt a \"Save As\" to see if that works."; Base.showWarning("Serious Error", msg, null); } return; } */ /* // set the sketch name... used by the pde and whatnot. // the name is only set in the sketch constructor, // so it's important here name = newName; code[0].name = newName; code[0].file = mainFile; code[0].program = editor.getText(); code[0].save(); folder = newFolder; // get the changes into the sketchbook menu editor.sketchbook.rebuildMenus(); // reload the sketch load(); */ } else { if (!current.file.renameTo(newFile)) { Base.showWarning("Error", "Could not rename \"" + current.file.getName() + "\" to \"" + newFile.getName() + "\"", null); return; } // just reopen the class itself current.name = newName; current.file = newFile; current.flavor = newFlavor; } } else { // creating a new file try { newFile.createNewFile(); // TODO returns a boolean } catch (IOException e) { Base.showWarning("Error", "Could not create the file \"" + newFile + "\"\n" + "in \"" + folder.getAbsolutePath() + "\"", e); return; } SketchCode newCode = new SketchCode(newName, newFile, newFlavor); insertCode(newCode); } // sort the entries sortCode(); // set the new guy as current setCurrent(newName + flavorExtensionsShown[newFlavor]); // update the tabs //editor.header.repaint(); editor.header.rebuild(); // force the update on the mac? Toolkit.getDefaultToolkit().sync(); //editor.header.getToolkit().sync(); } /** * Remove a piece of code from the sketch and from the disk. */ public void deleteCode() { // make sure the user didn't hide the sketch folder ensureExistence(); // if read-only, give an error if (isReadOnly()) { // if the files are read-only, need to first do a "save as". Base.showMessage("Sketch is Read-Only", "Some files are marked \"read-only\", so you'll\n" + "need to re-save the sketch in another location,\n" + "and try again."); return; } // confirm deletion with user, yes/no Object[] options = { "OK", "Cancel" }; String prompt = (current == code[0]) ? "Are you sure you want to delete this sketch?" : "Are you sure you want to delete \"" + current.name + flavorExtensionsShown[current.flavor] + "\"?"; int result = JOptionPane.showOptionDialog(editor, prompt, "Delete", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (result == JOptionPane.YES_OPTION) { if (current == code[0]) { // need to unset all the modified flags, otherwise tries // to do a save on the handleNew() // delete the entire sketch Base.removeDir(folder); // get the changes into the sketchbook menu //sketchbook.rebuildMenus(); // make a new sketch, and i think this will rebuild the sketch menu editor.handleNewUnchecked(); } else { // delete the file if (!current.file.delete()) { Base.showMessage("Couldn't do it", "Could not delete \"" + current.name + "\"."); return; } // remove code from the list removeCode(current); // just set current tab to the main tab setCurrent(0); // update the tabs editor.header.repaint(); } } } protected void removeCode(SketchCode which) { // remove it from the internal list of files // resort internal list of files for (int i = 0; i < codeCount; i++) { if (code[i] == which) { for (int j = i; j < codeCount-1; j++) { code[j] = code[j+1]; } codeCount--; return; } } System.err.println("removeCode: internal error.. could not find code"); } public void hideCode() { // make sure the user didn't hide the sketch folder ensureExistence(); // if read-only, give an error if (isReadOnly()) { // if the files are read-only, need to first do a "save as". Base.showMessage("Sketch is Read-Only", "Some files are marked \"read-only\", so you'll\n" + "need to re-save the sketch in another location,\n" + "and try again."); return; } // don't allow hide of the main code // TODO maybe gray out the menu on setCurrent(0) if (current == code[0]) { Base.showMessage("Can't do that", "You cannot hide the main " + ".pde file from a sketch\n"); return; } // rename the file File newFile = new File(current.file.getAbsolutePath() + ".x"); if (!current.file.renameTo(newFile)) { Base.showWarning("Error", "Could not hide " + "\"" + current.file.getName() + "\".", null); return; } current.file = newFile; // move it to the hidden list if (hiddenCount == hidden.length) { SketchCode temp[] = new SketchCode[hiddenCount+1]; System.arraycopy(hidden, 0, temp, 0, hiddenCount); hidden = temp; } hidden[hiddenCount++] = current; // remove it from the main list removeCode(current); // update the tabs setCurrent(0); editor.header.repaint(); } public void unhideCode(String what) { SketchCode unhideCode = null; String name = what.substring(0, (what.indexOf(".") == -1 ? what.length() : what.indexOf("."))); String extension = what.indexOf(".") == -1 ? "" : what.substring(what.indexOf(".")); for (int i = 0; i < hiddenCount; i++) { if (hidden[i].name.equals(name) && Sketch.flavorExtensionsShown[hidden[i].flavor].equals(extension)) { //unhideIndex = i; unhideCode = hidden[i]; // remove from the 'hidden' list for (int j = i; j < hiddenCount-1; j++) { hidden[j] = hidden[j+1]; } hiddenCount--; break; } } //if (unhideIndex == -1) { if (unhideCode == null) { System.err.println("internal error: could find " + what + " to unhide."); return; } if (!unhideCode.file.exists()) { Base.showMessage("Can't unhide", "The file \"" + what + "\" no longer exists."); //System.out.println(unhideCode.file); return; } String unhidePath = unhideCode.file.getAbsolutePath(); File unhideFile = new File(unhidePath.substring(0, unhidePath.length() - 2)); if (!unhideCode.file.renameTo(unhideFile)) { Base.showMessage("Can't unhide", "The file \"" + what + "\" could not be" + "renamed and unhidden."); return; } unhideCode.file = unhideFile; insertCode(unhideCode); sortCode(); setCurrent(unhideCode.name); editor.header.repaint(); } /** * Sets the modified value for the code in the frontmost tab. */ public void setModified(boolean state) { current.modified = state; calcModified(); } public void calcModified() { modified = false; for (int i = 0; i < codeCount; i++) { if (code[i].modified) { modified = true; break; } } editor.header.repaint(); } /** * Save all code in the current sketch. */ public boolean save() throws IOException { // make sure the user didn't hide the sketch folder ensureExistence(); // first get the contents of the editor text area if (current.modified) { current.program = editor.getText(); } // don't do anything if not actually modified //if (!modified) return false; if (isReadOnly()) { // if the files are read-only, need to first do a "save as". Base.showMessage("Sketch is read-only", "Some files are marked \"read-only\", so you'll\n" + "need to re-save this sketch to another location."); // if the user cancels, give up on the save() if (!saveAs()) return false; } for (int i = 0; i < codeCount; i++) { if (code[i].modified) code[i].save(); } calcModified(); return true; } /** * Handles 'Save As' for a sketch. * <P> * This basically just duplicates the current sketch folder to * a new location, and then calls 'Save'. (needs to take the current * state of the open files and save them to the new folder.. * but not save over the old versions for the old sketch..) * <P> * Also removes the previously-generated .class and .jar files, * because they can cause trouble. */ public boolean saveAs() throws IOException { // get new name for folder FileDialog fd = new FileDialog(editor, "Save sketch folder as...", FileDialog.SAVE); if (isReadOnly()) { // default to the sketchbook folder fd.setDirectory(Preferences.get("sketchbook.path")); } else { // default to the parent folder of where this was fd.setDirectory(folder.getParent()); } fd.setFile(folder.getName()); fd.show(); String newParentDir = fd.getDirectory(); String newName = fd.getFile(); // user cancelled selection if (newName == null) return false; newName = Sketchbook.sanitizeName(newName); // make sure there doesn't exist a tab with that name already // (but allow it if it's just the main tab resaving itself.. oops) File codeAlready = new File(folder, newName + ".pde"); if (codeAlready.exists() && (!newName.equals(name))) { Base.showMessage("Nope", "You can't save the sketch as \"" + newName + "\"\n" + "because the sketch already has a tab with that name."); return false; } // make sure there doesn't exist a tab with that name already File hiddenAlready = new File(folder, newName + ".pde.x"); if (hiddenAlready.exists()) { Base.showMessage("Nope", "You can't save the sketch as \"" + newName + "\"\n" + "because the sketch already has a " + "hidden tab with that name."); return false; } // new sketch folder File newFolder = new File(newParentDir, newName); // make sure the paths aren't the same if (newFolder.equals(folder)) { Base.showWarning("You can't fool me", "The new sketch name and location are the same as\n" + "the old. I ain't not doin nuthin' not now.", null); return false; } // check to see if the user is trying to save this sketch // inside the same sketch try { String newPath = newFolder.getCanonicalPath() + File.separator; String oldPath = folder.getCanonicalPath() + File.separator; if (newPath.indexOf(oldPath) == 0) { Base.showWarning("How very Borges of you", "You cannot save the sketch into a folder\n" + "inside itself. This would go on forever.", null); return false; } } catch (IOException e) { } // if the new folder already exists, then need to remove // its contents before copying everything over // (user will have already been warned) if (newFolder.exists()) { Base.removeDir(newFolder); } // in fact, you can't do this on windows because the file dialog // will instead put you inside the folder, but it happens on osx a lot. // now make a fresh copy of the folder newFolder.mkdirs(); // grab the contents of the current tab before saving // first get the contents of the editor text area if (current.modified) { current.program = editor.getText(); } // save the other tabs to their new location for (int i = 1; i < codeCount; i++) { File newFile = new File(newFolder, code[i].file.getName()); code[i].saveAs(newFile); } // save the hidden code to its new location for (int i = 0; i < hiddenCount; i++) { File newFile = new File(newFolder, hidden[i].file.getName()); hidden[i].saveAs(newFile); } // re-copy the data folder (this may take a while.. add progress bar?) if (dataFolder.exists()) { File newDataFolder = new File(newFolder, "data"); Base.copyDir(dataFolder, newDataFolder); } // re-copy the code folder if (codeFolder.exists()) { File newCodeFolder = new File(newFolder, "code"); Base.copyDir(codeFolder, newCodeFolder); } // save the main tab with its new name File newFile = new File(newFolder, newName + ".pde"); code[0].saveAs(newFile); editor.handleOpenUnchecked(newFile.getPath()); /* // copy the entire contents of the sketch folder Base.copyDir(folder, newFolder); // change the references to the dir location in SketchCode files for (int i = 0; i < codeCount; i++) { code[i].file = new File(newFolder, code[i].file.getName()); } for (int i = 0; i < hiddenCount; i++) { hidden[i].file = new File(newFolder, hidden[i].file.getName()); } // remove the old sketch file from the new dir code[0].file.delete(); // name for the new main .pde file code[0].file = new File(newFolder, newName + ".pde"); code[0].name = newName; // write the contents to the renamed file // (this may be resaved if the code is modified) code[0].modified = true; //code[0].save(); //System.out.println("modified is " + modified); // change the other paths String oldName = name; name = newName; File oldFolder = folder; folder = newFolder; dataFolder = new File(folder, "data"); codeFolder = new File(folder, "code"); // remove the 'applet', 'application', 'library' folders // from the copied version. // otherwise their .class and .jar files can cause conflicts. Base.removeDir(new File(folder, "applet")); Base.removeDir(new File(folder, "application")); //Base.removeDir(new File(folder, "library")); // do a "save" // this will take care of the unsaved changes in each of the tabs save(); // get the changes into the sketchbook menu //sketchbook.rebuildMenu(); // done inside Editor instead // update the tabs for the name change editor.header.repaint(); */ // let Editor know that the save was successful return true; } /** * Prompt the user for a new file to the sketch. * This could be .class or .jar files for the code folder, * .pde or .java files for the project, * or .dll, .jnilib, or .so files for the code folder */ public void addFile() { // make sure the user didn't hide the sketch folder ensureExistence(); // if read-only, give an error if (isReadOnly()) { // if the files are read-only, need to first do a "save as". Base.showMessage("Sketch is Read-Only", "Some files are marked \"read-only\", so you'll\n" + "need to re-save the sketch in another location,\n" + "and try again."); return; } // get a dialog, select a file to add to the sketch String prompt = "Select an image or other data file to copy to your sketch"; //FileDialog fd = new FileDialog(new Frame(), prompt, FileDialog.LOAD); FileDialog fd = new FileDialog(editor, prompt, FileDialog.LOAD); fd.show(); String directory = fd.getDirectory(); String filename = fd.getFile(); if (filename == null) return; // copy the file into the folder. if people would rather // it move instead of copy, they can do it by hand File sourceFile = new File(directory, filename); // now do the work of adding the file addFile(sourceFile); } /** * Add a file to the sketch. * <p/> * .pde or .java files will be added to the sketch folder. <br/> * .jar, .class, .dll, .jnilib, and .so files will all * be added to the "code" folder. <br/> * All other files will be added to the "data" folder. * <p/> * If they don't exist already, the "code" or "data" folder * will be created. * <p/> * @return true if successful. */ public boolean addFile(File sourceFile) { String filename = sourceFile.getName(); File destFile = null; boolean addingCode = false; // if the file appears to be code related, drop it // into the code folder, instead of the data folder if (filename.toLowerCase().endsWith(".o") /*|| filename.toLowerCase().endsWith(".jar") || filename.toLowerCase().endsWith(".dll") || filename.toLowerCase().endsWith(".jnilib") || filename.toLowerCase().endsWith(".so") */ ) { //File codeFolder = new File(this.folder, "code"); if (!codeFolder.exists()) codeFolder.mkdirs(); destFile = new File(codeFolder, filename); } else if (filename.toLowerCase().endsWith(".pde") || filename.toLowerCase().endsWith(".c") || filename.toLowerCase().endsWith(".h") || filename.toLowerCase().endsWith(".cpp")) { destFile = new File(this.folder, filename); addingCode = true; } else { //File dataFolder = new File(this.folder, "data"); if (!dataFolder.exists()) dataFolder.mkdirs(); destFile = new File(dataFolder, filename); } // make sure they aren't the same file if (!addingCode && sourceFile.equals(destFile)) { Base.showWarning("You can't fool me", "This file has already been copied to the\n" + "location where you're trying to add it.\n" + "I ain't not doin nuthin'.", null); return false; } // in case the user is "adding" the code in an attempt // to update the sketch's tabs if (!sourceFile.equals(destFile)) { try { Base.copyFile(sourceFile, destFile); } catch (IOException e) { Base.showWarning("Error adding file", "Could not add '" + filename + "' to the sketch.", e); return false; } } // make the tabs update after this guy is added if (addingCode) { String newName = destFile.getName(); int newFlavor = -1; if (newName.toLowerCase().endsWith(".pde")) { newName = newName.substring(0, newName.length() - 4); newFlavor = PDE; } else if (newName.toLowerCase().endsWith(".c")) { newName = newName.substring(0, newName.length() - 2); newFlavor = C; } else if (newName.toLowerCase().endsWith(".h")) { newName = newName.substring(0, newName.length() - 2); newFlavor = HEADER; } else { // ".cpp" newName = newName.substring(0, newName.length() - 4); newFlavor = CPP; } // see also "nameCode" for identical situation SketchCode newCode = new SketchCode(newName, destFile, newFlavor); insertCode(newCode); sortCode(); setCurrent(newName); editor.header.repaint(); } return true; } public void importLibrary(String jarPath) { //System.out.println(jarPath); // make sure the user didn't hide the sketch folder ensureExistence(); //String list[] = Compiler.packageListFromClassPath(jarPath); FileFilter onlyHFiles = new FileFilter() { public boolean accept(File file) { return (file.getName()).endsWith(".h"); } }; File list[] = new File(jarPath).listFiles(onlyHFiles); // import statements into the main sketch file (code[0]) // if the current code is a .java file, insert into current if (current.flavor == PDE) { setCurrent(0); } // could also scan the text in the file to see if each import // statement is already in there, but if the user has the import // commented out, then this will be a problem. StringBuffer buffer = new StringBuffer(); for (int i = 0; i < list.length; i++) { buffer.append("#include <"); buffer.append(list[i].getName()); buffer.append(">\n"); } buffer.append('\n'); buffer.append(editor.getText()); editor.setText(buffer.toString(), 0, 0); // scroll to start setModified(true); } /** * Change what file is currently being edited. * <OL> * <LI> store the String for the text of the current file. * <LI> retrieve the String for the text of the new file. * <LI> change the text that's visible in the text area * </OL> */ public void setCurrent(int which) { if (current == code[which]) { //System.out.println("already current, ignoring"); return; } // get the text currently being edited if (current != null) { current.program = editor.getText(); current.selectionStart = editor.textarea.getSelectionStart(); current.selectionStop = editor.textarea.getSelectionEnd(); current.scrollPosition = editor.textarea.getScrollPosition(); } current = code[which]; editor.setCode(current); //editor.setDocument(current.document, // current.selectionStart, current.selectionStop, // current.scrollPosition, current.undo); // set to the text for this file // 'true' means to wipe out the undo buffer // (so they don't undo back to the other file.. whups!) /* editor.setText(current.program, current.selectionStart, current.selectionStop, current.undo); */ // set stored caret and scroll positions //editor.textarea.setScrollPosition(current.scrollPosition); //editor.textarea.select(current.selectionStart, current.selectionStop); //editor.textarea.setSelectionStart(current.selectionStart); //editor.textarea.setSelectionEnd(current.selectionStop); editor.header.rebuild(); } /** * Internal helper function to set the current tab * based on a name (used by codeNew and codeRename). */ protected void setCurrent(String findName) { SketchCode unhideCode = null; String name = findName.substring(0, (findName.indexOf(".") == -1 ? findName.length() : findName.indexOf("."))); String extension = findName.indexOf(".") == -1 ? "" : findName.substring(findName.indexOf(".")); for (int i = 0; i < codeCount; i++) { if (name.equals(code[i].name) && Sketch.flavorExtensionsShown[code[i].flavor].equals(extension)) { setCurrent(i); return; } } } /** * Cleanup temporary files used during a build/run. */ protected void cleanup() { // if the java runtime is holding onto any files in the build dir, we // won't be able to delete them, so we need to force a gc here System.gc(); // note that we can't remove the builddir itself, otherwise // the next time we start up, internal runs using Runner won't // work because the build dir won't exist at startup, so the classloader // will ignore the fact that that dir is in the CLASSPATH in run.sh Base.removeDescendants(tempBuildFolder); } /** * Preprocess, Compile, and Run the current code. * <P> * There are three main parts to this process: * <PRE> * (0. if not java, then use another 'engine'.. i.e. python) * * 1. do the p5 language preprocessing * this creates a working .java file in a specific location * better yet, just takes a chunk of java code and returns a * new/better string editor can take care of saving this to a * file location * * 2. compile the code from that location * catching errors along the way * placing it in a ready classpath, or .. ? * * 3. run the code * needs to communicate location for window * and maybe setup presentation space as well * run externally if a code folder exists, * or if more than one file is in the project * * X. afterwards, some of these steps need a cleanup function * </PRE> */ public boolean handleRun(Target target) throws RunnerException { // make sure the user didn't hide the sketch folder ensureExistence(); current.program = editor.getText(); // TODO record history here //current.history.record(program, SketchHistory.RUN); // if an external editor is being used, need to grab the // latest version of the code from the file. if (Preferences.getBoolean("editor.external")) { // history gets screwed by the open.. //String historySaved = history.lastRecorded; //handleOpen(sketch); //history.lastRecorded = historySaved; // nuke previous files and settings, just get things loaded load(); } // in case there were any boogers left behind // do this here instead of after exiting, since the exit // can happen so many different ways.. and this will be // better connected to the dataFolder stuff below. cleanup(); // make up a temporary class name to suggest. // name will only be used if the code is not in ADVANCED mode. String suggestedClassName = ("Temporary_" + String.valueOf((int) (Math.random() * 10000)) + "_" + String.valueOf((int) (Math.random() * 10000))); // handle preprocessing the main file's code //mainClassName = build(TEMP_BUILD_PATH, suggestedClassName); mainClassName = build(target, tempBuildFolder.getAbsolutePath(), suggestedClassName); size(tempBuildFolder.getAbsolutePath(), name); // externalPaths is magically set by build() if (!externalRuntime) { // only if not running externally already // copy contents of data dir into lib/build if (dataFolder.exists()) { // just drop the files in the build folder (pre-68) //Base.copyDir(dataDir, buildDir); // drop the files into a 'data' subfolder of the build dir try { Base.copyDir(dataFolder, new File(tempBuildFolder, "data")); } catch (IOException e) { e.printStackTrace(); throw new RunnerException("Problem copying files from data folder"); } } } return (mainClassName != null); } /** * Build all the code for this sketch. * * In an advanced program, the returned classname could be different, * which is why the className is set based on the return value. * A compilation error will burp up a RunnerException. * * @return null if compilation failed, main class name if not */ protected String build(Target target, String buildPath, String suggestedClassName) throws RunnerException { // build unbuilt buildable libraries // completely independent from sketch, so run all the time editor.prepareLibraries(); // make sure the user didn't hide the sketch folder ensureExistence(); String codeFolderPackages[] = null; String javaClassPath = System.getProperty("java.class.path"); // remove quotes if any.. this is an annoying thing on windows if (javaClassPath.startsWith("\"") && javaClassPath.endsWith("\"")) { javaClassPath = javaClassPath.substring(1, javaClassPath.length() - 1); } classPath = buildPath + File.pathSeparator + Sketchbook.librariesClassPath + File.pathSeparator + javaClassPath; //System.out.println("cp = " + classPath); // figure out the contents of the code folder to see if there // are files that need to be added to the imports //File codeFolder = new File(folder, "code"); if (codeFolder.exists()) { externalRuntime = true; //classPath += File.pathSeparator + //Compiler.contentsToClassPath(codeFolder); classPath = Compiler.contentsToClassPath(codeFolder) + File.pathSeparator + classPath; //codeFolderPackages = Compiler.packageListFromClassPath(classPath); //codeFolderPackages = Compiler.packageListFromClassPath(codeFolder); libraryPath = codeFolder.getAbsolutePath(); // get a list of .jar files in the "code" folder // (class files in subfolders should also be picked up) String codeFolderClassPath = Compiler.contentsToClassPath(codeFolder); // get list of packages found in those jars // codeFolderPackages = // Compiler.packageListFromClassPath(codeFolderClassPath); //PApplet.println(libraryPath); //PApplet.println("packages:"); //PApplet.printarr(codeFolderPackages); } else { // since using the special classloader, // run externally whenever there are extra classes defined //externalRuntime = (codeCount > 1); // this no longer appears to be true.. so scrapping for 0088 // check to see if multiple files that include a .java file externalRuntime = false; for (int i = 0; i < codeCount; i++) { if (code[i].flavor == C || code[i].flavor == CPP) { externalRuntime = true; break; } } //codeFolderPackages = null; libraryPath = ""; } // if 'data' folder is large, set to external runtime if (dataFolder.exists() && Base.calcFolderSize(dataFolder) > 768 * 1024) { // if > 768k externalRuntime = true; } // 1. concatenate all .pde files to the 'main' pde // store line number for starting point of each code bit StringBuffer bigCode = new StringBuffer(code[0].program); int bigCount = countLines(code[0].program); for (int i = 1; i < codeCount; i++) { if (code[i].flavor == PDE) { code[i].preprocOffset = ++bigCount; bigCode.append('\n'); bigCode.append(code[i].program); bigCount += countLines(code[i].program); code[i].preprocName = null; // don't compile me } } // since using the special classloader, // run externally whenever there are extra classes defined /* if ((bigCode.indexOf(" class ") != -1) || (bigCode.indexOf("\nclass ") != -1)) { externalRuntime = true; } */ // if running in opengl mode, this is gonna be external //if (Preferences.get("renderer").equals("opengl")) { //externalRuntime = true; //} // 2. run preproc on that code using the sugg class name // to create a single .java file and write to buildpath String primaryClassName = null; PdePreprocessor preprocessor = new PdePreprocessor(); try { // if (i != 0) preproc will fail if a pde file is not // java mode, since that's required String className = preprocessor.write(bigCode.toString(), buildPath, suggestedClassName, codeFolderPackages); if (className == null) { throw new RunnerException("Could not find main class"); // this situation might be perfectly fine, // (i.e. if the file is empty) //System.out.println("No class found in " + code[i].name); //System.out.println("(any code in that file will be ignored)"); //System.out.println(); } else { code[0].preprocName = className + ".cpp"; } // store this for the compiler and the runtime primaryClassName = className; //System.out.println("primary class " + primaryClassName); // check if the 'main' file is in java mode if ((PdePreprocessor.programType == PdePreprocessor.JAVA) || (preprocessor.extraImports.length != 0)) { externalRuntime = true; // we in advanced mode now, boy } } catch (antlr.RecognitionException re) { // this even returns a column int errorFile = 0; int errorLine = re.getLine() - 1; for (int i = 1; i < codeCount; i++) { if ((code[i].flavor == PDE) && (code[i].preprocOffset < errorLine)) { errorFile = i; } } errorLine -= code[errorFile].preprocOffset; errorLine -= preprocessor.prototypeCount; errorLine -= preprocessor.headerCount; throw new RunnerException(re.getMessage(), errorFile, errorLine, re.getColumn()); } catch (antlr.TokenStreamRecognitionException tsre) { // while this seems to store line and column internally, // there doesn't seem to be a method to grab it.. // so instead it's done using a regexp PatternMatcher matcher = new Perl5Matcher(); PatternCompiler compiler = new Perl5Compiler(); // line 3:1: unexpected char: 0xA0 String mess = "^line (\\d+):(\\d+):\\s"; Pattern pattern = null; try { pattern = compiler.compile(mess); } catch (MalformedPatternException e) { Base.showWarning("Internal Problem", "An internal error occurred while trying\n" + "to compile the sketch. Please report\n" + "this online at " + "https://developer.berlios.de/bugs/?group_id=3590", e); } PatternMatcherInput input = new PatternMatcherInput(tsre.toString()); if (matcher.contains(input, pattern)) { MatchResult result = matcher.getMatch(); int errorLine = Integer.parseInt(result.group(1).toString()) - 1; int errorColumn = Integer.parseInt(result.group(2).toString()); int errorFile = 0; for (int i = 1; i < codeCount; i++) { if ((code[i].flavor == PDE) && (code[i].preprocOffset < errorLine)) { errorFile = i; } } errorLine -= code[errorFile].preprocOffset; errorLine -= preprocessor.prototypeCount; errorLine -= preprocessor.headerCount; throw new RunnerException(tsre.getMessage(), errorFile, errorLine, errorColumn); } else { // this is bad, defaults to the main class.. hrm. throw new RunnerException(tsre.toString(), 0, -1, -1); } } catch (RunnerException pe) { // RunnerExceptions are caught here and re-thrown, so that they don't // get lost in the more general "Exception" handler below. throw pe; } catch (Exception ex) { // TODO better method for handling this? System.err.println("Uncaught exception type:" + ex.getClass()); ex.printStackTrace(); throw new RunnerException(ex.toString()); } // grab the imports from the code just preproc'd importedLibraries = new Vector(); String imports[] = preprocessor.extraImports; try { LibraryManager libraryManager = new LibraryManager(); Collection libraries = libraryManager.getAll(); for (Iterator i = libraries.iterator(); i.hasNext(); ) { Library library = (Library) i.next(); File[] headerFiles = library.getHeaderFiles(); for (int j = 0; j < headerFiles.length; j++) for (int k = 0; k < imports.length; k++) if (headerFiles[j].getName().equals(imports[k]) && !importedLibraries.contains(library)) { importedLibraries.add(library); //System.out.println("Adding library " + library.getName()); } } } catch (IOException e) { System.err.println("Error finding libraries:"); e.printStackTrace(); throw new RunnerException(e.getMessage()); } //for (int i = 0; i < imports.length; i++) { /* // remove things up to the last dot String entry = imports[i].substring(0, imports[i].lastIndexOf('.')); //System.out.println("found package " + entry); File libFolder = (File) Sketchbook.importToLibraryTable.get(entry); if (libFolder == null) { //throw new RunnerException("Could not find library for " + entry); continue; } importedLibraries.add(libFolder); libraryPath += File.pathSeparator + libFolder.getAbsolutePath(); */ /* String list[] = libFolder.list(); if (list != null) { for (int j = 0; j < list.length; j++) { // this might have a dll/jnilib/so packed, // so add it to the library path if (list[j].toLowerCase().endsWith(".jar")) { libraryPath += File.pathSeparator + libFolder.getAbsolutePath() + File.separator + list[j]; } } } */ //} // 3. then loop over the code[] and save each .java file for (int i = 0; i < codeCount; i++) { if (code[i].flavor == CPP || code[i].flavor == C || code[i].flavor == HEADER) { // no pre-processing services necessary for java files // just write the the contents of 'program' to a .java file // into the build directory. uses byte stream and reader/writer // shtuff so that unicode bunk is properly handled String filename = code[i].name + flavorExtensionsReal[code[i].flavor]; try { Base.saveFile(code[i].program, new File(buildPath, filename)); } catch (IOException e) { e.printStackTrace(); throw new RunnerException("Problem moving " + filename + " to the build folder"); } code[i].preprocName = filename; } } // compile the program. errors will happen as a RunnerException // that will bubble up to whomever called build(). // // note: this has been changed to catch build exceptions, adjust // line number for number of included prototypes, and rethrow Compiler compiler = new Compiler(); boolean success; try { success = compiler.compile(this, buildPath, target); } catch (RunnerException re) { throw new RunnerException(re.getMessage(), re.file, re.line - preprocessor.prototypeCount - preprocessor.headerCount, re.column); } catch (Exception ex) { // TODO better method for handling this? throw new RunnerException(ex.toString()); } //System.out.println("success = " + success + " ... " + primaryClassName); return success ? primaryClassName : null; } protected void size(String buildPath, String suggestedClassName) throws RunnerException { long size = 0; long maxsize = Preferences.getInteger("upload.maximum_size"); if (Preferences.get("build.mcu").equals("atmega168")) maxsize *= 2; Sizer sizer = new Sizer(buildPath, suggestedClassName); try { size = sizer.computeSize(); System.out.println("Binary sketch size: " + size + " bytes (of a " + maxsize + " byte maximum)"); } catch (RunnerException e) { System.err.println("Couldn't determine program size: " + e.getMessage()); } if (size > maxsize) throw new RunnerException( "Sketch too big; try deleting code, removing floats, or see " + "http://www.arduino.cc/en/Main/FAQ for more advice."); } protected String upload(String buildPath, String suggestedClassName) throws RunnerException { // download the program // Uploader uploader = new Uploader(); // macos9 now officially broken.. see PdeCompilerJavac //PdeCompiler compiler = // ((PdeBase.platform == PdeBase.MACOS9) ? // new PdeCompilerJavac(buildPath, className, this) : // new PdeCompiler(buildPath, className, this)); // run the compiler, and funnel errors to the leechErr // which is a wrapped around // (this will catch and parse errors during compilation // the messageStream will call message() for 'compiler') //MessageStream messageStream = new MessageStream(downloader); //PrintStream leechErr = new PrintStream(messageStream); //boolean result = compiler.compileJava(leechErr); //return compiler.compileJava(leechErr); boolean success = uploader.uploadUsingPreferences(buildPath, suggestedClassName); return success ? suggestedClassName : null; } protected int countLines(String what) { char c[] = what.toCharArray(); int count = 0; for (int i = 0; i < c.length; i++) { if (c[i] == '\n') count++; } return count; } /** * Initiate export to applet. * <PRE> * +-------------------------------------------------------+ * + + * + Export to: [ Applet (for the web) + ] [ OK ] + * + + * + > Advanced + * + + * + - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + Version: [ Java 1.1 + ] + * + + * + Recommended version of Java when exporting applets. + * + - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + Version: [ Java 1.3 + ] + * + + * + Java 1.3 is not recommended for applets, + * + unless you are using features that require it. + * + Using a version of Java other than 1.1 will require + * + your Windows users to install the Java Plug-In, + * + and your Macintosh users to be running OS X. + * + - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + Version: [ Java 1.4 + ] + * + + * + identical message as 1.3 above... + * + + * +-------------------------------------------------------+ * </PRE> */ public boolean exportApplet(Target target) throws RunnerException { // make sure the user didn't hide the sketch folder ensureExistence(); current.program = editor.getText(); zipFileContents = new Hashtable(); // nuke the old applet folder because it can cause trouble File appletFolder = new File(folder, "applet"); Base.removeDir(appletFolder); appletFolder.mkdirs(); // build the sketch String foundName = build(target, appletFolder.getPath(), name); size(appletFolder.getPath(), name); foundName = upload(appletFolder.getPath(), name); // (already reported) error during export, exit this function if (foundName == null) return false; // if name != exportSketchName, then that's weirdness // BUG unfortunately, that can also be a bug in the preproc :( if (!name.equals(foundName)) { Base.showWarning("Error during export", "Sketch name is " + name + " but the sketch\n" + "name in the code was " + foundName, null); return false; } /* int wide = PApplet.DEFAULT_WIDTH; int high = PApplet.DEFAULT_HEIGHT; PatternMatcher matcher = new Perl5Matcher(); PatternCompiler compiler = new Perl5Compiler(); // this matches against any uses of the size() function, // whether they contain numbers of variables or whatever. // this way, no warning is shown if size() isn't actually // used in the applet, which is the case especially for // beginners that are cutting/pasting from the reference. // modified for 83 to match size(XXX, ddd so that it'll // properly handle size(200, 200) and size(200, 200, P3D) String sizing = "[\\s\\;]size\\s*\\(\\s*(\\S+)\\s*,\\s*(\\d+)"; Pattern pattern = compiler.compile(sizing); // adds a space at the beginning, in case size() is the very // first thing in the program (very common), since the regexp // needs to check for things in front of it. PatternMatcherInput input = new PatternMatcherInput(" " + code[0].program); if (matcher.contains(input, pattern)) { MatchResult result = matcher.getMatch(); try { wide = Integer.parseInt(result.group(1).toString()); high = Integer.parseInt(result.group(2).toString()); } catch (NumberFormatException e) { // found a reference to size, but it didn't // seem to contain numbers final String message = "The size of this applet could not automatically be\n" + "determined from your code. You'll have to edit the\n" + "HTML file to set the size of the applet."; Base.showWarning("Could not find applet size", message, null); } } // else no size() command found // originally tried to grab this with a regexp matcher, // but it wouldn't span over multiple lines for the match. // this could prolly be forced, but since that's the case // better just to parse by hand. StringBuffer dbuffer = new StringBuffer(); String lines[] = PApplet.split(code[0].program, '\n'); for (int i = 0; i < lines.length; i++) { if (lines[i].trim().startsWith("/**")) { // this is our comment */ // some smartass put the whole thing on the same line //if (lines[j].indexOf("*/") != -1) break; // for (int j = i+1; j < lines.length; j++) { // if (lines[j].trim().endsWith("*/")) { // remove the */ from the end, and any extra *s // in case there's also content on this line // nah, don't bother.. make them use the three lines // break; // } /* int offset = 0; while ((offset < lines[j].length()) && ((lines[j].charAt(offset) == '*') || (lines[j].charAt(offset) == ' '))) { offset++; } // insert the return into the html to help w/ line breaks dbuffer.append(lines[j].substring(offset) + "\n"); } } } String description = dbuffer.toString(); StringBuffer sources = new StringBuffer(); for (int i = 0; i < codeCount; i++) { sources.append("<a href=\"" + code[i].file.getName() + "\">" + code[i].name + "</a> "); } File htmlOutputFile = new File(appletFolder, "index.html"); FileOutputStream fos = new FileOutputStream(htmlOutputFile); PrintStream ps = new PrintStream(fos); // @@sketch@@, @@width@@, @@height@@, @@archive@@, @@source@@ // and now @@description@@ InputStream is = null; // if there is an applet.html file in the sketch folder, use that File customHtml = new File(folder, "applet.html"); if (customHtml.exists()) { is = new FileInputStream(customHtml); } if (is == null) { is = Base.getStream("applet.html"); } BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line = null; while ((line = reader.readLine()) != null) { if (line.indexOf("@@") != -1) { StringBuffer sb = new StringBuffer(line); int index = 0; while ((index = sb.indexOf("@@sketch@@")) != -1) { sb.replace(index, index + "@@sketch@@".length(), name); } while ((index = sb.indexOf("@@source@@")) != -1) { sb.replace(index, index + "@@source@@".length(), sources.toString()); } while ((index = sb.indexOf("@@archive@@")) != -1) { sb.replace(index, index + "@@archive@@".length(), name + ".jar"); } while ((index = sb.indexOf("@@width@@")) != -1) { sb.replace(index, index + "@@width@@".length(), String.valueOf(wide)); } while ((index = sb.indexOf("@@height@@")) != -1) { sb.replace(index, index + "@@height@@".length(), String.valueOf(high)); } while ((index = sb.indexOf("@@description@@")) != -1) { sb.replace(index, index + "@@description@@".length(), description); } line = sb.toString(); } ps.println(line); } reader.close(); ps.flush(); ps.close(); // copy the loading gif to the applet String LOADING_IMAGE = "loading.gif"; File loadingImage = new File(folder, LOADING_IMAGE); if (!loadingImage.exists()) { loadingImage = new File("lib", LOADING_IMAGE); } Base.copyFile(loadingImage, new File(appletFolder, LOADING_IMAGE)); */ // copy the source files to the target, since we like // to encourage people to share their code for (int i = 0; i < codeCount; i++) { try { Base.copyFile(code[i].file, new File(appletFolder, code[i].file.getName())); } catch (IOException e) { e.printStackTrace(); } } /* // create new .jar file FileOutputStream zipOutputFile = new FileOutputStream(new File(appletFolder, name + ".jar")); ZipOutputStream zos = new ZipOutputStream(zipOutputFile); ZipEntry entry; // add the manifest file addManifest(zos); // add the contents of the code folder to the jar // unpacks all jar files //File codeFolder = new File(folder, "code"); if (codeFolder.exists()) { String includes = Compiler.contentsToClassPath(codeFolder); packClassPathIntoZipFile(includes, zos); } // add contents of 'library' folders to the jar file // if a file called 'export.txt' is in there, it contains // a list of the files that should be exported. // otherwise, all files are exported. Enumeration en = importedLibraries.elements(); while (en.hasMoreElements()) { // in the list is a File object that points the // library sketch's "library" folder File libraryFolder = (File)en.nextElement(); File exportSettings = new File(libraryFolder, "export.txt"); String exportList[] = null; if (exportSettings.exists()) { String info[] = Base.loadStrings(exportSettings); for (int i = 0; i < info.length; i++) { if (info[i].startsWith("applet")) { int idx = info[i].indexOf('='); // get applet= or applet = String commas = info[i].substring(idx+1).trim(); exportList = PApplet.split(commas, ", "); } } } else { exportList = libraryFolder.list(); } for (int i = 0; i < exportList.length; i++) { if (exportList[i].equals(".") || exportList[i].equals("..")) continue; exportList[i] = PApplet.trim(exportList[i]); if (exportList[i].equals("")) continue; File exportFile = new File(libraryFolder, exportList[i]); if (!exportFile.exists()) { System.err.println("File " + exportList[i] + " does not exist"); } else if (exportFile.isDirectory()) { System.err.println("Ignoring sub-folder \"" + exportList[i] + "\""); } else if (exportFile.getName().toLowerCase().endsWith(".zip") || exportFile.getName().toLowerCase().endsWith(".jar")) { packClassPathIntoZipFile(exportFile.getAbsolutePath(), zos); } else { // just copy the file over.. prolly a .dll or something Base.copyFile(exportFile, new File(appletFolder, exportFile.getName())); } } } */ /* String bagelJar = "lib/core.jar"; packClassPathIntoZipFile(bagelJar, zos); // files to include from data directory // TODO this needs to be recursive if (dataFolder.exists()) { String dataFiles[] = dataFolder.list(); for (int i = 0; i < dataFiles.length; i++) { // don't export hidden files // skipping dot prefix removes all: . .. .DS_Store if (dataFiles[i].charAt(0) == '.') continue; entry = new ZipEntry(dataFiles[i]); zos.putNextEntry(entry); zos.write(Base.grabFile(new File(dataFolder, dataFiles[i]))); zos.closeEntry(); } } // add the project's .class files to the jar // just grabs everything from the build directory // since there may be some inner classes // (add any .class files from the applet dir, then delete them) // TODO this needs to be recursive (for packages) String classfiles[] = appletFolder.list(); for (int i = 0; i < classfiles.length; i++) { if (classfiles[i].endsWith(".class")) { entry = new ZipEntry(classfiles[i]); zos.putNextEntry(entry); zos.write(Base.grabFile(new File(appletFolder, classfiles[i]))); zos.closeEntry(); } } */ String classfiles[] = appletFolder.list(); // remove the .class files from the applet folder. if they're not // removed, the msjvm will complain about an illegal access error, // since the classes are outside the jar file. for (int i = 0; i < classfiles.length; i++) { if (classfiles[i].endsWith(".class")) { File deadguy = new File(appletFolder, classfiles[i]); if (!deadguy.delete()) { Base.showWarning("Could not delete", classfiles[i] + " could not \n" + "be deleted from the applet folder. \n" + "You'll need to remove it by hand.", null); } } } // close up the jar file /* zos.flush(); zos.close(); */ if(Preferences.getBoolean("uploader.open_folder")) Base.openFolder(appletFolder); return true; } /** * Export to application. * <PRE> * +-------------------------------------------------------+ * + + * + Export to: [ Application + ] [ OK ] + * + + * + > Advanced + * + - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + Version: [ Java 1.1 + ] + * + + * + Not much point to using Java 1.1 for applications. + * + To run applications, all users will have to + * + install Java, in which case they'll most likely + * + have version 1.3 or later. + * + - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + Version: [ Java 1.3 + ] + * + + * + Java 1.3 is the recommended setting for exporting + * + applications. Applications will run on any Windows + * + or Unix machine with Java installed. Mac OS X has + * + Java installed with the operation system, so there + * + is no additional installation will be required. + * + + * + - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + + * + Platform: [ Mac OS X + ] <-- defaults to current platform * + + * + Exports the application as a double-clickable + * + .app package, compatible with Mac OS X. + * + - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + Platform: [ Windows + ] + * + + * + Exports the application as a double-clickable + * + .exe and a handful of supporting files. + * + - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + Platform: [ jar file + ] + * + + * + A jar file can be used on any platform that has + * + Java installed. Simply doube-click the jar (or type + * + "java -jar sketch.jar" at a command prompt) to run + * + the application. It is the least fancy method for + * + exporting. + * + + * +-------------------------------------------------------+ * </PRE> */ public boolean exportApplication() { return true; } /* public void addManifest(ZipOutputStream zos) throws IOException { ZipEntry entry = new ZipEntry("META-INF/MANIFEST.MF"); zos.putNextEntry(entry); String contents = "Manifest-Version: 1.0\n" + "Created-By: Processing " + Base.VERSION_NAME + "\n" + "Main-Class: " + name + "\n"; // TODO not package friendly zos.write(contents.getBytes()); zos.closeEntry(); */ /* for (int i = 0; i < bagelClasses.length; i++) { if (!bagelClasses[i].endsWith(".class")) continue; entry = new ZipEntry(bagelClasses[i]); zos.putNextEntry(entry); zos.write(Base.grabFile(new File(exportDir + bagelClasses[i]))); zos.closeEntry(); } */ /* } */ /** * Slurps up .class files from a colon (or semicolon on windows) * separated list of paths and adds them to a ZipOutputStream. */ /* public void packClassPathIntoZipFile(String path, ZipOutputStream zos) throws IOException { String pieces[] = PApplet.split(path, File.pathSeparatorChar); for (int i = 0; i < pieces.length; i++) { if (pieces[i].length() == 0) continue; //System.out.println("checking piece " + pieces[i]); // is it a jar file or directory? if (pieces[i].toLowerCase().endsWith(".jar") || pieces[i].toLowerCase().endsWith(".zip")) { try { ZipFile file = new ZipFile(pieces[i]); Enumeration entries = file.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (entry.isDirectory()) { // actually 'continue's for all dir entries } else { String entryName = entry.getName(); // ignore contents of the META-INF folders if (entryName.indexOf("META-INF") == 0) continue; // don't allow duplicate entries if (zipFileContents.get(entryName) != null) continue; zipFileContents.put(entryName, new Object()); ZipEntry entree = new ZipEntry(entryName); zos.putNextEntry(entree); byte buffer[] = new byte[(int) entry.getSize()]; InputStream is = file.getInputStream(entry); int offset = 0; int remaining = buffer.length; while (remaining > 0) { int count = is.read(buffer, offset, remaining); offset += count; remaining -= count; } zos.write(buffer); zos.flush(); zos.closeEntry(); } } } catch (IOException e) { System.err.println("Error in file " + pieces[i]); e.printStackTrace(); } } else { // not a .jar or .zip, prolly a directory File dir = new File(pieces[i]); // but must be a dir, since it's one of several paths // just need to check if it exists if (dir.exists()) { packClassPathIntoZipFileRecursive(dir, null, zos); } } } } */ /** * Continue the process of magical exporting. This function * can be called recursively to walk through folders looking * for more goodies that will be added to the ZipOutputStream. */ /* static public void packClassPathIntoZipFileRecursive(File dir, String sofar, ZipOutputStream zos) throws IOException { String files[] = dir.list(); for (int i = 0; i < files.length; i++) { // ignore . .. and .DS_Store if (files[i].charAt(0) == '.') continue; File sub = new File(dir, files[i]); String nowfar = (sofar == null) ? files[i] : (sofar + "/" + files[i]); if (sub.isDirectory()) { packClassPathIntoZipFileRecursive(sub, nowfar, zos); } else { // don't add .jar and .zip files, since they only work // inside the root, and they're unpacked if (!files[i].toLowerCase().endsWith(".jar") && !files[i].toLowerCase().endsWith(".zip") && files[i].charAt(0) != '.') { ZipEntry entry = new ZipEntry(nowfar); zos.putNextEntry(entry); zos.write(Base.grabFile(sub)); zos.closeEntry(); } } } } */ /** * Make sure the sketch hasn't been moved or deleted by some * nefarious user. If they did, try to re-create it and save. * Only checks to see if the main folder is still around, * but not its contents. */ protected void ensureExistence() { if (folder.exists()) return; Base.showWarning("Sketch Disappeared", "The sketch folder has disappeared.\n " + "Will attempt to re-save in the same location,\n" + "but anything besides the code will be lost.", null); try { folder.mkdirs(); modified = true; for (int i = 0; i < codeCount; i++) { code[i].save(); // this will force a save } for (int i = 0; i < hiddenCount; i++) { hidden[i].save(); // this will force a save } calcModified(); } catch (Exception e) { Base.showWarning("Could not re-save sketch", "Could not properly re-save the sketch. " + "You may be in trouble at this point,\n" + "and it might be time to copy and paste " + "your code to another text editor.", e); } } /** * Returns true if this is a read-only sketch. Used for the * examples directory, or when sketches are loaded from read-only * volumes or folders without appropriate permissions. */ public boolean isReadOnly() { String apath = folder.getAbsolutePath(); if (apath.startsWith(Sketchbook.examplesPath) || apath.startsWith(Sketchbook.librariesPath)) { return true; // canWrite() doesn't work on directories //} else if (!folder.canWrite()) { } else { // check to see if each modified code file can be written to for (int i = 0; i < codeCount; i++) { if (code[i].modified && !code[i].file.canWrite() && code[i].file.exists()) { //System.err.println("found a read-only file " + code[i].file); return true; } } //return true; } return false; } /** * Returns path to the main .pde file for this sketch. */ public String getMainFilePath() { return code[0].file.getAbsolutePath(); } }
app/Sketch.java
/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* Part of the Processing project - http://processing.org Copyright (c) 2004-05 Ben Fry and Casey Reas Copyright (c) 2001-04 Massachusetts Institute of Technology This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package processing.app; import processing.app.preproc.*; //import processing.core.*; import java.awt.*; import java.io.*; import java.util.*; import java.util.zip.*; import javax.swing.JOptionPane; import com.oroinc.text.regex.*; /** * Stores information about files in the current sketch */ public class Sketch { static File tempBuildFolder; Editor editor; /** * Name of sketch, which is the name of main file * (without .pde or .java extension) */ String name; /** * Name of 'main' file, used by load(), such as sketch_04040.pde */ String mainFilename; /** * true if any of the files have been modified. */ boolean modified; public File folder; public File dataFolder; public File codeFolder; static final int PDE = 0; static final int CPP = 1; static final int C = 2; static final int HEADER = 3; static final String flavorExtensionsReal[] = new String[] { ".pde", ".cpp", ".c", ".h" }; static final String flavorExtensionsShown[] = new String[] { "", ".cpp", ".c", ".h" }; public SketchCode current; int codeCount; SketchCode code[]; int hiddenCount; SketchCode hidden[]; Hashtable zipFileContents; // all these set each time build() is called String mainClassName; String classPath; String libraryPath; boolean externalRuntime; public Vector importedLibraries; // vec of Library objects /** * path is location of the main .pde file, because this is also * simplest to use when opening the file from the finder/explorer. */ public Sketch(Editor editor, String path) throws IOException { this.editor = editor; File mainFile = new File(path); //System.out.println("main file is " + mainFile); mainFilename = mainFile.getName(); //System.out.println("main file is " + mainFilename); // get the name of the sketch by chopping .pde or .java // off of the main file name if (mainFilename.endsWith(".pde")) { name = mainFilename.substring(0, mainFilename.length() - 4); } else if (mainFilename.endsWith(".c")) { name = mainFilename.substring(0, mainFilename.length() - 2); } else if (mainFilename.endsWith(".h")) { name = mainFilename.substring(0, mainFilename.length() - 2); } else if (mainFilename.endsWith(".cpp")) { name = mainFilename.substring(0, mainFilename.length() - 4); } // lib/build must exist when the application is started // it is added to the CLASSPATH by default, but if it doesn't // exist when the application is started, then java will remove // the entry from the CLASSPATH, causing Runner to fail. // /* tempBuildFolder = new File(TEMP_BUILD_PATH); if (!tempBuildFolder.exists()) { tempBuildFolder.mkdirs(); Base.showError("Required folder missing", "A required folder was missing from \n" + "from your installation of Processing.\n" + "It has now been replaced, please restart \n" + "the application to complete the repair.", null); } */ tempBuildFolder = Base.getBuildFolder(); //Base.addBuildFolderToClassPath(); folder = new File(new File(path).getParent()); //System.out.println("sketch dir is " + folder); load(); } /** * Build the list of files. * * Generally this is only done once, rather than * each time a change is made, because otherwise it gets to be * a nightmare to keep track of what files went where, because * not all the data will be saved to disk. * * This also gets called when the main sketch file is renamed, * because the sketch has to be reloaded from a different folder. * * Another exception is when an external editor is in use, * in which case the load happens each time "run" is hit. */ public void load() { codeFolder = new File(folder, "code"); dataFolder = new File(folder, "data"); // get list of files in the sketch folder String list[] = folder.list(); for (int i = 0; i < list.length; i++) { if (list[i].endsWith(".pde")) codeCount++; else if (list[i].endsWith(".c")) codeCount++; else if (list[i].endsWith(".h")) codeCount++; else if (list[i].endsWith(".cpp")) codeCount++; else if (list[i].endsWith(".pde.x")) hiddenCount++; else if (list[i].endsWith(".c.x")) hiddenCount++; else if (list[i].endsWith(".h.x")) hiddenCount++; else if (list[i].endsWith(".cpp.x")) hiddenCount++; } code = new SketchCode[codeCount]; hidden = new SketchCode[hiddenCount]; int codeCounter = 0; int hiddenCounter = 0; for (int i = 0; i < list.length; i++) { if (list[i].endsWith(".pde")) { code[codeCounter++] = new SketchCode(list[i].substring(0, list[i].length() - 4), new File(folder, list[i]), PDE); } else if (list[i].endsWith(".c")) { code[codeCounter++] = new SketchCode(list[i].substring(0, list[i].length() - 2), new File(folder, list[i]), C); } else if (list[i].endsWith(".h")) { code[codeCounter++] = new SketchCode(list[i].substring(0, list[i].length() - 2), new File(folder, list[i]), HEADER); } else if (list[i].endsWith(".cpp")) { code[codeCounter++] = new SketchCode(list[i].substring(0, list[i].length() - 4), new File(folder, list[i]), CPP); } else if (list[i].endsWith(".pde.x")) { hidden[hiddenCounter++] = new SketchCode(list[i].substring(0, list[i].length() - 6), new File(folder, list[i]), PDE); } else if (list[i].endsWith(".c.x")) { hidden[hiddenCounter++] = new SketchCode(list[i].substring(0, list[i].length() - 4), new File(folder, list[i]), C); } else if (list[i].endsWith(".h.x")) { hidden[hiddenCounter++] = new SketchCode(list[i].substring(0, list[i].length() - 4), new File(folder, list[i]), HEADER); } else if (list[i].endsWith(".cpp.x")) { hidden[hiddenCounter++] = new SketchCode(list[i].substring(0, list[i].length() - 6), new File(folder, list[i]), CPP); } } // remove any entries that didn't load properly int index = 0; while (index < codeCount) { if ((code[index] == null) || (code[index].program == null)) { for (int i = index+1; i < codeCount; i++) { code[i-1] = code[i]; } codeCount--; } else { index++; } } // move the main class to the first tab // start at 1, if it's at zero, don't bother for (int i = 1; i < codeCount; i++) { if (code[i].file.getName().equals(mainFilename)) { SketchCode temp = code[0]; code[0] = code[i]; code[i] = temp; break; } } // sort the entries at the top sortCode(); // set the main file to be the current tab setCurrent(0); } protected void insertCode(SketchCode newCode) { // make sure the user didn't hide the sketch folder ensureExistence(); // add file to the code/codeCount list, resort the list if (codeCount == code.length) { SketchCode temp[] = new SketchCode[codeCount+1]; System.arraycopy(code, 0, temp, 0, codeCount); code = temp; } code[codeCount++] = newCode; } protected void sortCode() { // cheap-ass sort of the rest of the files // it's a dumb, slow sort, but there shouldn't be more than ~5 files for (int i = 1; i < codeCount; i++) { int who = i; for (int j = i + 1; j < codeCount; j++) { if (code[j].name.compareTo(code[who].name) < 0) { who = j; // this guy is earlier in the alphabet } } if (who != i) { // swap with someone if changes made SketchCode temp = code[who]; code[who] = code[i]; code[i] = temp; } } } boolean renamingCode; public void newCode() { // make sure the user didn't hide the sketch folder ensureExistence(); // if read-only, give an error if (isReadOnly()) { // if the files are read-only, need to first do a "save as". Base.showMessage("Sketch is Read-Only", "Some files are marked \"read-only\", so you'll\n" + "need to re-save the sketch in another location,\n" + "and try again."); return; } renamingCode = false; editor.status.edit("Name for new file:", ""); } public void renameCode() { // make sure the user didn't hide the sketch folder ensureExistence(); // if read-only, give an error if (isReadOnly()) { // if the files are read-only, need to first do a "save as". Base.showMessage("Sketch is Read-Only", "Some files are marked \"read-only\", so you'll\n" + "need to re-save the sketch in another location,\n" + "and try again."); return; } // ask for new name of file (internal to window) // TODO maybe just popup a text area? renamingCode = true; String prompt = (current == code[0]) ? "New name for sketch:" : "New name for file:"; String oldName = current.name + flavorExtensionsShown[current.flavor]; editor.status.edit(prompt, oldName); } /** * This is called upon return from entering a new file name. * (that is, from either newCode or renameCode after the prompt) * This code is almost identical for both the newCode and renameCode * cases, so they're kept merged except for right in the middle * where they diverge. */ public void nameCode(String newName) { // make sure the user didn't hide the sketch folder ensureExistence(); // if renaming to the same thing as before, just ignore. // also ignoring case here, because i don't want to write // a bunch of special stuff for each platform // (osx is case insensitive but preserving, windows insensitive, // *nix is sensitive and preserving.. argh) if (renamingCode && newName.equalsIgnoreCase(current.name)) { // exit quietly for the 'rename' case. // if it's a 'new' then an error will occur down below return; } // don't allow blank names if (newName.trim().equals("")) { return; } if (newName.trim().equals(".c") || newName.trim().equals(".h") || newName.trim().equals(".pde") || newName.trim().equals(".cpp")) { return; } String newFilename = null; int newFlavor = 0; // separate into newName (no extension) and newFilename (with ext) // add .pde to file if it has no extension if (newName.endsWith(".pde")) { newFilename = newName; newName = newName.substring(0, newName.length() - 4); newFlavor = PDE; } else if (newName.endsWith(".c") || newName.endsWith(".cpp") || newName.endsWith(".h")) { // don't show this error if creating a new tab if (renamingCode && (code[0] == current)) { Base.showWarning("Problem with rename", "The main .pde file cannot be .c, .cpp, or .h file.\n" + "(It may be time for your to graduate to a\n" + "\"real\" programming environment)", null); return; } newFilename = newName; if(newName.endsWith(".c")) { newName = newName.substring(0, newName.length() - 2); newFlavor = C; } if(newName.endsWith(".h")) { newName = newName.substring(0, newName.length() - 2); newFlavor = HEADER; } else if(newName.endsWith(".cpp")) { newName = newName.substring(0, newName.length() - 4); newFlavor = CPP; } } else { newFilename = newName + ".pde"; newFlavor = PDE; } // dots are allowed for the .pde and .java, but not in the name // make sure the user didn't name things poo.time.pde // or something like that (nothing against poo time) if (newName.indexOf('.') != -1) { newName = Sketchbook.sanitizedName(newName); newFilename = newName + ((newFlavor == PDE) ? ".pde" : ".cpp"); } // create the new file, new SketchCode object and load it File newFile = new File(folder, newFilename); if (newFile.exists()) { // yay! users will try anything Base.showMessage("Nope", "A file named \"" + newFile + "\" already exists\n" + "in \"" + folder.getAbsolutePath() + "\""); return; } File newFileHidden = new File(folder, newFilename + ".x"); if (newFileHidden.exists()) { // don't let them get away with it if they try to create something // with the same name as something hidden Base.showMessage("No Way", "A hidden tab with the same name already exists.\n" + "Use \"Unhide\" to bring it back."); return; } if (renamingCode) { if (current == code[0]) { // get the new folder name/location File newFolder = new File(folder.getParentFile(), newName); if (newFolder.exists()) { Base.showWarning("Cannot Rename", "Sorry, a sketch (or folder) named " + "\"" + newName + "\" already exists.", null); return; } // unfortunately this can't be a "save as" because that // only copies the sketch files and the data folder // however this *will* first save the sketch, then rename // first get the contents of the editor text area if (current.modified) { current.program = editor.getText(); try { // save this new SketchCode current.save(); } catch (Exception e) { Base.showWarning("Error", "Could not rename the sketch. (0)", e); return; } } if (!current.file.renameTo(newFile)) { Base.showWarning("Error", "Could not rename \"" + current.file.getName() + "\" to \"" + newFile.getName() + "\"", null); return; } // save each of the other tabs because this is gonna be re-opened try { for (int i = 1; i < codeCount; i++) { //if (code[i].modified) code[i].save(); code[i].save(); } } catch (Exception e) { Base.showWarning("Error", "Could not rename the sketch. (1)", e); return; } // now rename the sketch folder and re-open boolean success = folder.renameTo(newFolder); if (!success) { Base.showWarning("Error", "Could not rename the sketch. (2)", null); return; } // if successful, set base properties for the sketch File mainFile = new File(newFolder, newName + ".pde"); mainFilename = mainFile.getAbsolutePath(); // having saved everything and renamed the folder and the main .pde, // use the editor to re-open the sketch to re-init state // (unfortunately this will kill positions for carets etc) editor.handleOpenUnchecked(mainFilename); /* // backtrack and don't rename the sketch folder success = newFolder.renameTo(folder); if (!success) { String msg = "Started renaming sketch and then ran into\n" + "nasty trouble. Try to salvage with Copy & Paste\n" + "or attempt a \"Save As\" to see if that works."; Base.showWarning("Serious Error", msg, null); } return; } */ /* // set the sketch name... used by the pde and whatnot. // the name is only set in the sketch constructor, // so it's important here name = newName; code[0].name = newName; code[0].file = mainFile; code[0].program = editor.getText(); code[0].save(); folder = newFolder; // get the changes into the sketchbook menu editor.sketchbook.rebuildMenus(); // reload the sketch load(); */ } else { if (!current.file.renameTo(newFile)) { Base.showWarning("Error", "Could not rename \"" + current.file.getName() + "\" to \"" + newFile.getName() + "\"", null); return; } // just reopen the class itself current.name = newName; current.file = newFile; current.flavor = newFlavor; } } else { // creating a new file try { newFile.createNewFile(); // TODO returns a boolean } catch (IOException e) { Base.showWarning("Error", "Could not create the file \"" + newFile + "\"\n" + "in \"" + folder.getAbsolutePath() + "\"", e); return; } SketchCode newCode = new SketchCode(newName, newFile, newFlavor); insertCode(newCode); } // sort the entries sortCode(); // set the new guy as current setCurrent(newName + flavorExtensionsShown[newFlavor]); // update the tabs //editor.header.repaint(); editor.header.rebuild(); // force the update on the mac? Toolkit.getDefaultToolkit().sync(); //editor.header.getToolkit().sync(); } /** * Remove a piece of code from the sketch and from the disk. */ public void deleteCode() { // make sure the user didn't hide the sketch folder ensureExistence(); // if read-only, give an error if (isReadOnly()) { // if the files are read-only, need to first do a "save as". Base.showMessage("Sketch is Read-Only", "Some files are marked \"read-only\", so you'll\n" + "need to re-save the sketch in another location,\n" + "and try again."); return; } // confirm deletion with user, yes/no Object[] options = { "OK", "Cancel" }; String prompt = (current == code[0]) ? "Are you sure you want to delete this sketch?" : "Are you sure you want to delete \"" + current.name + flavorExtensionsShown[current.flavor] + "\"?"; int result = JOptionPane.showOptionDialog(editor, prompt, "Delete", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (result == JOptionPane.YES_OPTION) { if (current == code[0]) { // need to unset all the modified flags, otherwise tries // to do a save on the handleNew() // delete the entire sketch Base.removeDir(folder); // get the changes into the sketchbook menu //sketchbook.rebuildMenus(); // make a new sketch, and i think this will rebuild the sketch menu editor.handleNewUnchecked(); } else { // delete the file if (!current.file.delete()) { Base.showMessage("Couldn't do it", "Could not delete \"" + current.name + "\"."); return; } // remove code from the list removeCode(current); // just set current tab to the main tab setCurrent(0); // update the tabs editor.header.repaint(); } } } protected void removeCode(SketchCode which) { // remove it from the internal list of files // resort internal list of files for (int i = 0; i < codeCount; i++) { if (code[i] == which) { for (int j = i; j < codeCount-1; j++) { code[j] = code[j+1]; } codeCount--; return; } } System.err.println("removeCode: internal error.. could not find code"); } public void hideCode() { // make sure the user didn't hide the sketch folder ensureExistence(); // if read-only, give an error if (isReadOnly()) { // if the files are read-only, need to first do a "save as". Base.showMessage("Sketch is Read-Only", "Some files are marked \"read-only\", so you'll\n" + "need to re-save the sketch in another location,\n" + "and try again."); return; } // don't allow hide of the main code // TODO maybe gray out the menu on setCurrent(0) if (current == code[0]) { Base.showMessage("Can't do that", "You cannot hide the main " + ".pde file from a sketch\n"); return; } // rename the file File newFile = new File(current.file.getAbsolutePath() + ".x"); if (!current.file.renameTo(newFile)) { Base.showWarning("Error", "Could not hide " + "\"" + current.file.getName() + "\".", null); return; } current.file = newFile; // move it to the hidden list if (hiddenCount == hidden.length) { SketchCode temp[] = new SketchCode[hiddenCount+1]; System.arraycopy(hidden, 0, temp, 0, hiddenCount); hidden = temp; } hidden[hiddenCount++] = current; // remove it from the main list removeCode(current); // update the tabs setCurrent(0); editor.header.repaint(); } public void unhideCode(String what) { SketchCode unhideCode = null; String name = what.substring(0, (what.indexOf(".") == -1 ? what.length() : what.indexOf("."))); String extension = what.indexOf(".") == -1 ? "" : what.substring(what.indexOf(".")); for (int i = 0; i < hiddenCount; i++) { if (hidden[i].name.equals(name) && Sketch.flavorExtensionsShown[hidden[i].flavor].equals(extension)) { //unhideIndex = i; unhideCode = hidden[i]; // remove from the 'hidden' list for (int j = i; j < hiddenCount-1; j++) { hidden[j] = hidden[j+1]; } hiddenCount--; break; } } //if (unhideIndex == -1) { if (unhideCode == null) { System.err.println("internal error: could find " + what + " to unhide."); return; } if (!unhideCode.file.exists()) { Base.showMessage("Can't unhide", "The file \"" + what + "\" no longer exists."); //System.out.println(unhideCode.file); return; } String unhidePath = unhideCode.file.getAbsolutePath(); File unhideFile = new File(unhidePath.substring(0, unhidePath.length() - 2)); if (!unhideCode.file.renameTo(unhideFile)) { Base.showMessage("Can't unhide", "The file \"" + what + "\" could not be" + "renamed and unhidden."); return; } unhideCode.file = unhideFile; insertCode(unhideCode); sortCode(); setCurrent(unhideCode.name); editor.header.repaint(); } /** * Sets the modified value for the code in the frontmost tab. */ public void setModified(boolean state) { current.modified = state; calcModified(); } public void calcModified() { modified = false; for (int i = 0; i < codeCount; i++) { if (code[i].modified) { modified = true; break; } } editor.header.repaint(); } /** * Save all code in the current sketch. */ public boolean save() throws IOException { // make sure the user didn't hide the sketch folder ensureExistence(); // first get the contents of the editor text area if (current.modified) { current.program = editor.getText(); } // don't do anything if not actually modified //if (!modified) return false; if (isReadOnly()) { // if the files are read-only, need to first do a "save as". Base.showMessage("Sketch is read-only", "Some files are marked \"read-only\", so you'll\n" + "need to re-save this sketch to another location."); // if the user cancels, give up on the save() if (!saveAs()) return false; } for (int i = 0; i < codeCount; i++) { if (code[i].modified) code[i].save(); } calcModified(); return true; } /** * Handles 'Save As' for a sketch. * <P> * This basically just duplicates the current sketch folder to * a new location, and then calls 'Save'. (needs to take the current * state of the open files and save them to the new folder.. * but not save over the old versions for the old sketch..) * <P> * Also removes the previously-generated .class and .jar files, * because they can cause trouble. */ public boolean saveAs() throws IOException { // get new name for folder FileDialog fd = new FileDialog(editor, "Save sketch folder as...", FileDialog.SAVE); if (isReadOnly()) { // default to the sketchbook folder fd.setDirectory(Preferences.get("sketchbook.path")); } else { // default to the parent folder of where this was fd.setDirectory(folder.getParent()); } fd.setFile(folder.getName()); fd.show(); String newParentDir = fd.getDirectory(); String newName = fd.getFile(); // user cancelled selection if (newName == null) return false; newName = Sketchbook.sanitizeName(newName); // make sure there doesn't exist a tab with that name already // (but allow it if it's just the main tab resaving itself.. oops) File codeAlready = new File(folder, newName + ".pde"); if (codeAlready.exists() && (!newName.equals(name))) { Base.showMessage("Nope", "You can't save the sketch as \"" + newName + "\"\n" + "because the sketch already has a tab with that name."); return false; } // make sure there doesn't exist a tab with that name already File hiddenAlready = new File(folder, newName + ".pde.x"); if (hiddenAlready.exists()) { Base.showMessage("Nope", "You can't save the sketch as \"" + newName + "\"\n" + "because the sketch already has a " + "hidden tab with that name."); return false; } // new sketch folder File newFolder = new File(newParentDir, newName); // make sure the paths aren't the same if (newFolder.equals(folder)) { Base.showWarning("You can't fool me", "The new sketch name and location are the same as\n" + "the old. I ain't not doin nuthin' not now.", null); return false; } // check to see if the user is trying to save this sketch // inside the same sketch try { String newPath = newFolder.getCanonicalPath() + File.separator; String oldPath = folder.getCanonicalPath() + File.separator; if (newPath.indexOf(oldPath) == 0) { Base.showWarning("How very Borges of you", "You cannot save the sketch into a folder\n" + "inside itself. This would go on forever.", null); return false; } } catch (IOException e) { } // if the new folder already exists, then need to remove // its contents before copying everything over // (user will have already been warned) if (newFolder.exists()) { Base.removeDir(newFolder); } // in fact, you can't do this on windows because the file dialog // will instead put you inside the folder, but it happens on osx a lot. // now make a fresh copy of the folder newFolder.mkdirs(); // grab the contents of the current tab before saving // first get the contents of the editor text area if (current.modified) { current.program = editor.getText(); } // save the other tabs to their new location for (int i = 1; i < codeCount; i++) { File newFile = new File(newFolder, code[i].file.getName()); code[i].saveAs(newFile); } // save the hidden code to its new location for (int i = 0; i < hiddenCount; i++) { File newFile = new File(newFolder, hidden[i].file.getName()); hidden[i].saveAs(newFile); } // re-copy the data folder (this may take a while.. add progress bar?) if (dataFolder.exists()) { File newDataFolder = new File(newFolder, "data"); Base.copyDir(dataFolder, newDataFolder); } // re-copy the code folder if (codeFolder.exists()) { File newCodeFolder = new File(newFolder, "code"); Base.copyDir(codeFolder, newCodeFolder); } // save the main tab with its new name File newFile = new File(newFolder, newName + ".pde"); code[0].saveAs(newFile); editor.handleOpenUnchecked(newFile.getPath()); /* // copy the entire contents of the sketch folder Base.copyDir(folder, newFolder); // change the references to the dir location in SketchCode files for (int i = 0; i < codeCount; i++) { code[i].file = new File(newFolder, code[i].file.getName()); } for (int i = 0; i < hiddenCount; i++) { hidden[i].file = new File(newFolder, hidden[i].file.getName()); } // remove the old sketch file from the new dir code[0].file.delete(); // name for the new main .pde file code[0].file = new File(newFolder, newName + ".pde"); code[0].name = newName; // write the contents to the renamed file // (this may be resaved if the code is modified) code[0].modified = true; //code[0].save(); //System.out.println("modified is " + modified); // change the other paths String oldName = name; name = newName; File oldFolder = folder; folder = newFolder; dataFolder = new File(folder, "data"); codeFolder = new File(folder, "code"); // remove the 'applet', 'application', 'library' folders // from the copied version. // otherwise their .class and .jar files can cause conflicts. Base.removeDir(new File(folder, "applet")); Base.removeDir(new File(folder, "application")); //Base.removeDir(new File(folder, "library")); // do a "save" // this will take care of the unsaved changes in each of the tabs save(); // get the changes into the sketchbook menu //sketchbook.rebuildMenu(); // done inside Editor instead // update the tabs for the name change editor.header.repaint(); */ // let Editor know that the save was successful return true; } /** * Prompt the user for a new file to the sketch. * This could be .class or .jar files for the code folder, * .pde or .java files for the project, * or .dll, .jnilib, or .so files for the code folder */ public void addFile() { // make sure the user didn't hide the sketch folder ensureExistence(); // if read-only, give an error if (isReadOnly()) { // if the files are read-only, need to first do a "save as". Base.showMessage("Sketch is Read-Only", "Some files are marked \"read-only\", so you'll\n" + "need to re-save the sketch in another location,\n" + "and try again."); return; } // get a dialog, select a file to add to the sketch String prompt = "Select an image or other data file to copy to your sketch"; //FileDialog fd = new FileDialog(new Frame(), prompt, FileDialog.LOAD); FileDialog fd = new FileDialog(editor, prompt, FileDialog.LOAD); fd.show(); String directory = fd.getDirectory(); String filename = fd.getFile(); if (filename == null) return; // copy the file into the folder. if people would rather // it move instead of copy, they can do it by hand File sourceFile = new File(directory, filename); // now do the work of adding the file addFile(sourceFile); } /** * Add a file to the sketch. * <p/> * .pde or .java files will be added to the sketch folder. <br/> * .jar, .class, .dll, .jnilib, and .so files will all * be added to the "code" folder. <br/> * All other files will be added to the "data" folder. * <p/> * If they don't exist already, the "code" or "data" folder * will be created. * <p/> * @return true if successful. */ public boolean addFile(File sourceFile) { String filename = sourceFile.getName(); File destFile = null; boolean addingCode = false; // if the file appears to be code related, drop it // into the code folder, instead of the data folder if (filename.toLowerCase().endsWith(".o") /*|| filename.toLowerCase().endsWith(".jar") || filename.toLowerCase().endsWith(".dll") || filename.toLowerCase().endsWith(".jnilib") || filename.toLowerCase().endsWith(".so") */ ) { //File codeFolder = new File(this.folder, "code"); if (!codeFolder.exists()) codeFolder.mkdirs(); destFile = new File(codeFolder, filename); } else if (filename.toLowerCase().endsWith(".pde") || filename.toLowerCase().endsWith(".c") || filename.toLowerCase().endsWith(".h") || filename.toLowerCase().endsWith(".cpp")) { destFile = new File(this.folder, filename); addingCode = true; } else { //File dataFolder = new File(this.folder, "data"); if (!dataFolder.exists()) dataFolder.mkdirs(); destFile = new File(dataFolder, filename); } // make sure they aren't the same file if (!addingCode && sourceFile.equals(destFile)) { Base.showWarning("You can't fool me", "This file has already been copied to the\n" + "location where you're trying to add it.\n" + "I ain't not doin nuthin'.", null); return false; } // in case the user is "adding" the code in an attempt // to update the sketch's tabs if (!sourceFile.equals(destFile)) { try { Base.copyFile(sourceFile, destFile); } catch (IOException e) { Base.showWarning("Error adding file", "Could not add '" + filename + "' to the sketch.", e); return false; } } // make the tabs update after this guy is added if (addingCode) { String newName = destFile.getName(); int newFlavor = -1; if (newName.toLowerCase().endsWith(".pde")) { newName = newName.substring(0, newName.length() - 4); newFlavor = PDE; } else if (newName.toLowerCase().endsWith(".c")) { newName = newName.substring(0, newName.length() - 2); newFlavor = C; } else if (newName.toLowerCase().endsWith(".h")) { newName = newName.substring(0, newName.length() - 2); newFlavor = HEADER; } else { // ".cpp" newName = newName.substring(0, newName.length() - 4); newFlavor = CPP; } // see also "nameCode" for identical situation SketchCode newCode = new SketchCode(newName, destFile, newFlavor); insertCode(newCode); sortCode(); setCurrent(newName); editor.header.repaint(); } return true; } public void importLibrary(String jarPath) { //System.out.println(jarPath); // make sure the user didn't hide the sketch folder ensureExistence(); //String list[] = Compiler.packageListFromClassPath(jarPath); FileFilter onlyHFiles = new FileFilter() { public boolean accept(File file) { return (file.getName()).endsWith(".h"); } }; File list[] = new File(jarPath).listFiles(onlyHFiles); // import statements into the main sketch file (code[0]) // if the current code is a .java file, insert into current if (current.flavor == PDE) { setCurrent(0); } // could also scan the text in the file to see if each import // statement is already in there, but if the user has the import // commented out, then this will be a problem. StringBuffer buffer = new StringBuffer(); for (int i = 0; i < list.length; i++) { buffer.append("#include <"); buffer.append(list[i].getName()); buffer.append(">\n"); } buffer.append('\n'); buffer.append(editor.getText()); editor.setText(buffer.toString(), 0, 0); // scroll to start setModified(true); } /** * Change what file is currently being edited. * <OL> * <LI> store the String for the text of the current file. * <LI> retrieve the String for the text of the new file. * <LI> change the text that's visible in the text area * </OL> */ public void setCurrent(int which) { if (current == code[which]) { //System.out.println("already current, ignoring"); return; } // get the text currently being edited if (current != null) { current.program = editor.getText(); current.selectionStart = editor.textarea.getSelectionStart(); current.selectionStop = editor.textarea.getSelectionEnd(); current.scrollPosition = editor.textarea.getScrollPosition(); } current = code[which]; editor.setCode(current); //editor.setDocument(current.document, // current.selectionStart, current.selectionStop, // current.scrollPosition, current.undo); // set to the text for this file // 'true' means to wipe out the undo buffer // (so they don't undo back to the other file.. whups!) /* editor.setText(current.program, current.selectionStart, current.selectionStop, current.undo); */ // set stored caret and scroll positions //editor.textarea.setScrollPosition(current.scrollPosition); //editor.textarea.select(current.selectionStart, current.selectionStop); //editor.textarea.setSelectionStart(current.selectionStart); //editor.textarea.setSelectionEnd(current.selectionStop); editor.header.rebuild(); } /** * Internal helper function to set the current tab * based on a name (used by codeNew and codeRename). */ protected void setCurrent(String findName) { SketchCode unhideCode = null; String name = findName.substring(0, (findName.indexOf(".") == -1 ? findName.length() : findName.indexOf("."))); String extension = findName.indexOf(".") == -1 ? "" : findName.substring(findName.indexOf(".")); for (int i = 0; i < codeCount; i++) { if (name.equals(code[i].name) && Sketch.flavorExtensionsShown[code[i].flavor].equals(extension)) { setCurrent(i); return; } } } /** * Cleanup temporary files used during a build/run. */ protected void cleanup() { // if the java runtime is holding onto any files in the build dir, we // won't be able to delete them, so we need to force a gc here System.gc(); // note that we can't remove the builddir itself, otherwise // the next time we start up, internal runs using Runner won't // work because the build dir won't exist at startup, so the classloader // will ignore the fact that that dir is in the CLASSPATH in run.sh Base.removeDescendants(tempBuildFolder); } /** * Preprocess, Compile, and Run the current code. * <P> * There are three main parts to this process: * <PRE> * (0. if not java, then use another 'engine'.. i.e. python) * * 1. do the p5 language preprocessing * this creates a working .java file in a specific location * better yet, just takes a chunk of java code and returns a * new/better string editor can take care of saving this to a * file location * * 2. compile the code from that location * catching errors along the way * placing it in a ready classpath, or .. ? * * 3. run the code * needs to communicate location for window * and maybe setup presentation space as well * run externally if a code folder exists, * or if more than one file is in the project * * X. afterwards, some of these steps need a cleanup function * </PRE> */ public boolean handleRun(Target target) throws RunnerException { // make sure the user didn't hide the sketch folder ensureExistence(); current.program = editor.getText(); // TODO record history here //current.history.record(program, SketchHistory.RUN); // if an external editor is being used, need to grab the // latest version of the code from the file. if (Preferences.getBoolean("editor.external")) { // history gets screwed by the open.. //String historySaved = history.lastRecorded; //handleOpen(sketch); //history.lastRecorded = historySaved; // nuke previous files and settings, just get things loaded load(); } // in case there were any boogers left behind // do this here instead of after exiting, since the exit // can happen so many different ways.. and this will be // better connected to the dataFolder stuff below. cleanup(); // make up a temporary class name to suggest. // name will only be used if the code is not in ADVANCED mode. String suggestedClassName = ("Temporary_" + String.valueOf((int) (Math.random() * 10000)) + "_" + String.valueOf((int) (Math.random() * 10000))); // handle preprocessing the main file's code //mainClassName = build(TEMP_BUILD_PATH, suggestedClassName); mainClassName = build(target, tempBuildFolder.getAbsolutePath(), suggestedClassName); size(tempBuildFolder.getAbsolutePath(), name); // externalPaths is magically set by build() if (!externalRuntime) { // only if not running externally already // copy contents of data dir into lib/build if (dataFolder.exists()) { // just drop the files in the build folder (pre-68) //Base.copyDir(dataDir, buildDir); // drop the files into a 'data' subfolder of the build dir try { Base.copyDir(dataFolder, new File(tempBuildFolder, "data")); } catch (IOException e) { e.printStackTrace(); throw new RunnerException("Problem copying files from data folder"); } } } return (mainClassName != null); } /** * Build all the code for this sketch. * * In an advanced program, the returned classname could be different, * which is why the className is set based on the return value. * A compilation error will burp up a RunnerException. * * @return null if compilation failed, main class name if not */ protected String build(Target target, String buildPath, String suggestedClassName) throws RunnerException { // build unbuilt buildable libraries // completely independent from sketch, so run all the time editor.prepareLibraries(); // make sure the user didn't hide the sketch folder ensureExistence(); String codeFolderPackages[] = null; String javaClassPath = System.getProperty("java.class.path"); // remove quotes if any.. this is an annoying thing on windows if (javaClassPath.startsWith("\"") && javaClassPath.endsWith("\"")) { javaClassPath = javaClassPath.substring(1, javaClassPath.length() - 1); } classPath = buildPath + File.pathSeparator + Sketchbook.librariesClassPath + File.pathSeparator + javaClassPath; //System.out.println("cp = " + classPath); // figure out the contents of the code folder to see if there // are files that need to be added to the imports //File codeFolder = new File(folder, "code"); if (codeFolder.exists()) { externalRuntime = true; //classPath += File.pathSeparator + //Compiler.contentsToClassPath(codeFolder); classPath = Compiler.contentsToClassPath(codeFolder) + File.pathSeparator + classPath; //codeFolderPackages = Compiler.packageListFromClassPath(classPath); //codeFolderPackages = Compiler.packageListFromClassPath(codeFolder); libraryPath = codeFolder.getAbsolutePath(); // get a list of .jar files in the "code" folder // (class files in subfolders should also be picked up) String codeFolderClassPath = Compiler.contentsToClassPath(codeFolder); // get list of packages found in those jars // codeFolderPackages = // Compiler.packageListFromClassPath(codeFolderClassPath); //PApplet.println(libraryPath); //PApplet.println("packages:"); //PApplet.printarr(codeFolderPackages); } else { // since using the special classloader, // run externally whenever there are extra classes defined //externalRuntime = (codeCount > 1); // this no longer appears to be true.. so scrapping for 0088 // check to see if multiple files that include a .java file externalRuntime = false; for (int i = 0; i < codeCount; i++) { if (code[i].flavor == C || code[i].flavor == CPP) { externalRuntime = true; break; } } //codeFolderPackages = null; libraryPath = ""; } // if 'data' folder is large, set to external runtime if (dataFolder.exists() && Base.calcFolderSize(dataFolder) > 768 * 1024) { // if > 768k externalRuntime = true; } // 1. concatenate all .pde files to the 'main' pde // store line number for starting point of each code bit StringBuffer bigCode = new StringBuffer(code[0].program); int bigCount = countLines(code[0].program); for (int i = 1; i < codeCount; i++) { if (code[i].flavor == PDE) { code[i].preprocOffset = ++bigCount; bigCode.append('\n'); bigCode.append(code[i].program); bigCount += countLines(code[i].program); code[i].preprocName = null; // don't compile me } } // since using the special classloader, // run externally whenever there are extra classes defined /* if ((bigCode.indexOf(" class ") != -1) || (bigCode.indexOf("\nclass ") != -1)) { externalRuntime = true; } */ // if running in opengl mode, this is gonna be external //if (Preferences.get("renderer").equals("opengl")) { //externalRuntime = true; //} // 2. run preproc on that code using the sugg class name // to create a single .java file and write to buildpath String primaryClassName = null; PdePreprocessor preprocessor = new PdePreprocessor(); try { // if (i != 0) preproc will fail if a pde file is not // java mode, since that's required String className = preprocessor.write(bigCode.toString(), buildPath, suggestedClassName, codeFolderPackages); if (className == null) { throw new RunnerException("Could not find main class"); // this situation might be perfectly fine, // (i.e. if the file is empty) //System.out.println("No class found in " + code[i].name); //System.out.println("(any code in that file will be ignored)"); //System.out.println(); } else { code[0].preprocName = className + ".cpp"; } // store this for the compiler and the runtime primaryClassName = className; //System.out.println("primary class " + primaryClassName); // check if the 'main' file is in java mode if ((PdePreprocessor.programType == PdePreprocessor.JAVA) || (preprocessor.extraImports.length != 0)) { externalRuntime = true; // we in advanced mode now, boy } } catch (antlr.RecognitionException re) { // this even returns a column int errorFile = 0; int errorLine = re.getLine() - 1; for (int i = 1; i < codeCount; i++) { if ((code[i].flavor == PDE) && (code[i].preprocOffset < errorLine)) { errorFile = i; } } errorLine -= code[errorFile].preprocOffset; errorLine -= preprocessor.prototypeCount; errorLine -= preprocessor.headerCount; throw new RunnerException(re.getMessage(), errorFile, errorLine, re.getColumn()); } catch (antlr.TokenStreamRecognitionException tsre) { // while this seems to store line and column internally, // there doesn't seem to be a method to grab it.. // so instead it's done using a regexp PatternMatcher matcher = new Perl5Matcher(); PatternCompiler compiler = new Perl5Compiler(); // line 3:1: unexpected char: 0xA0 String mess = "^line (\\d+):(\\d+):\\s"; Pattern pattern = null; try { pattern = compiler.compile(mess); } catch (MalformedPatternException e) { Base.showWarning("Internal Problem", "An internal error occurred while trying\n" + "to compile the sketch. Please report\n" + "this online at " + "https://developer.berlios.de/bugs/?group_id=3590", e); } PatternMatcherInput input = new PatternMatcherInput(tsre.toString()); if (matcher.contains(input, pattern)) { MatchResult result = matcher.getMatch(); int errorLine = Integer.parseInt(result.group(1).toString()) - 1; int errorColumn = Integer.parseInt(result.group(2).toString()); int errorFile = 0; for (int i = 1; i < codeCount; i++) { if ((code[i].flavor == PDE) && (code[i].preprocOffset < errorLine)) { errorFile = i; } } errorLine -= code[errorFile].preprocOffset; errorLine -= preprocessor.prototypeCount; errorLine -= preprocessor.headerCount; throw new RunnerException(tsre.getMessage(), errorFile, errorLine, errorColumn); } else { // this is bad, defaults to the main class.. hrm. throw new RunnerException(tsre.toString(), 0, -1, -1); } } catch (RunnerException pe) { // RunnerExceptions are caught here and re-thrown, so that they don't // get lost in the more general "Exception" handler below. throw pe; } catch (Exception ex) { // TODO better method for handling this? System.err.println("Uncaught exception type:" + ex.getClass()); ex.printStackTrace(); throw new RunnerException(ex.toString()); } // grab the imports from the code just preproc'd importedLibraries = new Vector(); String imports[] = preprocessor.extraImports; try { LibraryManager libraryManager = new LibraryManager(); Collection libraries = libraryManager.getAll(); for (Iterator i = libraries.iterator(); i.hasNext(); ) { Library library = (Library) i.next(); File[] headerFiles = library.getHeaderFiles(); for (int j = 0; j < headerFiles.length; j++) for (int k = 0; k < imports.length; k++) if (headerFiles[j].getName().equals(imports[k]) && !importedLibraries.contains(library)) { importedLibraries.add(library); //System.out.println("Adding library " + library.getName()); } } } catch (IOException e) { System.err.println("Error finding libraries:"); e.printStackTrace(); throw new RunnerException(e.getMessage()); } //for (int i = 0; i < imports.length; i++) { /* // remove things up to the last dot String entry = imports[i].substring(0, imports[i].lastIndexOf('.')); //System.out.println("found package " + entry); File libFolder = (File) Sketchbook.importToLibraryTable.get(entry); if (libFolder == null) { //throw new RunnerException("Could not find library for " + entry); continue; } importedLibraries.add(libFolder); libraryPath += File.pathSeparator + libFolder.getAbsolutePath(); */ /* String list[] = libFolder.list(); if (list != null) { for (int j = 0; j < list.length; j++) { // this might have a dll/jnilib/so packed, // so add it to the library path if (list[j].toLowerCase().endsWith(".jar")) { libraryPath += File.pathSeparator + libFolder.getAbsolutePath() + File.separator + list[j]; } } } */ //} // 3. then loop over the code[] and save each .java file for (int i = 0; i < codeCount; i++) { if (code[i].flavor == CPP || code[i].flavor == C || code[i].flavor == HEADER) { // no pre-processing services necessary for java files // just write the the contents of 'program' to a .java file // into the build directory. uses byte stream and reader/writer // shtuff so that unicode bunk is properly handled String filename = code[i].name + flavorExtensionsReal[code[i].flavor]; try { Base.saveFile(code[i].program, new File(buildPath, filename)); } catch (IOException e) { e.printStackTrace(); throw new RunnerException("Problem moving " + filename + " to the build folder"); } code[i].preprocName = filename; } } // compile the program. errors will happen as a RunnerException // that will bubble up to whomever called build(). // // note: this has been changed to catch build exceptions, adjust // line number for number of included prototypes, and rethrow Compiler compiler = new Compiler(); boolean success; try { success = compiler.compile(this, buildPath, target); } catch (RunnerException re) { throw new RunnerException(re.getMessage(), re.file, re.line - preprocessor.prototypeCount - preprocessor.headerCount, re.column); } catch (Exception ex) { // TODO better method for handling this? throw new RunnerException(ex.toString()); } //System.out.println("success = " + success + " ... " + primaryClassName); return success ? primaryClassName : null; } protected void size(String buildPath, String suggestedClassName) throws RunnerException { long size = 0; Sizer sizer = new Sizer(buildPath, suggestedClassName); try { size = sizer.computeSize(); System.out.println("Binary sketch size: " + size + " bytes (of a " + Preferences.get("upload.maximum_size") + " byte maximum)"); } catch (RunnerException e) { System.err.println("Couldn't determine program size: " + e.getMessage()); } if (size > Preferences.getInteger("upload.maximum_size")) throw new RunnerException( "Sketch too big; try deleting code, removing floats, or see " + "http://www.arduino.cc/en/Main/FAQ for more advice."); } protected String upload(String buildPath, String suggestedClassName) throws RunnerException { // download the program // Uploader uploader = new Uploader(); // macos9 now officially broken.. see PdeCompilerJavac //PdeCompiler compiler = // ((PdeBase.platform == PdeBase.MACOS9) ? // new PdeCompilerJavac(buildPath, className, this) : // new PdeCompiler(buildPath, className, this)); // run the compiler, and funnel errors to the leechErr // which is a wrapped around // (this will catch and parse errors during compilation // the messageStream will call message() for 'compiler') //MessageStream messageStream = new MessageStream(downloader); //PrintStream leechErr = new PrintStream(messageStream); //boolean result = compiler.compileJava(leechErr); //return compiler.compileJava(leechErr); boolean success = uploader.uploadUsingPreferences(buildPath, suggestedClassName); return success ? suggestedClassName : null; } protected int countLines(String what) { char c[] = what.toCharArray(); int count = 0; for (int i = 0; i < c.length; i++) { if (c[i] == '\n') count++; } return count; } /** * Initiate export to applet. * <PRE> * +-------------------------------------------------------+ * + + * + Export to: [ Applet (for the web) + ] [ OK ] + * + + * + > Advanced + * + + * + - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + Version: [ Java 1.1 + ] + * + + * + Recommended version of Java when exporting applets. + * + - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + Version: [ Java 1.3 + ] + * + + * + Java 1.3 is not recommended for applets, + * + unless you are using features that require it. + * + Using a version of Java other than 1.1 will require + * + your Windows users to install the Java Plug-In, + * + and your Macintosh users to be running OS X. + * + - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + Version: [ Java 1.4 + ] + * + + * + identical message as 1.3 above... + * + + * +-------------------------------------------------------+ * </PRE> */ public boolean exportApplet(Target target) throws RunnerException { // make sure the user didn't hide the sketch folder ensureExistence(); current.program = editor.getText(); zipFileContents = new Hashtable(); // nuke the old applet folder because it can cause trouble File appletFolder = new File(folder, "applet"); Base.removeDir(appletFolder); appletFolder.mkdirs(); // build the sketch String foundName = build(target, appletFolder.getPath(), name); size(appletFolder.getPath(), name); foundName = upload(appletFolder.getPath(), name); // (already reported) error during export, exit this function if (foundName == null) return false; // if name != exportSketchName, then that's weirdness // BUG unfortunately, that can also be a bug in the preproc :( if (!name.equals(foundName)) { Base.showWarning("Error during export", "Sketch name is " + name + " but the sketch\n" + "name in the code was " + foundName, null); return false; } /* int wide = PApplet.DEFAULT_WIDTH; int high = PApplet.DEFAULT_HEIGHT; PatternMatcher matcher = new Perl5Matcher(); PatternCompiler compiler = new Perl5Compiler(); // this matches against any uses of the size() function, // whether they contain numbers of variables or whatever. // this way, no warning is shown if size() isn't actually // used in the applet, which is the case especially for // beginners that are cutting/pasting from the reference. // modified for 83 to match size(XXX, ddd so that it'll // properly handle size(200, 200) and size(200, 200, P3D) String sizing = "[\\s\\;]size\\s*\\(\\s*(\\S+)\\s*,\\s*(\\d+)"; Pattern pattern = compiler.compile(sizing); // adds a space at the beginning, in case size() is the very // first thing in the program (very common), since the regexp // needs to check for things in front of it. PatternMatcherInput input = new PatternMatcherInput(" " + code[0].program); if (matcher.contains(input, pattern)) { MatchResult result = matcher.getMatch(); try { wide = Integer.parseInt(result.group(1).toString()); high = Integer.parseInt(result.group(2).toString()); } catch (NumberFormatException e) { // found a reference to size, but it didn't // seem to contain numbers final String message = "The size of this applet could not automatically be\n" + "determined from your code. You'll have to edit the\n" + "HTML file to set the size of the applet."; Base.showWarning("Could not find applet size", message, null); } } // else no size() command found // originally tried to grab this with a regexp matcher, // but it wouldn't span over multiple lines for the match. // this could prolly be forced, but since that's the case // better just to parse by hand. StringBuffer dbuffer = new StringBuffer(); String lines[] = PApplet.split(code[0].program, '\n'); for (int i = 0; i < lines.length; i++) { if (lines[i].trim().startsWith("/**")) { // this is our comment */ // some smartass put the whole thing on the same line //if (lines[j].indexOf("*/") != -1) break; // for (int j = i+1; j < lines.length; j++) { // if (lines[j].trim().endsWith("*/")) { // remove the */ from the end, and any extra *s // in case there's also content on this line // nah, don't bother.. make them use the three lines // break; // } /* int offset = 0; while ((offset < lines[j].length()) && ((lines[j].charAt(offset) == '*') || (lines[j].charAt(offset) == ' '))) { offset++; } // insert the return into the html to help w/ line breaks dbuffer.append(lines[j].substring(offset) + "\n"); } } } String description = dbuffer.toString(); StringBuffer sources = new StringBuffer(); for (int i = 0; i < codeCount; i++) { sources.append("<a href=\"" + code[i].file.getName() + "\">" + code[i].name + "</a> "); } File htmlOutputFile = new File(appletFolder, "index.html"); FileOutputStream fos = new FileOutputStream(htmlOutputFile); PrintStream ps = new PrintStream(fos); // @@sketch@@, @@width@@, @@height@@, @@archive@@, @@source@@ // and now @@description@@ InputStream is = null; // if there is an applet.html file in the sketch folder, use that File customHtml = new File(folder, "applet.html"); if (customHtml.exists()) { is = new FileInputStream(customHtml); } if (is == null) { is = Base.getStream("applet.html"); } BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line = null; while ((line = reader.readLine()) != null) { if (line.indexOf("@@") != -1) { StringBuffer sb = new StringBuffer(line); int index = 0; while ((index = sb.indexOf("@@sketch@@")) != -1) { sb.replace(index, index + "@@sketch@@".length(), name); } while ((index = sb.indexOf("@@source@@")) != -1) { sb.replace(index, index + "@@source@@".length(), sources.toString()); } while ((index = sb.indexOf("@@archive@@")) != -1) { sb.replace(index, index + "@@archive@@".length(), name + ".jar"); } while ((index = sb.indexOf("@@width@@")) != -1) { sb.replace(index, index + "@@width@@".length(), String.valueOf(wide)); } while ((index = sb.indexOf("@@height@@")) != -1) { sb.replace(index, index + "@@height@@".length(), String.valueOf(high)); } while ((index = sb.indexOf("@@description@@")) != -1) { sb.replace(index, index + "@@description@@".length(), description); } line = sb.toString(); } ps.println(line); } reader.close(); ps.flush(); ps.close(); // copy the loading gif to the applet String LOADING_IMAGE = "loading.gif"; File loadingImage = new File(folder, LOADING_IMAGE); if (!loadingImage.exists()) { loadingImage = new File("lib", LOADING_IMAGE); } Base.copyFile(loadingImage, new File(appletFolder, LOADING_IMAGE)); */ // copy the source files to the target, since we like // to encourage people to share their code for (int i = 0; i < codeCount; i++) { try { Base.copyFile(code[i].file, new File(appletFolder, code[i].file.getName())); } catch (IOException e) { e.printStackTrace(); } } /* // create new .jar file FileOutputStream zipOutputFile = new FileOutputStream(new File(appletFolder, name + ".jar")); ZipOutputStream zos = new ZipOutputStream(zipOutputFile); ZipEntry entry; // add the manifest file addManifest(zos); // add the contents of the code folder to the jar // unpacks all jar files //File codeFolder = new File(folder, "code"); if (codeFolder.exists()) { String includes = Compiler.contentsToClassPath(codeFolder); packClassPathIntoZipFile(includes, zos); } // add contents of 'library' folders to the jar file // if a file called 'export.txt' is in there, it contains // a list of the files that should be exported. // otherwise, all files are exported. Enumeration en = importedLibraries.elements(); while (en.hasMoreElements()) { // in the list is a File object that points the // library sketch's "library" folder File libraryFolder = (File)en.nextElement(); File exportSettings = new File(libraryFolder, "export.txt"); String exportList[] = null; if (exportSettings.exists()) { String info[] = Base.loadStrings(exportSettings); for (int i = 0; i < info.length; i++) { if (info[i].startsWith("applet")) { int idx = info[i].indexOf('='); // get applet= or applet = String commas = info[i].substring(idx+1).trim(); exportList = PApplet.split(commas, ", "); } } } else { exportList = libraryFolder.list(); } for (int i = 0; i < exportList.length; i++) { if (exportList[i].equals(".") || exportList[i].equals("..")) continue; exportList[i] = PApplet.trim(exportList[i]); if (exportList[i].equals("")) continue; File exportFile = new File(libraryFolder, exportList[i]); if (!exportFile.exists()) { System.err.println("File " + exportList[i] + " does not exist"); } else if (exportFile.isDirectory()) { System.err.println("Ignoring sub-folder \"" + exportList[i] + "\""); } else if (exportFile.getName().toLowerCase().endsWith(".zip") || exportFile.getName().toLowerCase().endsWith(".jar")) { packClassPathIntoZipFile(exportFile.getAbsolutePath(), zos); } else { // just copy the file over.. prolly a .dll or something Base.copyFile(exportFile, new File(appletFolder, exportFile.getName())); } } } */ /* String bagelJar = "lib/core.jar"; packClassPathIntoZipFile(bagelJar, zos); // files to include from data directory // TODO this needs to be recursive if (dataFolder.exists()) { String dataFiles[] = dataFolder.list(); for (int i = 0; i < dataFiles.length; i++) { // don't export hidden files // skipping dot prefix removes all: . .. .DS_Store if (dataFiles[i].charAt(0) == '.') continue; entry = new ZipEntry(dataFiles[i]); zos.putNextEntry(entry); zos.write(Base.grabFile(new File(dataFolder, dataFiles[i]))); zos.closeEntry(); } } // add the project's .class files to the jar // just grabs everything from the build directory // since there may be some inner classes // (add any .class files from the applet dir, then delete them) // TODO this needs to be recursive (for packages) String classfiles[] = appletFolder.list(); for (int i = 0; i < classfiles.length; i++) { if (classfiles[i].endsWith(".class")) { entry = new ZipEntry(classfiles[i]); zos.putNextEntry(entry); zos.write(Base.grabFile(new File(appletFolder, classfiles[i]))); zos.closeEntry(); } } */ String classfiles[] = appletFolder.list(); // remove the .class files from the applet folder. if they're not // removed, the msjvm will complain about an illegal access error, // since the classes are outside the jar file. for (int i = 0; i < classfiles.length; i++) { if (classfiles[i].endsWith(".class")) { File deadguy = new File(appletFolder, classfiles[i]); if (!deadguy.delete()) { Base.showWarning("Could not delete", classfiles[i] + " could not \n" + "be deleted from the applet folder. \n" + "You'll need to remove it by hand.", null); } } } // close up the jar file /* zos.flush(); zos.close(); */ if(Preferences.getBoolean("uploader.open_folder")) Base.openFolder(appletFolder); return true; } /** * Export to application. * <PRE> * +-------------------------------------------------------+ * + + * + Export to: [ Application + ] [ OK ] + * + + * + > Advanced + * + - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + Version: [ Java 1.1 + ] + * + + * + Not much point to using Java 1.1 for applications. + * + To run applications, all users will have to + * + install Java, in which case they'll most likely + * + have version 1.3 or later. + * + - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + Version: [ Java 1.3 + ] + * + + * + Java 1.3 is the recommended setting for exporting + * + applications. Applications will run on any Windows + * + or Unix machine with Java installed. Mac OS X has + * + Java installed with the operation system, so there + * + is no additional installation will be required. + * + + * + - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + + * + Platform: [ Mac OS X + ] <-- defaults to current platform * + + * + Exports the application as a double-clickable + * + .app package, compatible with Mac OS X. + * + - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + Platform: [ Windows + ] + * + + * + Exports the application as a double-clickable + * + .exe and a handful of supporting files. + * + - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + Platform: [ jar file + ] + * + + * + A jar file can be used on any platform that has + * + Java installed. Simply doube-click the jar (or type + * + "java -jar sketch.jar" at a command prompt) to run + * + the application. It is the least fancy method for + * + exporting. + * + + * +-------------------------------------------------------+ * </PRE> */ public boolean exportApplication() { return true; } /* public void addManifest(ZipOutputStream zos) throws IOException { ZipEntry entry = new ZipEntry("META-INF/MANIFEST.MF"); zos.putNextEntry(entry); String contents = "Manifest-Version: 1.0\n" + "Created-By: Processing " + Base.VERSION_NAME + "\n" + "Main-Class: " + name + "\n"; // TODO not package friendly zos.write(contents.getBytes()); zos.closeEntry(); */ /* for (int i = 0; i < bagelClasses.length; i++) { if (!bagelClasses[i].endsWith(".class")) continue; entry = new ZipEntry(bagelClasses[i]); zos.putNextEntry(entry); zos.write(Base.grabFile(new File(exportDir + bagelClasses[i]))); zos.closeEntry(); } */ /* } */ /** * Slurps up .class files from a colon (or semicolon on windows) * separated list of paths and adds them to a ZipOutputStream. */ /* public void packClassPathIntoZipFile(String path, ZipOutputStream zos) throws IOException { String pieces[] = PApplet.split(path, File.pathSeparatorChar); for (int i = 0; i < pieces.length; i++) { if (pieces[i].length() == 0) continue; //System.out.println("checking piece " + pieces[i]); // is it a jar file or directory? if (pieces[i].toLowerCase().endsWith(".jar") || pieces[i].toLowerCase().endsWith(".zip")) { try { ZipFile file = new ZipFile(pieces[i]); Enumeration entries = file.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (entry.isDirectory()) { // actually 'continue's for all dir entries } else { String entryName = entry.getName(); // ignore contents of the META-INF folders if (entryName.indexOf("META-INF") == 0) continue; // don't allow duplicate entries if (zipFileContents.get(entryName) != null) continue; zipFileContents.put(entryName, new Object()); ZipEntry entree = new ZipEntry(entryName); zos.putNextEntry(entree); byte buffer[] = new byte[(int) entry.getSize()]; InputStream is = file.getInputStream(entry); int offset = 0; int remaining = buffer.length; while (remaining > 0) { int count = is.read(buffer, offset, remaining); offset += count; remaining -= count; } zos.write(buffer); zos.flush(); zos.closeEntry(); } } } catch (IOException e) { System.err.println("Error in file " + pieces[i]); e.printStackTrace(); } } else { // not a .jar or .zip, prolly a directory File dir = new File(pieces[i]); // but must be a dir, since it's one of several paths // just need to check if it exists if (dir.exists()) { packClassPathIntoZipFileRecursive(dir, null, zos); } } } } */ /** * Continue the process of magical exporting. This function * can be called recursively to walk through folders looking * for more goodies that will be added to the ZipOutputStream. */ /* static public void packClassPathIntoZipFileRecursive(File dir, String sofar, ZipOutputStream zos) throws IOException { String files[] = dir.list(); for (int i = 0; i < files.length; i++) { // ignore . .. and .DS_Store if (files[i].charAt(0) == '.') continue; File sub = new File(dir, files[i]); String nowfar = (sofar == null) ? files[i] : (sofar + "/" + files[i]); if (sub.isDirectory()) { packClassPathIntoZipFileRecursive(sub, nowfar, zos); } else { // don't add .jar and .zip files, since they only work // inside the root, and they're unpacked if (!files[i].toLowerCase().endsWith(".jar") && !files[i].toLowerCase().endsWith(".zip") && files[i].charAt(0) != '.') { ZipEntry entry = new ZipEntry(nowfar); zos.putNextEntry(entry); zos.write(Base.grabFile(sub)); zos.closeEntry(); } } } } */ /** * Make sure the sketch hasn't been moved or deleted by some * nefarious user. If they did, try to re-create it and save. * Only checks to see if the main folder is still around, * but not its contents. */ protected void ensureExistence() { if (folder.exists()) return; Base.showWarning("Sketch Disappeared", "The sketch folder has disappeared.\n " + "Will attempt to re-save in the same location,\n" + "but anything besides the code will be lost.", null); try { folder.mkdirs(); modified = true; for (int i = 0; i < codeCount; i++) { code[i].save(); // this will force a save } for (int i = 0; i < hiddenCount; i++) { hidden[i].save(); // this will force a save } calcModified(); } catch (Exception e) { Base.showWarning("Could not re-save sketch", "Could not properly re-save the sketch. " + "You may be in trouble at this point,\n" + "and it might be time to copy and paste " + "your code to another text editor.", e); } } /** * Returns true if this is a read-only sketch. Used for the * examples directory, or when sketches are loaded from read-only * volumes or folders without appropriate permissions. */ public boolean isReadOnly() { String apath = folder.getAbsolutePath(); if (apath.startsWith(Sketchbook.examplesPath) || apath.startsWith(Sketchbook.librariesPath)) { return true; // canWrite() doesn't work on directories //} else if (!folder.canWrite()) { } else { // check to see if each modified code file can be written to for (int i = 0; i < codeCount; i++) { if (code[i].modified && !code[i].file.canWrite() && code[i].file.exists()) { //System.err.println("found a read-only file " + code[i].file); return true; } } //return true; } return false; } /** * Returns path to the main .pde file for this sketch. */ public String getMainFilePath() { return code[0].file.getAbsolutePath(); } }
Quick hack to allow bigger code on the atmega168 (if build.mcu == atmega168, the upload.maximum_size gets doubled). Former-commit-id: 7fe87fe72437536c319de0b9fbea7d195c8072af
app/Sketch.java
Quick hack to allow bigger code on the atmega168 (if build.mcu == atmega168, the upload.maximum_size gets doubled).
Java
lgpl-2.1
5632bd6602f1953b4aeb21f4d23eb04eeef59d52
0
ekiwi/jade-mirror,ekiwi/jade-mirror,ekiwi/jade-mirror,ekiwi/jade-mirror
/***************************************************************** JADE - Java Agent DEvelopment Framework is a framework to develop multi-agent systems in compliance with the FIPA specifications. Copyright (C) 2000 CSELT S.p.A. GNU Lesser General Public License This library 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, version 2.1 of the License. This library 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 library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *****************************************************************/ package jade.lang.sl; import java.io.Writer; import java.io.StringWriter; import java.io.IOException; import jade.onto.Frame; import jade.onto.Ontology; import jade.onto.OntologyException; import jade.onto.TermDescriptor; /** @author Giovanni Rimassa - Universita` di Parma @version $Date$ $Revision$ */ class SL0Encoder { public String encode(Frame f, Ontology o) { StringWriter out = new StringWriter(); try { writeFrame(f, o, out); out.flush(); } catch(OntologyException oe) { oe.printStackTrace(); } catch(IOException ioe) { ioe.printStackTrace(); } return out.toString(); } private void writeFrame(Frame f, Ontology o, Writer w) throws OntologyException, IOException { String name = f.getName(); TermDescriptor[] terms = o.getTerms(name); if(o.isConcept(name)) writeConcept(name, f, o, terms, w); if(o.isAction(name)) writeAction(name, f, o, terms, w); if(o.isPredicate(name)) writePredicate(name, f, o, terms, w); } private void writeConcept(String name, Frame f, Ontology o, TermDescriptor[] terms, Writer w) throws OntologyException, IOException { w.write("( " + name + " "); for(int i = 0; i < terms.length; i++) { TermDescriptor current = terms[i]; String slotName = current.getName(); Object slotValue = f.getSlot(slotName); w.write("( "); w.write(slotName + " "); if(current.isComplex()) { Frame complexSlot = (Frame)slotValue; writeFrame(complexSlot, o, w); w.write(" "); } else { w.write(slotValue + " "); } w.write(" )"); } w.write(" )"); } private void writeAction(String name, Frame f, Ontology o, TermDescriptor[] terms, Writer w) throws OntologyException, IOException { String actor = (String)f.getSlot(":actor"); w.write("( action " + actor + " "); w.write("( " + name + " "); for(int i = 0; i < terms.length - 1; i++) { TermDescriptor current = terms[i]; Object slotValue = f.getSlot(i); if(current.isComplex()) { Frame complexSlot = (Frame)slotValue; writeFrame(complexSlot, o, w); w.write(" "); } else { w.write(slotValue + " "); } } w.write(" ) )"); } private void writePredicate(String name, Frame f, Ontology o, TermDescriptor[] terms, Writer w) throws OntologyException, IOException { w.write("( " + name + " "); for(int i = 0; i < terms.length; i++) { TermDescriptor current = terms[i]; Object slotValue = f.getSlot(i); if(current.isComplex()) { Frame complexSlot = (Frame)slotValue; writeFrame(complexSlot, o, w); w.write(" "); } else { w.write(slotValue + " "); } } w.write(" )"); } }
src/jade/lang/sl/SL0Encoder.java
/***************************************************************** JADE - Java Agent DEvelopment Framework is a framework to develop multi-agent systems in compliance with the FIPA specifications. Copyright (C) 2000 CSELT S.p.A. GNU Lesser General Public License This library 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, version 2.1 of the License. This library 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 library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *****************************************************************/ package jade.lang.sl; import java.io.Writer; import java.io.StringWriter; import java.io.IOException; import jade.onto.Frame; import jade.onto.Ontology; import jade.onto.OntologyException; import jade.onto.TermDescriptor; /** Javadoc documentation for the file @author Giovanni Rimassa - Universita` di Parma @version $Date$ $Revision$ */ class SL0Encoder { public String encode(Frame f, Ontology o) { StringWriter out = new StringWriter(); try { writeFrame(f, o, out); out.flush(); } catch(OntologyException oe) { oe.printStackTrace(); } catch(IOException ioe) { ioe.printStackTrace(); } return out.toString(); } private void writeFrame(Frame f, Ontology o, Writer w) throws OntologyException, IOException { String name = f.getName(); TermDescriptor[] terms = o.getTerms(name); if(o.isConcept(name)) writeConcept(name, f, o, terms, w); if(o.isAction(name)) writeAction(name, f, o, terms, w); if(o.isPredicate(name)) writePredicate(name, f, o, terms, w); } private void writeConcept(String name, Frame f, Ontology o, TermDescriptor[] terms, Writer w) throws OntologyException, IOException { w.write("( " + name + " "); for(int i = 0; i < terms.length; i++) { TermDescriptor current = terms[i]; String slotName = current.getName(); Object slotValue = f.getSlot(slotName); w.write("( "); w.write(slotName + " "); if(current.isComplex()) { Frame complexSlot = (Frame)slotValue; writeFrame(complexSlot, o, w); w.write(" "); } else { w.write(slotValue + " "); } w.write(" )"); } w.write(" )"); } private void writeAction(String name, Frame f, Ontology o, TermDescriptor[] terms, Writer w) throws OntologyException, IOException { String actor = (String)f.getSlot(":actor"); w.write("( action " + actor + " "); w.write("( " + name + " "); for(int i = 1; i < terms.length; i++) { TermDescriptor current = terms[i]; Object slotValue = f.getSlot(i); if(current.isComplex()) { Frame complexSlot = (Frame)slotValue; writeFrame(complexSlot, o, w); w.write(" "); } else { w.write(slotValue + " "); } } w.write(" ) )"); } private void writePredicate(String name, Frame f, Ontology o, TermDescriptor[] terms, Writer w) throws OntologyException, IOException { w.write("( " + name + " "); for(int i = 0; i < terms.length; i++) { TermDescriptor current = terms[i]; Object slotValue = f.getSlot(i); if(current.isComplex()) { Frame complexSlot = (Frame)slotValue; writeFrame(complexSlot, o, w); w.write(" "); } else { w.write(slotValue + " "); } } w.write(" )"); } }
corrected bug in writeAction
src/jade/lang/sl/SL0Encoder.java
corrected bug in writeAction
Java
apache-2.0
50553ae4c6cb4a90c6a8bc50e5a8977b11c84f01
0
reinert/requestor,reinert/requestor,reinert/requestor
/* * Copyright 2022 Danilo Reinert * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this FormData 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.reinert.requestor.net.serialization; import java.io.File; import java.io.InputStream; import java.net.URLConnection; import java.util.Collection; import java.util.Random; import io.reinert.requestor.core.FormData; import io.reinert.requestor.core.HttpSerializationContext; import io.reinert.requestor.core.header.ContentTypeHeader; import io.reinert.requestor.core.header.Param; import io.reinert.requestor.core.payload.SerializedPayload; import io.reinert.requestor.core.payload.TextSerializedPayload; import io.reinert.requestor.core.serialization.DeserializationContext; import io.reinert.requestor.core.serialization.SerializationContext; import io.reinert.requestor.core.serialization.SerializationException; import io.reinert.requestor.core.serialization.Serializer; import io.reinert.requestor.net.payload.CompositeSerializedPayload; /** * InputStream serializer for FormDatas. * * @author Danilo Reinert */ public class FormDataMultiPartSerializer implements Serializer<FormData> { public static final String LINE_FEED = "\r\n"; public static final String MULTIPART_FORM_DATA = "multipart/form-data"; public static String[] MEDIA_TYPE_PATTERNS = new String[]{MULTIPART_FORM_DATA}; private static final FormDataMultiPartSerializer INSTANCE = new FormDataMultiPartSerializer(); public static FormDataMultiPartSerializer getInstance() { return INSTANCE; } @Override public Class<FormData> handledType() { return FormData.class; } @Override public String[] mediaType() { return MEDIA_TYPE_PATTERNS; } @Override public SerializedPayload serialize(FormData formData, SerializationContext context) { if (formData == null || formData.isEmpty()) return SerializedPayload.EMPTY_PAYLOAD; final String boundary = "----RequestorFormBoundary" + generateRandomString(16); final String charset = context.getCharset(); ((HttpSerializationContext) context).getRequest().setContentType( new ContentTypeHeader(MULTIPART_FORM_DATA, Param.of("boundary", boundary))); if (formData.isPlain()) { final StringBuilder sb = new StringBuilder(); for (FormData.Param param : formData) { if (param == null) continue; Object value = param.getValue(); String name = param.getName(); checkNameNotNull(name); checkValueNotNull(value, name); addFormField(sb, boundary, name, (String) value, charset); } sb.append("--").append(boundary).append("--").append(LINE_FEED); return new TextSerializedPayload(sb.toString(), charset); } final CompositeSerializedPayload csp = new CompositeSerializedPayload(); for (FormData.Param param : formData) { if (param == null) continue; Object value = param.getValue(); String name = param.getName(); checkNameNotNull(name); checkValueNotNull(value, name); if (value instanceof String) { addFormField(csp, boundary, name, (String) value, charset); } else if (value instanceof File) { File file = (File) value; String fileName = param.getFileName() != null ? param.getFileName() : file.getName(); addFilePart(csp, boundary, name, file, fileName, context); } else if (value instanceof InputStream) { String fileName = param.getFileName() != null ? param.getFileName() : generateRandomString(8); addStreamPart(csp, boundary, name, (InputStream) value, fileName, context); } else { throw new SerializationException("Cannot serialize an instance of " + value.getClass().getName() + " as part of a multipart/form-data serialized payload."); } } csp.add(new TextSerializedPayload(LINE_FEED + "--" + boundary + "--" + LINE_FEED, charset)); return csp; } private void checkValueNotNull(Object value, String name) { if (value == null) { throw new SerializationException("Cannot serialized a null FormData param." + " The value associated with the name '" + name + "' is null."); } } private void checkNameNotNull(String name) { if (name == null) { throw new SerializationException("Cannot serialized a FormData param with name equals to null."); } } @Override public SerializedPayload serialize(Collection<FormData> c, SerializationContext context) { throw new UnsupportedOperationException("Cannot serialize a collection of FormData."); } @Override public FormData deserialize(SerializedPayload payload, DeserializationContext context) { throw new UnsupportedOperationException("Cannot deserialize to a FormData."); } @Override public <C extends Collection<FormData>> C deserialize(Class<C> collectionType, SerializedPayload payload, DeserializationContext context) { throw new UnsupportedOperationException("Cannot deserialize to a collection of FormData."); } public void addFormField(StringBuilder sb, String boundary, String name, String value, String charset) { sb.append("--").append(boundary) .append(LINE_FEED) .append("Content-Disposition: form-data; name=\"").append(name).append('"') .append(LINE_FEED) .append("Content-Type: text/plain; charset=").append(charset) .append(LINE_FEED) .append(LINE_FEED) .append(value) .append(LINE_FEED); } public void addFormField(CompositeSerializedPayload csp, String boundary, String name, String value, String charset) { addPart(csp, boundary, name, null, "text/plain; charset=" + charset, null, value, charset); } public void addStreamPart(CompositeSerializedPayload csp, String boundary, String fieldName, InputStream in, String fileName, SerializationContext context) { String contentType = URLConnection.guessContentTypeFromName(fileName); addPart(csp, boundary, fieldName, fileName, contentType, "binary", null, context.getCharset()); csp.add(InputStreamSerializer.getInstance().serialize(in, context)); } public void addFilePart(CompositeSerializedPayload csp, String boundary, String fieldName, File file, String fileName, SerializationContext context) { String contentType = URLConnection.guessContentTypeFromName(fileName); addPart(csp, boundary, fieldName, fileName, contentType, "binary", null, context.getCharset()); csp.add(FileSerializer.getInstance().serialize(file, context)); } private void addPart(CompositeSerializedPayload csp, String boundary, String fieldName, String fileName, String contentType, String contentEncoding, String value, String charset) { csp.add(new TextSerializedPayload((csp.isEmpty() ? "--" : LINE_FEED + "--") + boundary + LINE_FEED + "Content-Disposition: form-data; name=\"" + fieldName + (fileName != null ? "\"; filename=\"" + fileName + '"' : '"') + LINE_FEED + ((contentType != null && !contentType.isEmpty()) ? "Content-Type: " + contentType + LINE_FEED : "") + (contentEncoding != null ? "Content-Transfer-Encoding: " + contentEncoding + LINE_FEED : "") + LINE_FEED + (value != null ? value : ""), charset)); } private static String generateRandomString(int length) { return new Random().ints(48, 123) .filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97)) .limit(length) .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString(); } }
requestor/impl/requestor-net/src/main/java/io/reinert/requestor/net/serialization/FormDataMultiPartSerializer.java
/* * Copyright 2022 Danilo Reinert * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this FormData 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.reinert.requestor.net.serialization; import java.io.File; import java.io.InputStream; import java.net.URLConnection; import java.util.Collection; import java.util.Random; import io.reinert.requestor.core.FormData; import io.reinert.requestor.core.HttpSerializationContext; import io.reinert.requestor.core.header.ContentTypeHeader; import io.reinert.requestor.core.header.Param; import io.reinert.requestor.core.payload.SerializedPayload; import io.reinert.requestor.core.payload.TextSerializedPayload; import io.reinert.requestor.core.serialization.DeserializationContext; import io.reinert.requestor.core.serialization.SerializationContext; import io.reinert.requestor.core.serialization.SerializationException; import io.reinert.requestor.core.serialization.Serializer; import io.reinert.requestor.net.payload.CompositeSerializedPayload; /** * InputStream serializer for FormDatas. * * @author Danilo Reinert */ public class FormDataMultiPartSerializer implements Serializer<FormData> { public static String LINE_FEED = "\r\n"; public static String CHARSET = "UTF-8"; public static final String MULTIPART_FORM_DATA = "multipart/form-data"; public static String[] MEDIA_TYPE_PATTERNS = new String[]{MULTIPART_FORM_DATA}; private static final FormDataMultiPartSerializer INSTANCE = new FormDataMultiPartSerializer(); public static FormDataMultiPartSerializer getInstance() { return INSTANCE; } @Override public Class<FormData> handledType() { return FormData.class; } @Override public String[] mediaType() { return MEDIA_TYPE_PATTERNS; } @Override public SerializedPayload serialize(FormData formData, SerializationContext context) { if (formData == null || formData.isEmpty()) return SerializedPayload.EMPTY_PAYLOAD; final String boundary = "----RequestorFormBoundary" + generateRandomString(16); ((HttpSerializationContext) context).getRequest().setContentType( new ContentTypeHeader(MULTIPART_FORM_DATA, Param.of("boundary", boundary))); if (formData.isPlain()) { final StringBuilder sb = new StringBuilder(); for (FormData.Param param : formData) { if (param == null) continue; Object value = param.getValue(); String name = param.getName(); checkNameNotNull(name); checkValueNotNull(value, name); addFormField(sb, boundary, name, (String) value); } sb.append("--").append(boundary).append("--").append(LINE_FEED); return new TextSerializedPayload(sb.toString(), CHARSET); } final CompositeSerializedPayload csp = new CompositeSerializedPayload(); for (FormData.Param param : formData) { if (param == null) continue; Object value = param.getValue(); String name = param.getName(); checkNameNotNull(name); checkValueNotNull(value, name); if (value instanceof String) { addFormField(csp, boundary, name, (String) value); } else if (value instanceof File) { File file = (File) value; String fileName = param.getFileName() != null ? param.getFileName() : file.getName(); addFilePart(csp, boundary, name, file, fileName, context); } else if (value instanceof InputStream) { String fileName = param.getFileName() != null ? param.getFileName() : generateRandomString(8); addStreamPart(csp, boundary, name, (InputStream) value, fileName, context); } else { throw new SerializationException("Cannot serialize an instance of " + value.getClass().getName() + " as part of a multipart/form-data serialized payload."); } } csp.add(new TextSerializedPayload(LINE_FEED + "--" + boundary + "--" + LINE_FEED)); return csp; } private void checkValueNotNull(Object value, String name) { if (value == null) { throw new SerializationException("Cannot serialized a null FormData param." + " The value associated with the name '" + name + "' is null."); } } private void checkNameNotNull(String name) { if (name == null) { throw new SerializationException("Cannot serialized a FormData param with name equals to null."); } } @Override public SerializedPayload serialize(Collection<FormData> c, SerializationContext context) { throw new UnsupportedOperationException("Cannot serialize a collection of FormData."); } @Override public FormData deserialize(SerializedPayload payload, DeserializationContext context) { throw new UnsupportedOperationException("Cannot deserialize to a FormData."); } @Override public <C extends Collection<FormData>> C deserialize(Class<C> collectionType, SerializedPayload payload, DeserializationContext context) { throw new UnsupportedOperationException("Cannot deserialize to a collection of FormData."); } public void addFormField(StringBuilder sb, String boundary, String name, String value) { sb.append("--").append(boundary) .append(LINE_FEED) .append("Content-Disposition: form-data; name=\"").append(name).append('"') .append(LINE_FEED) .append("Content-Type: text/plain; charset=").append(CHARSET) .append(LINE_FEED) .append(LINE_FEED) .append(value) .append(LINE_FEED); } public void addFormField(CompositeSerializedPayload csp, String boundary, String name, String value) { addPart(csp, boundary, name, null, "text/plain; charset=" + CHARSET, null, value); } public void addStreamPart(CompositeSerializedPayload csp, String boundary, String fieldName, InputStream in, String fileName, SerializationContext context) { String contentType = URLConnection.guessContentTypeFromName(fileName); addPart(csp, boundary, fieldName, fileName, contentType, "binary", null); csp.add(InputStreamSerializer.getInstance().serialize(in, context)); } public void addFilePart(CompositeSerializedPayload csp, String boundary, String fieldName, File file, String fileName, SerializationContext context) { String contentType = URLConnection.guessContentTypeFromName(fileName); addPart(csp, boundary, fieldName, fileName, contentType, "binary", null); csp.add(FileSerializer.getInstance().serialize(file, context)); } private void addPart(CompositeSerializedPayload csp, String boundary, String fieldName, String fileName, String contentType, String contentEncoding, String value) { csp.add(new TextSerializedPayload((csp.isEmpty() ? "--" : LINE_FEED + "--") + boundary + LINE_FEED + "Content-Disposition: form-data; name=\"" + fieldName + (fileName != null ? "\"; filename=\"" + fileName + '"' : '"') + LINE_FEED + ((contentType != null && !contentType.isEmpty()) ? "Content-Type: " + contentType + LINE_FEED : "") + (contentEncoding != null ? "Content-Transfer-Encoding: " + contentEncoding + LINE_FEED : "") + LINE_FEED + (value != null ? value : ""))); } private static String generateRandomString(int length) { return new Random().ints(48, 123) .filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97)) .limit(length) .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString(); } }
#92 [api] Get charset from request in FormDataMultiPartSerializer
requestor/impl/requestor-net/src/main/java/io/reinert/requestor/net/serialization/FormDataMultiPartSerializer.java
#92 [api] Get charset from request in FormDataMultiPartSerializer
Java
apache-2.0
354439f3c5594d49263eaa94405fe158c1ed4d92
0
incodehq/isis,incodehq/isis,apache/isis,apache/isis,estatio/isis,incodehq/isis,apache/isis,apache/isis,estatio/isis,estatio/isis,apache/isis,estatio/isis,incodehq/isis,apache/isis
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.isis.core.metamodel.facets.members.cssclassfa.annotprop; import java.lang.reflect.Method; import org.apache.isis.applib.annotation.Mixin; import org.apache.isis.core.metamodel.facets.Annotations; import org.apache.isis.core.metamodel.specloader.specimpl.ObjectMemberAbstract; /** * To solve <a href="https://issues.apache.org/jira/browse/ISIS-1743">ISIS-1743</a>.<br/> * Could be better integrated into Isis' meta-model. * * @author [email protected] */ class MixinInterceptor { /** * If method originates from a mixin then we infer the intended name * from the mixin's class name. * * @param method within the mixin type itself. * @return the intended name of the method */ static String intendedNameOf(Method method) { final Class<?> declaringClass = method.getDeclaringClass(); final Mixin mixin = Annotations.getAnnotation(declaringClass, Mixin.class); if(mixin != null) { final String methodName = method.getName(); final String mixinAnnotMethodName = mixin.method(); if(mixinAnnotMethodName.equals(methodName)) { final String mixinMethodName = ObjectMemberAbstract.deriveMemberNameFrom(method.getDeclaringClass().getName()); if(mixinMethodName!=null) { return mixinMethodName; } } } // default behavior return method.getName(); } }
core/metamodel/src/main/java/org/apache/isis/core/metamodel/facets/members/cssclassfa/annotprop/MixinInterceptor.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.isis.core.metamodel.facets.members.cssclassfa.annotprop; import java.lang.reflect.Method; import java.util.List; import java.util.Optional; import org.apache.isis.applib.annotation.Mixin; import org.apache.isis.core.metamodel.facets.Annotations; import org.apache.isis.core.metamodel.specloader.specimpl.ObjectMemberAbstract; /** * To solve <a href="https://issues.apache.org/jira/browse/ISIS-1743">ISIS-1743</a>.<br/> * Could be better integrated into Isis' meta-model. * * @author [email protected] */ class MixinInterceptor { /** * If method originates from a mixin then we infer the intended name * from the mixin's class name. * * @param method within the mixin type itself. * @return the intended name of the method */ static String intendedNameOf(Method method) { final Class<?> declaringClass = method.getDeclaringClass(); final Mixin mixin = Annotations.getAnnotation(declaringClass, Mixin.class); if(mixin != null) { final String methodName = method.getName(); final String mixinAnnotMethodName = mixin.method(); if(mixinAnnotMethodName.equals(methodName)) { final String mixinMethodName = ObjectMemberAbstract.deriveMemberNameFrom(method.getDeclaringClass().getName()); if(mixinMethodName!=null) { return mixinMethodName; } } } // default behavior return method.getName(); } }
ISIS-1813: fixes java7/8 compilation issue (unused import from Java 8)
core/metamodel/src/main/java/org/apache/isis/core/metamodel/facets/members/cssclassfa/annotprop/MixinInterceptor.java
ISIS-1813: fixes java7/8 compilation issue (unused import from Java 8)
Java
apache-2.0
0688946cc279030d8bc3c710f6c1415b13f75dfb
0
subutai-io/Subutai,subutai-io/base,subutai-io/Subutai,subutai-io/base,subutai-io/Subutai,subutai-io/Subutai,subutai-io/base,subutai-io/Subutai,subutai-io/base,subutai-io/Subutai
package org.safehaus.kiskis.mgmt.server.ui.modules.hadoop.datanode; import com.vaadin.terminal.Sizeable; import com.vaadin.ui.*; import org.safehaus.kiskis.mgmt.server.ui.modules.hadoop.HadoopModule; import org.safehaus.kiskis.mgmt.server.ui.modules.hadoop.install.Commands; import org.safehaus.kiskis.mgmt.shared.protocol.*; import org.safehaus.kiskis.mgmt.api.agentmanager.AgentManager; import org.safehaus.kiskis.mgmt.shared.protocol.enums.TaskStatus; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import org.safehaus.kiskis.mgmt.api.taskrunner.TaskCallback; import org.safehaus.kiskis.mgmt.server.ui.modules.hadoop.HadoopDAO; import org.safehaus.kiskis.mgmt.server.ui.modules.hadoop.common.TaskType; import org.safehaus.kiskis.mgmt.server.ui.modules.hadoop.common.TaskUtil; public final class DataNodesWindow extends Window implements TaskCallback { private Button startButton, stopButton, restartButton, addButton; private Label statusLabel; private AgentsComboBox agentsComboBox; private DataNodesTable dataNodesTable; private List<String> keys; private HadoopClusterInfo cluster; private final DataNodesWindow INSTANCE; private Map<UUID, String> hostss; public DataNodesWindow(String clusterName) { INSTANCE = this; setModal(true); setCaption("Hadoop Data Node Configuration"); this.cluster = HadoopDAO.getHadoopClusterInfo(clusterName); VerticalLayout verticalLayout = new VerticalLayout(); verticalLayout.setWidth(900, Sizeable.UNITS_PIXELS); verticalLayout.setHeight(450, Sizeable.UNITS_PIXELS); HorizontalLayout buttonLayout = new HorizontalLayout(); buttonLayout.setSpacing(true); buttonLayout.addComponent(getStartButton()); buttonLayout.addComponent(getStopButton()); buttonLayout.addComponent(getRestartButton()); buttonLayout.addComponent(getStatusLabel()); /*HorizontalLayout agentsLayout = new HorizontalLayout(); agentsLayout.setSpacing(true); agentsComboBox = new AgentsComboBox(clusterName); agentsLayout.addComponent(agentsComboBox); agentsLayout.addComponent(getAddButton());*/ Panel panel = new Panel(); panel.setSizeFull(); panel.addComponent(buttonLayout); // panel.addComponent(agentsLayout); panel.addComponent(getTable()); verticalLayout.addComponent(panel); setContent(verticalLayout); getStatus(); } private Button getStartButton() { startButton = new Button("Start"); startButton.setEnabled(false); startButton.addListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { Agent master = cluster.getNameNode(); HashMap<String, String> map = new HashMap<String, String>(); map.put(":source", HadoopModule.MODULE_NAME); map.put(":uuid", master.getUuid().toString()); map.put(":command", "start"); TaskUtil.createRequest(Commands.COMMAND_NAME_NODE, "Start Hadoop Cluster", map, INSTANCE, TaskType.START); disableButtons(0); } }); return startButton; } private Button getStopButton() { stopButton = new Button("Stop"); stopButton.setEnabled(false); stopButton.addListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { Agent master = cluster.getNameNode(); HashMap<String, String> map = new HashMap<String, String>(); map.put(":source", HadoopModule.MODULE_NAME); map.put(":uuid", master.getUuid().toString()); map.put(":command", "stop"); TaskUtil.createRequest(Commands.COMMAND_NAME_NODE, "Stop Hadoop Cluster", map, INSTANCE, TaskType.STOP); disableButtons(0); } }); return stopButton; } private Button getRestartButton() { restartButton = new Button("Restart"); restartButton.setEnabled(false); restartButton.addListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { Agent master = cluster.getNameNode(); HashMap<String, String> map = new HashMap<String, String>(); map.put(":source", HadoopModule.MODULE_NAME); map.put(":uuid", master.getUuid().toString()); map.put(":command", "restart"); TaskUtil.createRequest(Commands.COMMAND_NAME_NODE, "Restart Hadoop Cluster", map, INSTANCE, TaskType.RESTART); disableButtons(0); } }); return restartButton; } private void disableButtons(int status) { startButton.setEnabled(false); stopButton.setEnabled(false); restartButton.setEnabled(false); if (status == 1) { stopButton.setEnabled(true); restartButton.setEnabled(true); } if (status == 2) { startButton.setEnabled(true); } } private Button getAddButton() { addButton = new Button("Add"); addButton.addListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { cluster = HadoopDAO.getHadoopClusterInfo(cluster.getClusterName()); Agent agent = (Agent) agentsComboBox.getValue(); // cluster.getDataNodes().add(agent.getUuid()); List<Agent> list = new ArrayList<Agent>(); list.addAll(cluster.getDataNodes()); list.add(agent); cluster.setDataNodes(list); addButton.setEnabled(false); configureNode(); } }); return addButton; } private void getStatus() { Agent master = cluster.getNameNode(); HashMap<String, String> map = new HashMap<String, String>(); map.put(":source", HadoopModule.MODULE_NAME); map.put(":uuid", master.getUuid().toString()); TaskUtil.createRequest(Commands.STATUS_DATA_NODE, "Get status for Hadoop Data Node", map, INSTANCE, TaskType.STATUS); dataNodesTable.refreshDataSource(); } private void configureNode() { keys = new ArrayList<String>(); HashMap<String, String> map = new HashMap<String, String>(); map.put(":source", HadoopModule.MODULE_NAME); map.put(":uuid", cluster.getNameNode().toString()); TaskUtil.createRequest(Commands.COPY_MASTER_KEY, "Configuring new node on Hadoop Cluster", map, INSTANCE, TaskType.CONFIGURE); if (!cluster.getNameNode().equals(cluster.getSecondaryNameNode())) { map = new HashMap<String, String>(); map.put(":source", HadoopModule.MODULE_NAME); map.put(":uuid", cluster.getSecondaryNameNode().toString()); TaskUtil.createRequest(Commands.COPY_MASTER_KEY, "Configuring new node on Hadoop Cluster", map, INSTANCE, TaskType.CONFIGURE); } if (!cluster.getJobTracker().equals(cluster.getNameNode()) && !cluster.getJobTracker().equals(cluster.getSecondaryNameNode())) { map = new HashMap<String, String>(); map.put(":source", HadoopModule.MODULE_NAME); map.put(":uuid", cluster.getJobTracker().toString()); TaskUtil.createRequest(Commands.COPY_MASTER_KEY, "Configuring new node on Hadoop Cluster", map, INSTANCE, TaskType.CONFIGURE); } } private void addNode() { Agent agent = (Agent) agentsComboBox.getValue(); for (String key : keys) { HashMap<String, String> map = new HashMap<String, String>(); map.put(":source", HadoopModule.MODULE_NAME); map.put(":uuid", agent.getUuid().toString()); map.put(":PUB_KEY", key); TaskUtil.createRequest(Commands.PASTE_MASTER_KEY, "Adding data node to Hadoop Cluster", map, INSTANCE, TaskType.ADD); } HashMap<String, String> map = new HashMap<String, String>(); map.put(":source", HadoopModule.MODULE_NAME); map.put(":uuid", agent.getUuid().toString()); TaskUtil.createRequest(Commands.INSTALL_DEB, "Adding data node to Hadoop Cluster", map, INSTANCE, TaskType.ADD); map = new HashMap<String, String>(); map.put(":source", HadoopModule.MODULE_NAME); map.put(":uuid", cluster.getNameNode().getUuid().toString()); map.put(":slave-hostname", agent.getHostname()); TaskUtil.createRequest(Commands.ADD_DATA_NODE, "Adding data node to Hadoop Cluster", map, INSTANCE, TaskType.ADD); for (Agent agentDataNode : cluster.getDataNodes()) { map = new HashMap<String, String>(); map.put(":source", HadoopModule.MODULE_NAME); map.put(":uuid", cluster.getNameNode().getUuid().toString()); map.put(":IP", agentDataNode.getHostname()); TaskUtil.createRequest(Commands.INCLUDE_DATA_NODE, "Adding data node to Hadoop Cluster", map, INSTANCE, TaskType.ADD); } /*map = new HashMap<String, String>(); map.put(":source", HadoopModule.MODULE_NAME); map.put(":uuid", agent.getUuid().toString()); // map.put(":uuid", getAgentManager().getAgent(cluster.getNameNode()).getUuid().toString()); createRequest(getCommandManager(), Commands.START_DATA_NODE, addTask, map);*/ } public void readHosts() { hostss = new HashMap<UUID, String>(); for (Agent agent : getAllNodes()) { HashMap<String, String> map = new HashMap<String, String>(); map.put(":source", HadoopModule.MODULE_NAME); map.put(":uuid", agent.getUuid().toString()); TaskUtil.createRequest(Commands.READ_HOSTNAME, "Read /etc/hosts file", map, INSTANCE, TaskType.READ_HOSTS); } } public void writeHosts(Map<UUID, String> hostss) { for (Map.Entry<UUID, String> host : hostss.entrySet()) { Agent agent = getAgentManager().getAgentByUUID(host.getKey()); String hosts = editHosts(host.getValue(), agent); HashMap<String, String> map = new HashMap<String, String>(); map.put(":source", HadoopModule.MODULE_NAME); map.put(":uuid", agent.getUuid().toString()); map.put(":hosts", hosts); TaskUtil.createRequest(Commands.WRITE_HOSTNAME, "Write /etc/hosts file", map, INSTANCE, TaskType.WRITE_HOSTS); } /*HashMap<String, String> map = new HashMap<String, String>(); map.put(":source", HadoopModule.MODULE_NAME); map.put(":uuid", getAgentManager().getAgent(cluster.getNameNode()).getUuid().toString()); createRequest(getCommandManager(), Commands.REFRESH_DATA_NODES, hadoopWriteHosts, map);*/ } private String editHosts(String input, Agent localAgent) { StringBuilder result = new StringBuilder(); String[] hosts = input.split("\n"); for (String host : hosts) { host = host.trim(); boolean isContains = false; for (Agent agent : getAllNodes()) { if (host.contains(agent.getHostname()) || host.contains("localhost") || host.contains(localAgent.getHostname()) || host.contains(localAgent.getListIP().get(0))) { isContains = true; } } if (!isContains) { result.append(host); result.append("\n"); } } for (Agent agent : getAllNodes()) { result.append(agent.getListIP().get(0)); result.append("\t"); result.append(agent.getHostname()); result.append("."); result.append(cluster.getIpMask()); result.append("\t"); result.append(agent.getHostname()); result.append("\n"); } result.append("127.0.0.1\tlocalhost"); return result.toString(); } private Label getStatusLabel() { statusLabel = new Label(); statusLabel.setValue(""); return statusLabel; } private List<Agent> getAllNodes() { List<Agent> list = new ArrayList<Agent>(); list.addAll(cluster.getDataNodes()); list.addAll(cluster.getTaskTrackers()); list.add(cluster.getNameNode()); list.add(cluster.getJobTracker()); list.add(cluster.getSecondaryNameNode()); return list; } private DataNodesTable getTable() { dataNodesTable = new DataNodesTable(cluster.getClusterName()); return dataNodesTable; } private String parseNameNodeStatus(String response) { String[] array = response.split("\n"); for (String status : array) { if (status.contains("NameNode")) { return status.replaceAll("NameNode is ", "") .replaceAll("\\(SecondaryNOT Running on this machine\\)", ""); } } return ""; } public AgentManager getAgentManager() { return ServiceLocator.getService(AgentManager.class); } @Override public Task onResponse(Task task, Response response, String stdOut, String stdErr) { if (task.getData() == TaskType.CONFIGURE && Util.isFinalResponse(response)) { keys.add(stdOut); } else if (task.getData() == TaskType.READ_HOSTS && Util.isFinalResponse(response)) { hostss.put(response.getUuid(), stdOut); } if (task.isCompleted()) { if (task.getData() == TaskType.CONFIGURE) { if (task.getTaskStatus().compareTo(TaskStatus.SUCCESS) == 0) { addNode(); } else { addButton.setEnabled(true); } } if (task.getData() == TaskType.ADD) { if (task.getTaskStatus().compareTo(TaskStatus.SUCCESS) == 0) { readHosts(); } } if (task.getData() == TaskType.STATUS) { String status = parseNameNodeStatus(stdOut); statusLabel.setValue(status); if (status.trim().equalsIgnoreCase("Running")) { disableButtons(1); } else { disableButtons(2); } } if (task.getData() == TaskType.START) { getStatus(); } if (task.getData() == TaskType.STOP) { getStatus(); } if (task.getData() == TaskType.RESTART) { getStatus(); } if (task.getData() == TaskType.READ_HOSTS) { if (task.getTaskStatus().equals(TaskStatus.SUCCESS)) { writeHosts(hostss); } } if (task.getData() == TaskType.WRITE_HOSTS) { if (task.getTaskStatus().equals(TaskStatus.SUCCESS)) { HadoopDAO.saveHadoopClusterInfo(cluster); agentsComboBox.refreshDataSource(); dataNodesTable.refreshDataSource(); } else { agentsComboBox.refreshDataSource(); } addButton.setEnabled(true); } } return null; } }
management/server/ui-modules/hadoop/src/main/java/org/safehaus/kiskis/mgmt/server/ui/modules/hadoop/datanode/DataNodesWindow.java
package org.safehaus.kiskis.mgmt.server.ui.modules.hadoop.datanode; import com.vaadin.terminal.Sizeable; import com.vaadin.ui.*; import org.safehaus.kiskis.mgmt.server.ui.modules.hadoop.HadoopModule; import org.safehaus.kiskis.mgmt.server.ui.modules.hadoop.install.Commands; import org.safehaus.kiskis.mgmt.shared.protocol.*; import org.safehaus.kiskis.mgmt.api.agentmanager.AgentManager; import org.safehaus.kiskis.mgmt.shared.protocol.enums.TaskStatus; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import org.safehaus.kiskis.mgmt.api.taskrunner.TaskCallback; import org.safehaus.kiskis.mgmt.server.ui.modules.hadoop.HadoopDAO; import org.safehaus.kiskis.mgmt.server.ui.modules.hadoop.common.TaskType; import org.safehaus.kiskis.mgmt.server.ui.modules.hadoop.common.TaskUtil; public final class DataNodesWindow extends Window implements TaskCallback { private Button startButton, stopButton, restartButton, addButton; private Label statusLabel; private AgentsComboBox agentsComboBox; private DataNodesTable dataNodesTable; private List<String> keys; private HadoopClusterInfo cluster; private final DataNodesWindow INSTANCE; private Map<UUID, String> hostss; public DataNodesWindow(String clusterName) { INSTANCE = this; setModal(true); setCaption("Hadoop Data Node Configuration"); this.cluster = HadoopDAO.getHadoopClusterInfo(clusterName); VerticalLayout verticalLayout = new VerticalLayout(); verticalLayout.setWidth(900, Sizeable.UNITS_PIXELS); verticalLayout.setHeight(450, Sizeable.UNITS_PIXELS); HorizontalLayout buttonLayout = new HorizontalLayout(); buttonLayout.setSpacing(true); buttonLayout.addComponent(getStartButton()); buttonLayout.addComponent(getStopButton()); buttonLayout.addComponent(getRestartButton()); buttonLayout.addComponent(getStatusLabel()); /*HorizontalLayout agentsLayout = new HorizontalLayout(); agentsLayout.setSpacing(true); agentsComboBox = new AgentsComboBox(clusterName); agentsLayout.addComponent(agentsComboBox); agentsLayout.addComponent(getAddButton());*/ Panel panel = new Panel(); panel.setSizeFull(); panel.addComponent(buttonLayout); // panel.addComponent(agentsLayout); panel.addComponent(getTable()); verticalLayout.addComponent(panel); setContent(verticalLayout); getStatus(); } private Button getStartButton() { startButton = new Button("Start"); startButton.setEnabled(false); startButton.addListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { Agent master = cluster.getNameNode(); HashMap<String, String> map = new HashMap<String, String>(); map.put(":source", HadoopModule.MODULE_NAME); map.put(":uuid", master.getUuid().toString()); map.put(":command", "start"); TaskUtil.createRequest(Commands.COMMAND_NAME_NODE, "Start Hadoop Cluster", map, INSTANCE, TaskType.START); disableButtons(0); } }); return startButton; } private Button getStopButton() { stopButton = new Button("Stop"); stopButton.setEnabled(false); stopButton.addListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { Agent master = cluster.getNameNode(); HashMap<String, String> map = new HashMap<String, String>(); map.put(":source", HadoopModule.MODULE_NAME); map.put(":uuid", master.getUuid().toString()); map.put(":command", "stop"); TaskUtil.createRequest(Commands.COMMAND_NAME_NODE, "Stop Hadoop Cluster", map, INSTANCE, TaskType.STOP); disableButtons(0); } }); return stopButton; } private Button getRestartButton() { restartButton = new Button("Restart"); restartButton.setEnabled(false); restartButton.addListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { Agent master = cluster.getNameNode(); HashMap<String, String> map = new HashMap<String, String>(); map.put(":source", HadoopModule.MODULE_NAME); map.put(":uuid", master.getUuid().toString()); map.put(":command", "restart"); TaskUtil.createRequest(Commands.COMMAND_NAME_NODE, "Restart Hadoop Cluster", map, INSTANCE, TaskType.RESTART); disableButtons(0); } }); return restartButton; } private void disableButtons(int status) { startButton.setEnabled(false); stopButton.setEnabled(false); restartButton.setEnabled(false); if (status == 1) { stopButton.setEnabled(true); restartButton.setEnabled(true); } if (status == 2) { startButton.setEnabled(true); } } private Button getAddButton() { addButton = new Button("Add"); addButton.addListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { cluster = HadoopDAO.getHadoopClusterInfo(cluster.getClusterName()); Agent agent = (Agent) agentsComboBox.getValue(); // cluster.getDataNodes().add(agent.getUuid()); List<Agent> list = new ArrayList<Agent>(); list.addAll(cluster.getDataNodes()); list.add(agent); cluster.setDataNodes(list); addButton.setEnabled(false); configureNode(); } }); return addButton; } private void getStatus() { Agent master = cluster.getNameNode(); HashMap<String, String> map = new HashMap<String, String>(); map.put(":source", HadoopModule.MODULE_NAME); map.put(":uuid", master.getUuid().toString()); TaskUtil.createRequest(Commands.STATUS_DATA_NODE, "Get status for Hadoop Data Node", map, INSTANCE, TaskType.STATUS); dataNodesTable.refreshDataSource(); } private void configureNode() { keys = new ArrayList<String>(); HashMap<String, String> map = new HashMap<String, String>(); map.put(":source", HadoopModule.MODULE_NAME); map.put(":uuid", cluster.getNameNode().toString()); TaskUtil.createRequest(Commands.COPY_MASTER_KEY, "Configuring new node on Hadoop Cluster", map, INSTANCE, TaskType.CONFIGURE); if (!cluster.getNameNode().equals(cluster.getSecondaryNameNode())) { map = new HashMap<String, String>(); map.put(":source", HadoopModule.MODULE_NAME); map.put(":uuid", cluster.getSecondaryNameNode().toString()); TaskUtil.createRequest(Commands.COPY_MASTER_KEY, "Configuring new node on Hadoop Cluster", map, INSTANCE, TaskType.CONFIGURE); } if (!cluster.getJobTracker().equals(cluster.getNameNode()) && !cluster.getJobTracker().equals(cluster.getSecondaryNameNode())) { map = new HashMap<String, String>(); map.put(":source", HadoopModule.MODULE_NAME); map.put(":uuid", cluster.getJobTracker().toString()); TaskUtil.createRequest(Commands.COPY_MASTER_KEY, "Configuring new node on Hadoop Cluster", map, INSTANCE, TaskType.CONFIGURE); } } private void addNode() { Agent agent = (Agent) agentsComboBox.getValue(); for (String key : keys) { HashMap<String, String> map = new HashMap<String, String>(); map.put(":source", HadoopModule.MODULE_NAME); map.put(":uuid", agent.getUuid().toString()); map.put(":PUB_KEY", key); TaskUtil.createRequest(Commands.PASTE_MASTER_KEY, "Adding data node to Hadoop Cluster", map, INSTANCE, TaskType.ADD); } HashMap<String, String> map = new HashMap<String, String>(); map.put(":source", HadoopModule.MODULE_NAME); map.put(":uuid", agent.getUuid().toString()); TaskUtil.createRequest(Commands.INSTALL_DEB, "Adding data node to Hadoop Cluster", map, INSTANCE, TaskType.ADD); map = new HashMap<String, String>(); map.put(":source", HadoopModule.MODULE_NAME); map.put(":uuid", cluster.getNameNode().getUuid().toString()); map.put(":slave-hostname", agent.getHostname()); TaskUtil.createRequest(Commands.ADD_DATA_NODE, "Adding data node to Hadoop Cluster", map, INSTANCE, TaskType.ADD); for (Agent agentDataNode : cluster.getDataNodes()) { map = new HashMap<String, String>(); map.put(":source", HadoopModule.MODULE_NAME); map.put(":uuid", cluster.getNameNode().getUuid().toString()); map.put(":IP", agentDataNode.getHostname()); TaskUtil.createRequest(Commands.INCLUDE_DATA_NODE, "Adding data node to Hadoop Cluster", map, INSTANCE, TaskType.ADD); } /*map = new HashMap<String, String>(); map.put(":source", HadoopModule.MODULE_NAME); map.put(":uuid", agent.getUuid().toString()); // map.put(":uuid", getAgentManager().getAgent(cluster.getNameNode()).getUuid().toString()); createRequest(getCommandManager(), Commands.START_DATA_NODE, addTask, map);*/ } public void readHosts() { hostss = new HashMap<UUID, String>(); for (Agent agent : getAllNodes()) { HashMap<String, String> map = new HashMap<String, String>(); map.put(":source", HadoopModule.MODULE_NAME); map.put(":uuid", agent.getUuid().toString()); TaskUtil.createRequest(Commands.READ_HOSTNAME, "Read /etc/hosts file", map, INSTANCE, TaskType.READ_HOSTS); } } public void writeHosts(Map<UUID, String> hostss) { for (Map.Entry<UUID, String> host : hostss.entrySet()) { Agent agent = getAgentManager().getAgentByUUID(host.getKey()); String hosts = editHosts(host.getValue(), agent); HashMap<String, String> map = new HashMap<String, String>(); map.put(":source", HadoopModule.MODULE_NAME); map.put(":uuid", agent.getUuid().toString()); map.put(":hosts", hosts); TaskUtil.createRequest(Commands.WRITE_HOSTNAME, "Write /etc/hosts file", map, INSTANCE, TaskType.WRITE_HOSTS); } /*HashMap<String, String> map = new HashMap<String, String>(); map.put(":source", HadoopModule.MODULE_NAME); map.put(":uuid", getAgentManager().getAgent(cluster.getNameNode()).getUuid().toString()); createRequest(getCommandManager(), Commands.REFRESH_DATA_NODES, hadoopWriteHosts, map);*/ } private String editHosts(String input, Agent localAgent) { StringBuilder result = new StringBuilder(); String[] hosts = input.split("\n"); for (String host : hosts) { host = host.trim(); boolean isContains = false; for (Agent agent : getAllNodes()) { if (host.contains(agent.getHostname()) || host.contains("localhost") || host.contains(localAgent.getHostname()) || host.contains(localAgent.getListIP().get(0))) { isContains = true; } } if (!isContains) { result.append(host); result.append("\n"); } } for (Agent agent : getAllNodes()) { result.append(agent.getListIP().get(0)); result.append("\t"); result.append(agent.getHostname()); result.append("."); result.append(cluster.getIpMask()); result.append("\t"); result.append(agent.getHostname()); result.append("\n"); } result.append("127.0.0.1\tlocalhost"); return result.toString(); } private Label getStatusLabel() { statusLabel = new Label(); statusLabel.setValue(""); return statusLabel; } private List<Agent> getAllNodes() { List<Agent> list = new ArrayList<Agent>(); list.addAll(cluster.getDataNodes()); list.addAll(cluster.getTaskTrackers()); list.add(cluster.getNameNode()); list.add(cluster.getJobTracker()); list.add(cluster.getSecondaryNameNode()); return list; } private DataNodesTable getTable() { dataNodesTable = new DataNodesTable(cluster.getClusterName()); return dataNodesTable; } private String parseNameNodeStatus(String response) { String[] array = response.split("\n"); for (String status : array) { if (status.contains("NameNode")) { return status.replaceAll("NameNode is ", "") .replaceAll("\\(SecondaryNOT Running on this machine\\)", ""); } } return ""; } public AgentManager getAgentManager() { return ServiceLocator.getService(AgentManager.class); } @Override public Task onResponse(Task task, Response response, String stdOut, String stdErr) { if (task.getData() == TaskType.CONFIGURE && Util.isFinalResponse(response)) { keys.add(stdOut); } else if (task.getData() == TaskType.READ_HOSTS && Util.isFinalResponse(response)) { hostss.put(response.getUuid(), stdOut); } if (task.isCompleted()) { if (task.getData() == TaskType.CONFIGURE) { if (task.getTaskStatus().compareTo(TaskStatus.SUCCESS) == 0) { addNode(); } else { addButton.setEnabled(true); } } if (task.getData() == TaskType.ADD) { if (task.getTaskStatus().compareTo(TaskStatus.SUCCESS) == 0) { readHosts(); } } if (task.getData() == TaskType.STATUS) { String status = parseNameNodeStatus(stdOut); statusLabel.setValue(status); if (status.trim().equalsIgnoreCase("Running")) { disableButtons(2); } else { disableButtons(1); } } if (task.getData() == TaskType.START) { getStatus(); } if (task.getData() == TaskType.STOP) { getStatus(); } if (task.getData() == TaskType.RESTART) { getStatus(); } if (task.getData() == TaskType.READ_HOSTS) { if (task.getTaskStatus().equals(TaskStatus.SUCCESS)) { writeHosts(hostss); } } if (task.getData() == TaskType.WRITE_HOSTS) { if (task.getTaskStatus().equals(TaskStatus.SUCCESS)) { HadoopDAO.saveHadoopClusterInfo(cluster); agentsComboBox.refreshDataSource(); dataNodesTable.refreshDataSource(); } else { agentsComboBox.refreshDataSource(); } addButton.setEnabled(true); } } return null; } }
attempt to migrate hadoop to unified persistence Former-commit-id: a48a20acb2cce01df07bbc167fa13028e09ec046
management/server/ui-modules/hadoop/src/main/java/org/safehaus/kiskis/mgmt/server/ui/modules/hadoop/datanode/DataNodesWindow.java
attempt to migrate hadoop to unified persistence
Java
apache-2.0
5f653aa87ae41d8c810a7dbe1ee99d01daf3617d
0
thomasbecker/jetty-7,jetty-project/jetty-plugin-support,xmpace/jetty-read,xmpace/jetty-read,thomasbecker/jetty-spdy,xmpace/jetty-read,jetty-project/jetty-plugin-support,thomasbecker/jetty-spdy,jetty-project/jetty-plugin-support,thomasbecker/jetty-7,xmpace/jetty-read,thomasbecker/jetty-spdy
// ======================================================================== // Copyright (c) 2004-2009 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // You may elect to redistribute this code under either of these licenses. // ======================================================================== package org.eclipse.jetty.io.nio; import java.io.IOException; import java.nio.channels.ClosedChannelException; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; import org.eclipse.jetty.io.AsyncEndPoint; import org.eclipse.jetty.io.Buffer; import org.eclipse.jetty.io.ConnectedEndPoint; import org.eclipse.jetty.io.Connection; import org.eclipse.jetty.io.EofException; import org.eclipse.jetty.io.nio.SelectorManager.SelectSet; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; /* ------------------------------------------------------------ */ /** * An Endpoint that can be scheduled by {@link SelectorManager}. */ public class SelectChannelEndPoint extends ChannelEndPoint implements AsyncEndPoint, ConnectedEndPoint { public static final Logger LOG=Log.getLogger("org.eclipse.jetty.io.nio"); private final SelectorManager.SelectSet _selectSet; private final SelectorManager _manager; private SelectionKey _key; private final Runnable _handler = new Runnable() { public void run() { handle(); } }; /** The desired value for {@link SelectionKey#interestOps()} */ private int _interestOps; /** * The connection instance is the handler for any IO activity on the endpoint. * There is a different type of connection for HTTP, AJP, WebSocket and * ProxyConnect. The connection may change for an SCEP as it is upgraded * from HTTP to proxy connect or websocket. */ private volatile Connection _connection; /** true if a thread has been dispatched to handle this endpoint */ private boolean _dispatched = false; /** true if a non IO dispatch (eg async resume) is outstanding */ private boolean _redispatched = false; /** true if the last write operation succeed and wrote all offered bytes */ private volatile boolean _writable = true; /** True if a thread has is blocked in {@link #blockReadable(long)} */ private boolean _readBlocked; /** True if a thread has is blocked in {@link #blockWritable(long)} */ private boolean _writeBlocked; /** true if {@link SelectSet#destroyEndPoint(SelectChannelEndPoint)} has not been called */ private boolean _open; private volatile long _idleTimestamp; /* ------------------------------------------------------------ */ public SelectChannelEndPoint(SocketChannel channel, SelectSet selectSet, SelectionKey key, int maxIdleTime) throws IOException { super(channel, maxIdleTime); _manager = selectSet.getManager(); _selectSet = selectSet; _dispatched = false; _redispatched = false; _open=true; _key = key; _connection = _manager.newConnection(channel,this); scheduleIdle(); } /* ------------------------------------------------------------ */ public SelectChannelEndPoint(SocketChannel channel, SelectSet selectSet, SelectionKey key) throws IOException { super(channel); _manager = selectSet.getManager(); _selectSet = selectSet; _dispatched = false; _redispatched = false; _open=true; _key = key; _connection = _manager.newConnection(channel,this); scheduleIdle(); } /* ------------------------------------------------------------ */ public SelectionKey getSelectionKey() { synchronized (this) { return _key; } } /* ------------------------------------------------------------ */ public SelectorManager getSelectManager() { return _manager; } /* ------------------------------------------------------------ */ public Connection getConnection() { return _connection; } /* ------------------------------------------------------------ */ public void setConnection(Connection connection) { Connection old=_connection; _connection=connection; _manager.endPointUpgraded(this,old); } /* ------------------------------------------------------------ */ public long getIdleTimestamp() { return _idleTimestamp; } /* ------------------------------------------------------------ */ /** Called by selectSet to schedule handling * */ public void schedule() { synchronized (this) { // If there is no key, then do nothing if (_key == null || !_key.isValid()) { _readBlocked=false; _writeBlocked=false; this.notifyAll(); return; } // If there are threads dispatched reading and writing if (_readBlocked || _writeBlocked) { // assert _dispatched; if (_readBlocked && _key.isReadable()) _readBlocked=false; if (_writeBlocked && _key.isWritable()) _writeBlocked=false; // wake them up is as good as a dispatched. this.notifyAll(); // we are not interested in further selecting if (_dispatched) _key.interestOps(0); return; } // Otherwise if we are still dispatched if (!isReadyForDispatch()) { // we are not interested in further selecting _key.interestOps(0); return; } // Remove writeable op if ((_key.readyOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE && (_key.interestOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) { // Remove writeable op _interestOps = _key.interestOps() & ~SelectionKey.OP_WRITE; _key.interestOps(_interestOps); _writable = true; // Once writable is in ops, only removed with dispatch. } // Dispatch if we are not already if (!_dispatched) { dispatch(); if (_dispatched && !_selectSet.getManager().isDeferringInterestedOps0()) { _key.interestOps(0); } } } } /* ------------------------------------------------------------ */ public void dispatch() { synchronized(this) { if (_dispatched) { _redispatched=true; } else { _dispatched = true; boolean dispatched = _manager.dispatch(_handler); if(!dispatched) { _dispatched = false; LOG.warn("Dispatched Failed! "+this+" to "+_manager); updateKey(); } } } } /* ------------------------------------------------------------ */ /** * Called when a dispatched thread is no longer handling the endpoint. * The selection key operations are updated. * @return If false is returned, the endpoint has been redispatched and * thread must keep handling the endpoint. */ protected boolean undispatch() { synchronized (this) { if (_redispatched) { _redispatched=false; return false; } _dispatched = false; updateKey(); } return true; } /* ------------------------------------------------------------ */ public void scheduleIdle() { _idleTimestamp=System.currentTimeMillis(); } /* ------------------------------------------------------------ */ public void cancelIdle() { _idleTimestamp=0; } /* ------------------------------------------------------------ */ public void checkIdleTimestamp(long now) { long idleTimestamp=_idleTimestamp; if (!getChannel().isOpen() || idleTimestamp!=0 && _maxIdleTime>0 && now>(idleTimestamp+_maxIdleTime)) idleExpired(); } /* ------------------------------------------------------------ */ protected void idleExpired() { _connection.idleExpired(); } /* ------------------------------------------------------------ */ /** * @return True if the endpoint has produced/consumed bytes itself (non application data). */ public boolean isProgressing() { return false; } /* ------------------------------------------------------------ */ /* */ @Override public int flush(Buffer header, Buffer buffer, Buffer trailer) throws IOException { int l = super.flush(header, buffer, trailer); // If there was something to write and it wasn't written, then we are not writable. if (l==0 && ( header!=null && header.hasContent() || buffer!=null && buffer.hasContent() || trailer!=null && trailer.hasContent())) { synchronized (this) { _writable=false; if (!_dispatched) updateKey(); } } else _writable=true; return l; } /* ------------------------------------------------------------ */ /* */ @Override public int flush(Buffer buffer) throws IOException { int l = super.flush(buffer); // If there was something to write and it wasn't written, then we are not writable. if (l==0 && buffer!=null && buffer.hasContent()) { synchronized (this) { _writable=false; if (!_dispatched) updateKey(); } } else _writable=true; return l; } /* ------------------------------------------------------------ */ public boolean isReadyForDispatch() { synchronized (this) { // Ready if not dispatched and not suspended return !(_dispatched || getConnection().isSuspended()); } } /* ------------------------------------------------------------ */ /* * Allows thread to block waiting for further events. */ @Override public boolean blockReadable(long timeoutMs) throws IOException { synchronized (this) { long now=_selectSet.getNow(); long end=now+timeoutMs; try { _readBlocked=true; while (isOpen() && _readBlocked) { try { updateKey(); this.wait(timeoutMs>=0?(end-now):10000); } catch (InterruptedException e) { LOG.warn(e); } finally { now=_selectSet.getNow(); } if (_readBlocked && timeoutMs>0 && now>=end) return false; } } finally { _readBlocked=false; } } return true; } /* ------------------------------------------------------------ */ /* * Allows thread to block waiting for further events. */ @Override public boolean blockWritable(long timeoutMs) throws IOException { synchronized (this) { if (!isOpen() || isOutputShutdown()) throw new EofException(); long now=_selectSet.getNow(); long end=now+timeoutMs; try { _writeBlocked=true; while (isOpen() && _writeBlocked && !isOutputShutdown()) { try { updateKey(); this.wait(timeoutMs>=0?(end-now):10000); } catch (InterruptedException e) { LOG.warn(e); } finally { now=_selectSet.getNow(); } if (_writeBlocked && timeoutMs>0 && now>=end) return false; } } catch(Throwable e) { // TODO remove this if it finds nothing LOG.warn(e); if (e instanceof RuntimeException) throw (RuntimeException)e; if (e instanceof Error) throw (Error)e; throw new RuntimeException(e); } finally { _writeBlocked=false; if (_idleTimestamp!=-1) scheduleIdle(); } } return true; } /* ------------------------------------------------------------ */ /* short cut for busyselectChannelServerTest */ public void clearWritable() { _writable=false; } /* ------------------------------------------------------------ */ public void scheduleWrite() { if (_writable==true) LOG.debug("Required scheduleWrite {}",this); _writable=false; updateKey(); } /* ------------------------------------------------------------ */ /** * Updates selection key. Adds operations types to the selection key as needed. No operations * are removed as this is only done during dispatch. This method records the new key and * schedules a call to doUpdateKey to do the keyChange */ private void updateKey() { synchronized (this) { int ops=-1; if (getChannel().isOpen()) { _interestOps = ((!_socket.isInputShutdown() && (!_dispatched || _readBlocked)) ? SelectionKey.OP_READ : 0) | ((!_socket.isOutputShutdown()&& (!_writable || _writeBlocked)) ? SelectionKey.OP_WRITE : 0); try { ops = ((_key!=null && _key.isValid())?_key.interestOps():-1); } catch(Exception e) { _key=null; LOG.ignore(e); } } if(_interestOps == ops && getChannel().isOpen()) return; } _selectSet.addChange(this); _selectSet.wakeup(); } /* ------------------------------------------------------------ */ /** * Synchronize the interestOps with the actual key. Call is scheduled by a call to updateKey */ void doUpdateKey() { synchronized (this) { if (getChannel().isOpen()) { if (_interestOps>0) { if (_key==null || !_key.isValid()) { SelectableChannel sc = (SelectableChannel)getChannel(); if (sc.isRegistered()) { updateKey(); } else { try { _key=((SelectableChannel)getChannel()).register(_selectSet.getSelector(),_interestOps,this); } catch (Exception e) { LOG.ignore(e); if (_key!=null && _key.isValid()) { _key.cancel(); } cancelIdle(); if (_open) { _selectSet.destroyEndPoint(this); } _open=false; _key = null; } } } else { _key.interestOps(_interestOps); } } else { if (_key!=null && _key.isValid()) _key.interestOps(0); else _key=null; } } else { if (_key!=null && _key.isValid()) _key.cancel(); cancelIdle(); if (_open) { _open=false; _selectSet.destroyEndPoint(this); } _key = null; } } } /* ------------------------------------------------------------ */ /* */ protected void handle() { boolean dispatched=true; try { while(dispatched) { try { while(true) { final Connection next = _connection.handle(); if (next!=_connection) { LOG.debug("{} replaced {}",next,_connection); _connection=next; continue; } break; } } catch (ClosedChannelException e) { LOG.ignore(e); } catch (EofException e) { LOG.debug("EOF", e); try{getChannel().close();} catch(IOException e2){LOG.ignore(e2);} } catch (IOException e) { LOG.warn(e.toString()); LOG.debug(e); try{getChannel().close();} catch(IOException e2){LOG.ignore(e2);} } catch (Throwable e) { LOG.warn("handle failed", e); try{getChannel().close();} catch(IOException e2){LOG.ignore(e2);} } dispatched=!undispatch(); } } finally { if (dispatched) { dispatched=!undispatch(); while (dispatched) { LOG.warn("SCEP.run() finally DISPATCHED"); dispatched=!undispatch(); } } } } /* ------------------------------------------------------------ */ /* * @see org.eclipse.io.nio.ChannelEndPoint#close() */ @Override public void close() throws IOException { try { super.close(); } catch (IOException e) { LOG.ignore(e); } finally { updateKey(); } } /* ------------------------------------------------------------ */ @Override public String toString() { synchronized(this) { return "SCEP@" + hashCode() + "/" + _channel+ "[o="+isOpen()+" d=" + _dispatched + ",io=" + _interestOps+ ",w=" + _writable + ",rb=" + _readBlocked + ",wb=" + _writeBlocked + "]"; } } /* ------------------------------------------------------------ */ public SelectSet getSelectSet() { return _selectSet; } /* ------------------------------------------------------------ */ /** * Don't set the SoTimeout * @see org.eclipse.jetty.io.nio.ChannelEndPoint#setMaxIdleTime(int) */ @Override public void setMaxIdleTime(int timeMs) throws IOException { _maxIdleTime=timeMs; } }
jetty-io/src/main/java/org/eclipse/jetty/io/nio/SelectChannelEndPoint.java
// ======================================================================== // Copyright (c) 2004-2009 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // You may elect to redistribute this code under either of these licenses. // ======================================================================== package org.eclipse.jetty.io.nio; import java.io.IOException; import java.nio.channels.ClosedChannelException; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; import org.eclipse.jetty.io.AsyncEndPoint; import org.eclipse.jetty.io.Buffer; import org.eclipse.jetty.io.ConnectedEndPoint; import org.eclipse.jetty.io.Connection; import org.eclipse.jetty.io.EofException; import org.eclipse.jetty.io.nio.SelectorManager.SelectSet; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; /* ------------------------------------------------------------ */ /** * An Endpoint that can be scheduled by {@link SelectorManager}. */ public class SelectChannelEndPoint extends ChannelEndPoint implements AsyncEndPoint, ConnectedEndPoint { public static final Logger LOG=Log.getLogger("org.eclipse.jetty.io.nio"); private final SelectorManager.SelectSet _selectSet; private final SelectorManager _manager; private SelectionKey _key; private final Runnable _handler = new Runnable() { public void run() { handle(); } }; /** The desired value for {@link SelectionKey#interestOps()} */ private int _interestOps; /** * The connection instance is the handler for any IO activity on the endpoint. * There is a different type of connection for HTTP, AJP, WebSocket and * ProxyConnect. The connection may change for an SCEP as it is upgraded * from HTTP to proxy connect or websocket. */ private volatile Connection _connection; /** true if a thread has been dispatched to handle this endpoint */ private boolean _dispatched = false; /** true if a non IO dispatch (eg async resume) is outstanding */ private boolean _redispatched = false; /** true if the last write operation succeed and wrote all offered bytes */ private volatile boolean _writable = true; /** True if a thread has is blocked in {@link #blockReadable(long)} */ private boolean _readBlocked; /** True if a thread has is blocked in {@link #blockWritable(long)} */ private boolean _writeBlocked; /** true if {@link SelectSet#destroyEndPoint(SelectChannelEndPoint)} has not been called */ private boolean _open; private volatile long _idleTimestamp; /* ------------------------------------------------------------ */ public SelectChannelEndPoint(SocketChannel channel, SelectSet selectSet, SelectionKey key, int maxIdleTime) throws IOException { super(channel, maxIdleTime); _manager = selectSet.getManager(); _selectSet = selectSet; _dispatched = false; _redispatched = false; _open=true; _key = key; _connection = _manager.newConnection(channel,this); scheduleIdle(); } /* ------------------------------------------------------------ */ public SelectChannelEndPoint(SocketChannel channel, SelectSet selectSet, SelectionKey key) throws IOException { super(channel); _manager = selectSet.getManager(); _selectSet = selectSet; _dispatched = false; _redispatched = false; _open=true; _key = key; _connection = _manager.newConnection(channel,this); scheduleIdle(); } /* ------------------------------------------------------------ */ public SelectionKey getSelectionKey() { synchronized (this) { return _key; } } /* ------------------------------------------------------------ */ public SelectorManager getSelectManager() { return _manager; } /* ------------------------------------------------------------ */ public Connection getConnection() { return _connection; } /* ------------------------------------------------------------ */ public void setConnection(Connection connection) { Connection old=_connection; _connection=connection; _manager.endPointUpgraded(this,old); } /* ------------------------------------------------------------ */ public long getIdleTimestamp() { return _idleTimestamp; } /* ------------------------------------------------------------ */ /** Called by selectSet to schedule handling * */ public void schedule() { synchronized (this) { // If there is no key, then do nothing if (_key == null || !_key.isValid()) { _readBlocked=false; _writeBlocked=false; this.notifyAll(); return; } // If there are threads dispatched reading and writing if (_readBlocked || _writeBlocked) { // assert _dispatched; if (_readBlocked && _key.isReadable()) _readBlocked=false; if (_writeBlocked && _key.isWritable()) _writeBlocked=false; // wake them up is as good as a dispatched. this.notifyAll(); // we are not interested in further selecting if (_dispatched) _key.interestOps(0); return; } // Otherwise if we are still dispatched if (!isReadyForDispatch()) { // we are not interested in further selecting _key.interestOps(0); return; } // Remove writeable op if ((_key.readyOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE && (_key.interestOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) { // Remove writeable op _interestOps = _key.interestOps() & ~SelectionKey.OP_WRITE; _key.interestOps(_interestOps); _writable = true; // Once writable is in ops, only removed with dispatch. } // Dispatch if we are not already if (!_dispatched) { dispatch(); if (_dispatched && !_selectSet.getManager().isDeferringInterestedOps0()) { _key.interestOps(0); } } } } /* ------------------------------------------------------------ */ public void dispatch() { synchronized(this) { if (_dispatched) { _redispatched=true; } else { _dispatched = true; boolean dispatched = _manager.dispatch(_handler); if(!dispatched) { _dispatched = false; LOG.warn("Dispatched Failed! "+this+" to "+_manager); updateKey(); } } } } /* ------------------------------------------------------------ */ /** * Called when a dispatched thread is no longer handling the endpoint. * The selection key operations are updated. * @return If false is returned, the endpoint has been redispatched and * thread must keep handling the endpoint. */ protected boolean undispatch() { synchronized (this) { if (_redispatched) { _redispatched=false; return false; } _dispatched = false; updateKey(); } return true; } /* ------------------------------------------------------------ */ public void scheduleIdle() { _idleTimestamp=System.currentTimeMillis(); } /* ------------------------------------------------------------ */ public void cancelIdle() { _idleTimestamp=0; } /* ------------------------------------------------------------ */ public void checkIdleTimestamp(long now) { long idleTimestamp=_idleTimestamp; if (!getChannel().isOpen() || idleTimestamp!=0 && _maxIdleTime>0 && now>(idleTimestamp+_maxIdleTime)) idleExpired(); } /* ------------------------------------------------------------ */ protected void idleExpired() { _connection.idleExpired(); } /* ------------------------------------------------------------ */ /** * @return True if the endpoint has produced/consumed bytes itself (non application data). */ public boolean isProgressing() { return false; } /* ------------------------------------------------------------ */ /* */ @Override public int flush(Buffer header, Buffer buffer, Buffer trailer) throws IOException { int l = super.flush(header, buffer, trailer); // If there was something to write and it wasn't written, then we are not writable. if (l==0 && ( header!=null && header.hasContent() || buffer!=null && buffer.hasContent() || trailer!=null && trailer.hasContent())) { synchronized (this) { _writable=false; if (!_dispatched) updateKey(); } } else _writable=true; return l; } /* ------------------------------------------------------------ */ /* */ @Override public int flush(Buffer buffer) throws IOException { int l = super.flush(buffer); // If there was something to write and it wasn't written, then we are not writable. if (l==0 && buffer!=null && buffer.hasContent()) { synchronized (this) { _writable=false; if (!_dispatched) updateKey(); } } else _writable=true; return l; } /* ------------------------------------------------------------ */ public boolean isReadyForDispatch() { synchronized (this) { // Ready if not dispatched and not suspended return !(_dispatched || getConnection().isSuspended()); } } /* ------------------------------------------------------------ */ /* * Allows thread to block waiting for further events. */ @Override public boolean blockReadable(long timeoutMs) throws IOException { synchronized (this) { long now=_selectSet.getNow(); long end=now+timeoutMs; try { _readBlocked=true; while (isOpen() && _readBlocked) { try { updateKey(); this.wait(timeoutMs>=0?(end-now):10000); } catch (InterruptedException e) { LOG.warn(e); } finally { now=_selectSet.getNow(); } if (_readBlocked && timeoutMs>0 && now>=end) return false; } } finally { _readBlocked=false; } } return true; } /* ------------------------------------------------------------ */ /* * Allows thread to block waiting for further events. */ @Override public boolean blockWritable(long timeoutMs) throws IOException { synchronized (this) { if (!isOpen() || isOutputShutdown()) throw new EofException(); long now=_selectSet.getNow(); long end=now+timeoutMs; try { _writeBlocked=true; while (isOpen() && _writeBlocked && !isOutputShutdown()) { try { updateKey(); this.wait(timeoutMs>=0?(end-now):10000); } catch (InterruptedException e) { LOG.warn(e); } finally { now=_selectSet.getNow(); } if (_writeBlocked && timeoutMs>0 && now>=end) return false; } } catch(Throwable e) { // TODO remove this if it finds nothing LOG.warn(e); if (e instanceof RuntimeException) throw (RuntimeException)e; if (e instanceof Error) throw (Error)e; throw new RuntimeException(e); } finally { _writeBlocked=false; if (_idleTimestamp!=-1) scheduleIdle(); } } return true; } /* ------------------------------------------------------------ */ /* short cut for busyselectChannelServerTest */ public void clearWritable() { _writable=false; } /* ------------------------------------------------------------ */ public void scheduleWrite() { if (_writable==true) LOG.debug("Required scheduleWrite {}",this); _writable=false; updateKey(); } /* ------------------------------------------------------------ */ /** * Updates selection key. Adds operations types to the selection key as needed. No operations * are removed as this is only done during dispatch. This method records the new key and * schedules a call to doUpdateKey to do the keyChange */ private void updateKey() { synchronized (this) { int ops=-1; if (getChannel().isOpen()) { _interestOps = ((!_socket.isInputShutdown() && (!_dispatched || _readBlocked)) ? SelectionKey.OP_READ : 0) | ((!_socket.isOutputShutdown()&& (!_writable || _writeBlocked)) ? SelectionKey.OP_WRITE : 0); try { ops = ((_key!=null && _key.isValid())?_key.interestOps():-1); } catch(Exception e) { _key=null; LOG.ignore(e); } } if(_interestOps == ops && getChannel().isOpen()) return; } _selectSet.addChange(this); _selectSet.wakeup(); } /* ------------------------------------------------------------ */ /** * Synchronize the interestOps with the actual key. Call is scheduled by a call to updateKey */ void doUpdateKey() { synchronized (this) { if (getChannel().isOpen()) { if (_interestOps>0) { if (_key==null || !_key.isValid()) { SelectableChannel sc = (SelectableChannel)getChannel(); if (sc.isRegistered()) { updateKey(); } else { try { _key=((SelectableChannel)getChannel()).register(_selectSet.getSelector(),_interestOps,this); } catch (Exception e) { LOG.ignore(e); if (_key!=null && _key.isValid()) { _key.cancel(); } cancelIdle(); if (_open) { _selectSet.destroyEndPoint(this); } _open=false; _key = null; } } } else { _key.interestOps(_interestOps); } } else { if (_key!=null && _key.isValid()) _key.interestOps(0); else _key=null; } } else { if (_key!=null && _key.isValid()) _key.cancel(); cancelIdle(); if (_open) { _open=false; _selectSet.destroyEndPoint(this); } _key = null; } } } /* ------------------------------------------------------------ */ /* */ protected void handle() { boolean dispatched=true; try { while(dispatched) { try { while(true) { final Connection next = _connection.handle(); if (next!=_connection) { LOG.debug("{} replaced {}",next,_connection); _connection=next; continue; } break; } } catch (ClosedChannelException e) { LOG.ignore(e); } catch (EofException e) { LOG.debug("EOF", e); try{getChannel().close();} catch(IOException e2){LOG.ignore(e2);} } catch (IOException e) { LOG.warn(e.toString()); LOG.debug(e); try{getChannel().close();} catch(IOException e2){LOG.ignore(e2);} } catch (Throwable e) { LOG.warn("handle failed", e); try{getChannel().close();} catch(IOException e2){LOG.ignore(e2);} } dispatched=!undispatch(); } } finally { if (dispatched) { dispatched=!undispatch(); while (dispatched) { LOG.warn("SCEP.run() finally DISPATCHED"); dispatched=!undispatch(); } } } } /* ------------------------------------------------------------ */ /* * @see org.eclipse.io.nio.ChannelEndPoint#close() */ @Override public void close() throws IOException { try { super.close(); } catch (IOException e) { LOG.ignore(e); } finally { updateKey(); } } /* ------------------------------------------------------------ */ @Override public String toString() { synchronized(this) { return "SCEP@" + hashCode() + _channel+ "[o="+isOpen()+" d=" + _dispatched + ",io=" + _interestOps+ ",w=" + _writable + ",rb=" + _readBlocked + ",wb=" + _writeBlocked + "]"; } } /* ------------------------------------------------------------ */ public SelectSet getSelectSet() { return _selectSet; } /* ------------------------------------------------------------ */ /** * Don't set the SoTimeout * @see org.eclipse.jetty.io.nio.ChannelEndPoint#setMaxIdleTime(int) */ @Override public void setMaxIdleTime(int timeMs) throws IOException { _maxIdleTime=timeMs; } }
Minor tweak to SCEP.toString() to make it a bit more readable
jetty-io/src/main/java/org/eclipse/jetty/io/nio/SelectChannelEndPoint.java
Minor tweak to SCEP.toString() to make it a bit more readable
Java
apache-2.0
269ca722225d659dfc21b343a14fb7017afe247e
0
maxee/floatingsearchview,arimorty/floatingsearchview,marsounjan/floatingsearchview,marsounjan/floatingsearchview,maxee/floatingsearchview,arimorty/floatingsearchview
package com.arlib.floatingsearchview; /** * Copyright (C) 2015 Ari C. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.app.Activity; import android.content.Context; import android.content.ContextWrapper; import android.content.res.Configuration; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.IntDef; import android.support.v4.graphics.drawable.DrawableCompat; import android.support.v4.view.ViewCompat; import android.support.v4.view.ViewPropertyAnimatorListenerAdapter; import android.support.v4.view.ViewPropertyAnimatorUpdateListener; import android.support.v7.graphics.drawable.DrawerArrowDrawable; import android.support.v7.view.menu.MenuBuilder; import android.support.v7.widget.CardView; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.WindowManager; import android.view.animation.Interpolator; import android.view.animation.LinearInterpolator; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import com.arlib.floatingsearchview.suggestions.SearchSuggestionsAdapter; import com.arlib.floatingsearchview.suggestions.model.SearchSuggestion; import com.arlib.floatingsearchview.util.Util; import com.arlib.floatingsearchview.util.adapter.GestureDetectorListenerAdapter; import com.arlib.floatingsearchview.util.adapter.OnItemTouchListenerAdapter; import com.arlib.floatingsearchview.util.adapter.TextWatcherAdapter; import com.arlib.floatingsearchview.util.view.MenuView; import com.bartoszlipinski.viewpropertyobjectanimator.ViewPropertyObjectAnimator; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * A search UI widget that implements a floating search box also called persistent * search. */ public class FloatingSearchView extends FrameLayout { private static final String TAG = "FloatingSearchView"; private static final int CARD_VIEW_TOP_BOTTOM_SHADOW_HEIGHT = 3; private static final int CARD_VIEW_CORNERS_AND_TOP_BOTTOM_SHADOW_HEIGHT = 5; private static final long CLEAR_BTN_FADE_ANIM_DURATION = 500; private static final int CLEAR_BTN_WIDTH = 48; private static final int LEFT_MENU_WIDTH_AND_MARGIN_START = 52; private final int BACKGROUND_DRAWABLE_ALPHA_SEARCH_FOCUSED = 150; private final int BACKGROUND_DRAWABLE_ALPHA_SEARCH_NOT_FOCUSED = 0; private final int BACKGROUND_FADE_ANIM_DURATION = 250; private final int MENU_ICON_ANIM_DURATION = 250; private final int ATTRS_SEARCH_BAR_MARGIN_DEFAULT = 0; public final static int LEFT_ACTION_MODE_SHOW_HAMBURGER = 1; public final static int LEFT_ACTION_MODE_SHOW_SEARCH = 2; public final static int LEFT_ACTION_MODE_SHOW_HOME = 3; public final static int LEFT_ACTION_MODE_NO_LEFT_ACTION = 4; private final static int LEFT_ACTION_MODE_NOT_SET = -1; @Retention(RetentionPolicy.SOURCE) @IntDef({LEFT_ACTION_MODE_SHOW_HAMBURGER, LEFT_ACTION_MODE_SHOW_SEARCH, LEFT_ACTION_MODE_SHOW_HOME, LEFT_ACTION_MODE_NO_LEFT_ACTION, LEFT_ACTION_MODE_NOT_SET}) public @interface LeftActionMode { } @LeftActionMode private final int ATTRS_SEARCH_BAR_LEFT_ACTION_MODE_DEFAULT = LEFT_ACTION_MODE_NO_LEFT_ACTION; private final boolean ATTRS_SHOW_MOVE_UP_SUGGESTION_DEFAULT = false; private final boolean ATTRS_DISMISS_ON_OUTSIDE_TOUCH_DEFAULT = true; private final boolean ATTRS_SEARCH_BAR_SHOW_SEARCH_KEY_DEFAULT = true; private final int ATTRS_SUGGESTION_TEXT_SIZE_SP_DEFAULT = 18; private final boolean ATTRS_SHOW_DIM_BACKGROUND_DEFAULT = true; private final Interpolator SUGGEST_ITEM_ADD_ANIM_INTERPOLATOR = new LinearInterpolator(); private final int ATTRS_SUGGESTION_ANIM_DURATION_DEFAULT = 250; private Activity mHostActivity; private View mMainLayout; private Drawable mBackgroundDrawable; private boolean mDimBackground; private boolean mDismissOnOutsideTouch = true; private boolean mIsFocused; private OnFocusChangeListener mFocusChangeListener; private CardView mQuerySection; private OnSearchListener mSearchListener; private EditText mSearchInput; private String mTitleText; private boolean mIsTitleSet; private int mSearchInputTextColor = -1; private int mSearchInputHintColor = -1; private View mSearchInputParent; private String mOldQuery = ""; private OnQueryChangeListener mQueryListener; private ImageView mLeftAction; private OnLeftMenuClickListener mOnMenuClickListener; private OnHomeActionClickListener mOnHomeActionClickListener; private ProgressBar mSearchProgress; private DrawerArrowDrawable mMenuBtnDrawable; private Drawable mIconBackArrow; private Drawable mIconSearch; @LeftActionMode int mLeftActionMode = LEFT_ACTION_MODE_NOT_SET; private int mLeftActionIconColor; private String mSearchHint; private boolean mShowSearchKey; private boolean mMenuOpen = false; private MenuView mMenuView; private int mMenuId = -1; private int mActionMenuItemColor; private int mOverflowIconColor; private OnMenuItemClickListener mActionMenuItemListener; private ImageView mClearButton; private int mClearBtnColor; private Drawable mIconClear; private int mBackgroundColor; private boolean mSkipQueryFocusChangeEvent; private boolean mSkipTextChangeEvent; private View mDivider; private int mDividerColor; private RelativeLayout mSuggestionsSection; private View mSuggestionListContainer; private RecyclerView mSuggestionsList; private int mSuggestionTextColor = -1; private int mSuggestionRightIconColor; private SearchSuggestionsAdapter mSuggestionsAdapter; private SearchSuggestionsAdapter.OnBindSuggestionCallback mOnBindSuggestionCallback; private int mSuggestionsTextSizePx; private boolean mIsInitialLayout = true; private boolean mIsSuggestionsSecHeightSet; private boolean mShowMoveUpSuggestion = ATTRS_SHOW_MOVE_UP_SUGGESTION_DEFAULT; private OnSuggestionsListHeightChanged mOnSuggestionsListHeightChanged; private long mSuggestionSectionAnimDuration; //An interface for implementing a listener that will get notified when the suggestions //section's height is set. This is to be used internally only. private interface OnSuggestionSecHeightSetListener { void onSuggestionSecHeightSet(); } private OnSuggestionSecHeightSetListener mSuggestionSecHeightListener; /** * Interface for implementing a listener to listen * changes in suggestion list height that occur when the list is expands/shrinks * because of calls to {@link FloatingSearchView#swapSuggestions(List)} */ public interface OnSuggestionsListHeightChanged { void onSuggestionsListHeightChanged(float newHeight); } /** * Interface for implementing a listener to listen * to state changes in the query text. */ public interface OnQueryChangeListener { /** * Called when the query has changed. It will * be invoked when one or more characters in the * query was changed. * * @param oldQuery the previous query * @param newQuery the new query */ void onSearchTextChanged(String oldQuery, String newQuery); } /** * Interface for implementing a listener to listen * to when the current search has completed. */ public interface OnSearchListener { /** * Called when a suggestion was clicked indicating * that the current search has completed. * * @param searchSuggestion */ void onSuggestionClicked(SearchSuggestion searchSuggestion); /** * Called when the current search has completed * as a result of pressing search key in the keyboard. * <p/> * Note: This will only get called if * {@link FloatingSearchView#setShowSearchKey(boolean)}} is set to true. * * @param currentQuery the text that is currently set in the query TextView */ void onSearchAction(String currentQuery); } /** * Interface for implementing a callback to be * invoked when the left menu (navigation menu) is * clicked. * <p/> * Note: This is only relevant when leftActionMode is * set to {@value #LEFT_ACTION_MODE_SHOW_HAMBURGER} */ public interface OnLeftMenuClickListener { /** * Called when the menu button was * clicked and the menu's state is now opened. */ void onMenuOpened(); /** * Called when the back button was * clicked and the menu's state is now closed. */ void onMenuClosed(); } /** * Interface for implementing a callback to be * invoked when the home action button (the back arrow) * is clicked. * <p/> * Note: This is only relevant when leftActionMode is * set to {@value #LEFT_ACTION_MODE_SHOW_HOME} */ public interface OnHomeActionClickListener { /** * Called when the home button was * clicked. */ void onHomeClicked(); } /** * Interface for implementing a listener to listen * when an item in the action (the item can be presented as an action * ,or as a menu item in the overflow menu) menu has been selected. */ public interface OnMenuItemClickListener { /** * Called when a menu item in has been * selected. * * @param item the selected menu item. */ void onActionMenuItemSelected(MenuItem item); } /** * Interface for implementing a listener to listen * to for focus state changes. */ public interface OnFocusChangeListener { /** * Called when the search bar has gained focus * and listeners are now active. */ void onFocus(); /** * Called when the search bar has lost focus * and listeners are no more active. */ void onFocusCleared(); } public FloatingSearchView(Context context) { this(context, null); } public FloatingSearchView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } private void init(AttributeSet attrs) { mHostActivity = getHostActivity(); LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); mMainLayout = inflate(getContext(), R.layout.floating_search_layout, this); mBackgroundDrawable = new ColorDrawable(Color.BLACK); mQuerySection = (CardView) findViewById(R.id.search_query_section); mClearButton = (ImageView) findViewById(R.id.clear_btn); mSearchInput = (EditText) findViewById(R.id.search_bar_text); mSearchInputParent = findViewById(R.id.search_input_parent); mLeftAction = (ImageView) findViewById(R.id.left_action); mSearchProgress = (ProgressBar) findViewById(R.id.search_bar_search_progress); initDrawables(); mClearButton.setImageDrawable(mIconClear); mMenuView = (MenuView) findViewById(R.id.menu_view); mDivider = findViewById(R.id.divider); mSuggestionsSection = (RelativeLayout) findViewById(R.id.search_suggestions_section); mSuggestionListContainer = findViewById(R.id.suggestions_list_container); mSuggestionsList = (RecyclerView) findViewById(R.id.suggestions_list); setupViews(attrs); } private Activity getHostActivity() { Context context = getContext(); while (context instanceof ContextWrapper) { if (context instanceof Activity) { return (Activity) context; } context = ((ContextWrapper) context).getBaseContext(); } return null; } private void initDrawables() { mMenuBtnDrawable = new DrawerArrowDrawable(getContext()); mIconClear = Util.getWrappedDrawable(getContext(), R.drawable.ic_clear_black_24dp); mIconBackArrow = Util.getWrappedDrawable(getContext(), R.drawable.ic_arrow_back_black_24dp); mIconSearch = Util.getWrappedDrawable(getContext(), R.drawable.ic_search_black_24dp); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); if (mIsInitialLayout) { //we need to add 5dp to the mSuggestionsSection because we are //going to move it up by 5dp in order to cover the search bar's //shadow padding and rounded corners. We also need to add an additional 10dp to //mSuggestionsSection in order to hide mSuggestionListContainer's //rounded corners and shadow for both, top and bottom. int addedHeight = 3 * Util.dpToPx(CARD_VIEW_CORNERS_AND_TOP_BOTTOM_SHADOW_HEIGHT); final int finalHeight = mSuggestionsSection.getHeight() + addedHeight; mSuggestionsSection.getLayoutParams().height = finalHeight; mSuggestionsSection.requestLayout(); ViewTreeObserver vto = mSuggestionListContainer.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (mSuggestionsSection.getHeight() == finalHeight) { Util.removeGlobalLayoutObserver(mSuggestionListContainer, this); mIsSuggestionsSecHeightSet = true; moveSuggestListToInitialPos(); if (mSuggestionSecHeightListener != null) { mSuggestionSecHeightListener.onSuggestionSecHeightSet(); mSuggestionSecHeightListener = null; } } } }); mIsInitialLayout = false; refreshDimBackground(); if(isInEditMode()) { inflateOverflowMenu(mMenuId); } } } private void setupViews(AttributeSet attrs) { mSuggestionsSection.setEnabled(false); if (attrs != null) { applyXmlAttributes(attrs); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { setBackground(mBackgroundDrawable); } else { setBackgroundDrawable(mBackgroundDrawable); } setupQueryBar(); if (!isInEditMode()) { setupSuggestionSection(); } } private void applyXmlAttributes(AttributeSet attrs) { TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.FloatingSearchView); try { int searchBarWidth = a.getDimensionPixelSize( R.styleable.FloatingSearchView_floatingSearch_searchBarWidth, ViewGroup.LayoutParams.MATCH_PARENT); mQuerySection.getLayoutParams().width = searchBarWidth; mDivider.getLayoutParams().width = searchBarWidth; mSuggestionListContainer.getLayoutParams().width = searchBarWidth; int searchBarLeftMargin = a.getDimensionPixelSize( R.styleable.FloatingSearchView_floatingSearch_searchBarMarginLeft, ATTRS_SEARCH_BAR_MARGIN_DEFAULT); int searchBarTopMargin = a.getDimensionPixelSize( R.styleable.FloatingSearchView_floatingSearch_searchBarMarginTop, ATTRS_SEARCH_BAR_MARGIN_DEFAULT); int searchBarRightMargin = a.getDimensionPixelSize( R.styleable.FloatingSearchView_floatingSearch_searchBarMarginRight, ATTRS_SEARCH_BAR_MARGIN_DEFAULT); LayoutParams querySectionLP = (LayoutParams) mQuerySection.getLayoutParams(); LayoutParams dividerLP = (LayoutParams) mDivider.getLayoutParams(); LinearLayout.LayoutParams suggestListSectionLP = (LinearLayout.LayoutParams) mSuggestionsSection.getLayoutParams(); int cardPadding = Util.dpToPx(CARD_VIEW_TOP_BOTTOM_SHADOW_HEIGHT); querySectionLP.setMargins(searchBarLeftMargin, searchBarTopMargin, searchBarRightMargin, 0); dividerLP.setMargins(searchBarLeftMargin + cardPadding, 0, searchBarRightMargin + cardPadding, ((MarginLayoutParams) mDivider.getLayoutParams()).bottomMargin); suggestListSectionLP.setMargins(searchBarLeftMargin, 0, searchBarRightMargin, 0); mQuerySection.setLayoutParams(querySectionLP); mDivider.setLayoutParams(dividerLP); mSuggestionsSection.setLayoutParams(suggestListSectionLP); setSearchHint(a.getString(R.styleable.FloatingSearchView_floatingSearch_searchHint)); setShowSearchKey(a.getBoolean(R.styleable.FloatingSearchView_floatingSearch_showSearchKey, ATTRS_SEARCH_BAR_SHOW_SEARCH_KEY_DEFAULT)); setDismissOnOutsideClick(a.getBoolean(R.styleable.FloatingSearchView_floatingSearch_dismissOnOutsideTouch, ATTRS_DISMISS_ON_OUTSIDE_TOUCH_DEFAULT)); setSuggestionItemTextSize(a.getDimensionPixelSize( R.styleable.FloatingSearchView_floatingSearch_searchSuggestionTextSize, Util.spToPx(ATTRS_SUGGESTION_TEXT_SIZE_SP_DEFAULT))); //noinspection ResourceType mLeftActionMode = a.getInt(R.styleable.FloatingSearchView_floatingSearch_leftActionMode, ATTRS_SEARCH_BAR_LEFT_ACTION_MODE_DEFAULT); if (a.hasValue(R.styleable.FloatingSearchView_floatingSearch_menu)) { mMenuId = a.getResourceId(R.styleable.FloatingSearchView_floatingSearch_menu, -1); } setDimBackground(a.getBoolean(R.styleable.FloatingSearchView_floatingSearch_dimBackground, ATTRS_SHOW_DIM_BACKGROUND_DEFAULT)); setShowMoveUpSuggestion(a.getBoolean(R.styleable.FloatingSearchView_floatingSearch_showMoveSuggestionUp, ATTRS_SHOW_MOVE_UP_SUGGESTION_DEFAULT)); this.mSuggestionSectionAnimDuration = a.getInt(R.styleable.FloatingSearchView_floatingSearch_suggestionsListAnimDuration, ATTRS_SUGGESTION_ANIM_DURATION_DEFAULT); setBackgroundColor(a.getColor(R.styleable.FloatingSearchView_floatingSearch_backgroundColor , Util.getColor(getContext(), R.color.background))); setLeftActionIconColor(a.getColor(R.styleable.FloatingSearchView_floatingSearch_leftActionColor , Util.getColor(getContext(), R.color.left_action_icon))); setActionMenuOverflowColor(a.getColor(R.styleable.FloatingSearchView_floatingSearch_actionMenuOverflowColor , Util.getColor(getContext(), R.color.overflow_icon_color))); setMenuItemIconColor(a.getColor(R.styleable.FloatingSearchView_floatingSearch_menuItemIconColor , Util.getColor(getContext(), R.color.menu_icon_color))); setDividerColor(a.getColor(R.styleable.FloatingSearchView_floatingSearch_dividerColor , Util.getColor(getContext(), R.color.divider))); setClearBtnColor(a.getColor(R.styleable.FloatingSearchView_floatingSearch_clearBtnColor , Util.getColor(getContext(), R.color.clear_btn_color))); setViewTextColor(a.getColor(R.styleable.FloatingSearchView_floatingSearch_viewTextColor , Util.getColor(getContext(), R.color.dark_gray))); setHintTextColor(a.getColor(R.styleable.FloatingSearchView_floatingSearch_hintTextColor , Util.getColor(getContext(), R.color.hint_color))); setSuggestionRightIconColor(a.getColor(R.styleable.FloatingSearchView_floatingSearch_suggestionRightIconColor , Util.getColor(getContext(), R.color.gray_active_icon))); } finally { a.recycle(); } } private void setupQueryBar() { mSearchInput.setTextColor(mSearchInputTextColor); mSearchInput.setHintTextColor(mSearchInputHintColor); if (!isInEditMode() && mHostActivity != null) { mHostActivity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); } ViewTreeObserver vto = mQuerySection.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { Util.removeGlobalLayoutObserver(mQuerySection, this); inflateOverflowMenu(mMenuId); } }); mMenuView.setMenuCallback(new MenuBuilder.Callback() { @Override public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) { if (mActionMenuItemListener != null) { mActionMenuItemListener.onActionMenuItemSelected(item); } //todo check if we should care about this return or not return false; } @Override public void onMenuModeChange(MenuBuilder menu) { } }); mMenuView.setOnVisibleWidthChanged(new MenuView.OnVisibleWidthChangedListener() { @Override public void onItemsMenuVisibleWidthChanged(int newVisibleWidth) { if (newVisibleWidth == 0) { mClearButton.setTranslationX(-Util.dpToPx(4)); int paddingRight = newVisibleWidth + Util.dpToPx(4); if (mIsFocused) { paddingRight += Util.dpToPx(CLEAR_BTN_WIDTH); } mSearchInput.setPadding(0, 0, paddingRight, 0); } else { mClearButton.setTranslationX(-newVisibleWidth); int paddingRight = newVisibleWidth; if (mIsFocused) { paddingRight += Util.dpToPx(CLEAR_BTN_WIDTH); } mSearchInput.setPadding(0, 0, paddingRight, 0); } } }); mMenuView.setActionIconColor(mActionMenuItemColor); mMenuView.setOverflowColor(mOverflowIconColor); mClearButton.setVisibility(View.INVISIBLE); mClearButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mSearchInput.setText(""); } }); mSearchInput.addTextChangedListener(new TextWatcherAdapter() { public void onTextChanged(final CharSequence s, int start, int before, int count) { //todo investigate why this is called twice when pressing back on the keyboard if (mSkipTextChangeEvent || !mIsFocused) { mSkipTextChangeEvent = false; } else { if (mSearchInput.getText().toString().length() != 0 && mClearButton.getVisibility() == View.INVISIBLE) { mClearButton.setAlpha(0.0f); mClearButton.setVisibility(View.VISIBLE); ViewCompat.animate(mClearButton).alpha(1.0f).setDuration(CLEAR_BTN_FADE_ANIM_DURATION).start(); } else if (mSearchInput.getText().toString().length() == 0) { mClearButton.setVisibility(View.INVISIBLE); } if (mQueryListener != null && mIsFocused && !mOldQuery.equals(mSearchInput.getText().toString())) { mQueryListener.onSearchTextChanged(mOldQuery, mSearchInput.getText().toString()); } mOldQuery = mSearchInput.getText().toString(); } } }); mSearchInput.setOnFocusChangeListener(new TextView.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (mSkipQueryFocusChangeEvent) { mSkipQueryFocusChangeEvent = false; } else if (hasFocus != mIsFocused) { setSearchFocusedInternal(hasFocus); } } }); mSearchInput.setOnKeyListener(new OnKeyListener() { public boolean onKey(View view, int keyCode, KeyEvent keyEvent) { if (mShowSearchKey && keyCode == KeyEvent.KEYCODE_ENTER) { if (mSearchListener != null) { mSearchListener.onSearchAction(getQuery()); } mSkipTextChangeEvent = true; setSearchBarTitle(getQuery()); setSearchFocusedInternal(false); return true; } return false; } }); mLeftAction.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (isSearchBarFocused()) { setSearchFocusedInternal(false); } else { switch (mLeftActionMode) { case LEFT_ACTION_MODE_SHOW_HAMBURGER: toggleLeftMenu(); break; case LEFT_ACTION_MODE_SHOW_SEARCH: setSearchFocusedInternal(true); break; case LEFT_ACTION_MODE_SHOW_HOME: if (mOnHomeActionClickListener != null) { mOnHomeActionClickListener.onHomeClicked(); } break; case LEFT_ACTION_MODE_NO_LEFT_ACTION: //do nothing break; } } } }); refreshLeftIcon(); } private int actionMenuAvailWidth() { if(isInEditMode()){ return mQuerySection.getMeasuredWidth() / 2; } return mQuerySection.getWidth() / 2; } /** * Sets the menu button's color. * * @param color the color to be applied to the * left menu button. */ public void setLeftActionIconColor(int color) { mLeftActionIconColor = color; mMenuBtnDrawable.setColor(color); DrawableCompat.setTint(mIconBackArrow, color); DrawableCompat.setTint(mIconSearch, color); } /** * Sets the clear button's color. * * @param color the color to be applied to the * clear button. */ public void setClearBtnColor(int color) { mClearBtnColor = color; DrawableCompat.setTint(mIconClear, mClearBtnColor); } /** * Sets the action menu icons' color. * * @param color the color to be applied to the * action menu items. */ public void setMenuItemIconColor(int color) { this.mActionMenuItemColor = color; if (mMenuView != null) { mMenuView.setActionIconColor(this.mActionMenuItemColor); } } /** * Sets the action menu overflow icon's color. * * @param color the color to be applied to the * overflow icon. */ public void setActionMenuOverflowColor(int color) { this.mOverflowIconColor = color; if (mMenuView != null) { mMenuView.setOverflowColor(this.mOverflowIconColor); } } /** * Sets the background color of the search * view including the suggestions section. * * @param color the color to be applied to the search bar and * the suggestion section background. */ public void setBackgroundColor(int color) { mBackgroundColor = color; if (mQuerySection != null && mSuggestionsList != null) { mQuerySection.setCardBackgroundColor(color); mSuggestionsList.setBackgroundColor(color); } } /** * Sets the text color of the search * and suggestion text. * * @param color the color to be applied to the search and suggestion * text. */ public void setViewTextColor(int color) { setSuggestionsTextColor(color); setQueryTextColor(color); } /** * Sets the text color of suggestion text. * * @param color */ public void setSuggestionsTextColor(int color) { mSuggestionTextColor = color; if (mSuggestionsAdapter != null) { mSuggestionsAdapter.setTextColor(mSuggestionTextColor); } } /** * Set the duration for the suggestions list expand/collapse * animation. * * @param duration */ public void setSuggestionsAnimDuration(long duration) { this.mSuggestionSectionAnimDuration = duration; } /** * Sets the text color of the search text. * * @param color */ public void setQueryTextColor(int color) { mSearchInputTextColor = color; if (mSearchInput != null) { mSearchInput.setTextColor(mSearchInputTextColor); } } /** * Sets the text color of the search * hint. * * @param color the color to be applied to the search hint. */ public void setHintTextColor(int color) { this.mSearchInputHintColor = color; if (mSearchInput != null) { mSearchInput.setHintTextColor(color); } } /** * Sets the color of the search divider that * divides the search section from the suggestions. * * @param color the color to be applied the divider. */ public void setDividerColor(int color) { mDividerColor = color; if (mDivider != null) { mDivider.setBackgroundColor(mDividerColor); } } /** * Set the tint of the suggestion items' right btn (move suggestion to * query) * * @param color */ public void setSuggestionRightIconColor(int color) { this.mSuggestionRightIconColor = color; if (mSuggestionsAdapter != null) { mSuggestionsAdapter.setRightIconColor(this.mSuggestionRightIconColor); } } /** * Set the text size of the suggestion items. * * @param sizePx */ private void setSuggestionItemTextSize(int sizePx) { //todo implement dynamic suggestionTextSize setter and expose method this.mSuggestionsTextSizePx = sizePx; } /** * Set the mode for the left action button. * * @param mode */ public void setLeftActionMode(@LeftActionMode int mode) { mLeftActionMode = mode; refreshLeftIcon(); } private void refreshLeftIcon() { int leftActionWidthAndMarginLeft = Util.dpToPx(LEFT_MENU_WIDTH_AND_MARGIN_START); int queryTranslationX = 0; mLeftAction.setVisibility(VISIBLE); switch (mLeftActionMode) { case LEFT_ACTION_MODE_SHOW_HAMBURGER: mLeftAction.setImageDrawable(mMenuBtnDrawable); break; case LEFT_ACTION_MODE_SHOW_SEARCH: mLeftAction.setImageDrawable(mIconSearch); break; case LEFT_ACTION_MODE_SHOW_HOME: mLeftAction.setImageDrawable(mMenuBtnDrawable); mMenuBtnDrawable.setProgress(1.0f); break; case LEFT_ACTION_MODE_NO_LEFT_ACTION: mLeftAction.setVisibility(View.INVISIBLE); queryTranslationX = -leftActionWidthAndMarginLeft; break; } mSearchInputParent.setTranslationX(queryTranslationX); } private void toggleLeftMenu() { if (mMenuOpen) { closeMenu(true); } else { openMenu(true); } } /** * <p/> * Enables clients to directly manipulate * the menu icon's progress. * <p/> * Useful for custom animation/behaviors. * * @param progress the desired progress of the menu * icon's rotation: 0.0 == hamburger * shape, 1.0 == back arrow shape */ public void setMenuIconProgress(float progress) { mMenuBtnDrawable.setProgress(progress); if (progress == 0) { closeMenu(false); } else if (progress == 1.0) { openMenu(false); } } /** * Mimics a menu click that opens the menu. Useful when for navigation * drawers when they open as a result of dragging. */ public void openMenu(boolean withAnim) { mMenuOpen = true; openMenuDrawable(mMenuBtnDrawable, withAnim); if (mOnMenuClickListener != null) { mOnMenuClickListener.onMenuOpened(); } } /** * Mimics a menu click that closes. Useful when fo navigation * drawers when they close as a result of selecting and item. * * @param withAnim true, will close the menu button with * the Material animation */ public void closeMenu(boolean withAnim) { mMenuOpen = false; closeMenuDrawable(mMenuBtnDrawable, withAnim); if (mOnMenuClickListener != null) { mOnMenuClickListener.onMenuClosed(); } } /** * Set the hamburger menu to open or closed without * animating hamburger to arrow and without calling listeners. * * @param isOpen */ public void setLeftMenuOpen(boolean isOpen) { mMenuOpen = isOpen; mMenuBtnDrawable.setProgress(isOpen ? 1.0f : 0.0f); } /** * Shows a circular progress on top of the * menu action button. * <p/> * Call hidProgress() * to change back to normal and make the menu * action visible. */ public void showProgress() { mLeftAction.setVisibility(View.GONE); mSearchProgress.setAlpha(0.0f); mSearchProgress.setVisibility(View.VISIBLE); ObjectAnimator.ofFloat(mSearchProgress, "alpha", 0.0f, 1.0f).start(); } /** * Hides the progress bar after * a prior call to showProgress() */ public void hideProgress() { mSearchProgress.setVisibility(View.GONE); mLeftAction.setAlpha(0.0f); mLeftAction.setVisibility(View.VISIBLE); ObjectAnimator.ofFloat(mLeftAction, "alpha", 0.0f, 1.0f).start(); } /** * Inflates the menu items from * an xml resource. * * @param menuId a menu xml resource reference */ public void inflateOverflowMenu(int menuId) { mMenuId = menuId; mMenuView.reset(menuId, actionMenuAvailWidth()); if (mIsFocused) { mMenuView.hideIfRoomItems(false); } } /** * Set a hint that will appear in the * search input. Default hint is R.string.abc_search_hint * which is "search..." (when device language is set to english) * * @param searchHint */ public void setSearchHint(String searchHint) { mSearchHint = searchHint != null ? searchHint : getResources().getString(R.string.abc_search_hint); mSearchInput.setHint(mSearchHint); } /** * Sets whether the the button with the search icon * will appear in the soft-keyboard or not. * * @param show to show the search button in * the soft-keyboard. */ public void setShowSearchKey(boolean show) { mShowSearchKey = show; if (show) { mSearchInput.setImeOptions(EditorInfo.IME_ACTION_SEARCH); } else { mSearchInput.setImeOptions(EditorInfo.IME_ACTION_NONE); } } /** * Set whether a touch outside of the * search bar's bounds will cause the search bar to * loos focus. * * @param enable true to dismiss on outside touch, false otherwise. */ public void setDismissOnOutsideClick(boolean enable) { mDismissOnOutsideTouch = enable; mSuggestionsSection.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { //todo check if this is called twice if (mDismissOnOutsideTouch && mIsFocused) { setSearchFocusedInternal(false); } return true; } }); } /** * Sets whether a dim background will show when the search is focused * * @param dimEnabled True to show dim */ public void setDimBackground(boolean dimEnabled) { this.mDimBackground = dimEnabled; refreshDimBackground(); } private void refreshDimBackground() { if (this.mDimBackground && mIsFocused) { mBackgroundDrawable.setAlpha(BACKGROUND_DRAWABLE_ALPHA_SEARCH_FOCUSED); } else { mBackgroundDrawable.setAlpha(BACKGROUND_DRAWABLE_ALPHA_SEARCH_NOT_FOCUSED); } } /** * Sets the arrow up of suggestion items to be enabled and visible or * disabled and invisible. * * @param show */ public void setShowMoveUpSuggestion(boolean show) { mShowMoveUpSuggestion = show; refreshShowMoveUpSuggestion(); } private void refreshShowMoveUpSuggestion() { if (mSuggestionsAdapter != null) { mSuggestionsAdapter.setShowMoveUpIcon(mShowMoveUpSuggestion); } } /** * Wrapper implementation for EditText.setFocusable(boolean focusable) * * @param focusable true, to make search focus when * clicked. */ public void setSearchFocusable(boolean focusable) { mSearchInput.setFocusable(focusable); } /** * Sets the title for the search bar. * <p/> * Note that after the title is set, when * the search gains focus, the title will be replaced * by the search hint. * * @param title the title to be shown when search * is not focused */ public void setSearchBarTitle(CharSequence title) { this.mTitleText = title.toString(); mIsTitleSet = true; mSearchInput.setText(title); } /** * Sets the search text. * <p/> * Note that this is the different from * {@link #setSearchBarTitle(CharSequence title) setSearchBarTitle} in * that it keeps the text when the search gains focus. * * @param text the text to be set for the search * input. */ public void setSearchText(CharSequence text) { mIsTitleSet = false; mSearchInput.setText(text); } /** * Returns the current query text. * * @return the current query */ public String getQuery() { return mSearchInput.getText().toString(); } public void clearQuery() { mSearchInput.setText(""); } /** * Sets whether the search is focused or not. * * @param focused true, to set the search to be active/focused. * @return true if the search was focused and will now become not focused. Useful for * calling supper.onBackPress() in the hosting activity only if this method returns false */ public boolean setSearchFocused(final boolean focused) { boolean updatedToNotFocused = !focused && this.mIsFocused; if ((focused != this.mIsFocused) && mSuggestionSecHeightListener == null) { if (mIsSuggestionsSecHeightSet) { setSearchFocusedInternal(focused); } else { mSuggestionSecHeightListener = new OnSuggestionSecHeightSetListener() { @Override public void onSuggestionSecHeightSet() { setSearchFocusedInternal(focused); mSuggestionSecHeightListener = null; } }; } } return updatedToNotFocused; } private void setupSuggestionSection() { LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, true); mSuggestionsList.setLayoutManager(layoutManager); mSuggestionsList.setItemAnimator(null); final GestureDetector gestureDetector = new GestureDetector(getContext(), new GestureDetectorListenerAdapter() { @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { if (mHostActivity != null) { Util.closeSoftKeyboard(mHostActivity); } return false; } }); mSuggestionsList.addOnItemTouchListener(new OnItemTouchListenerAdapter() { @Override public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) { gestureDetector.onTouchEvent(e); return false; } }); mSuggestionsAdapter = new SearchSuggestionsAdapter(getContext(), mSuggestionsTextSizePx, new SearchSuggestionsAdapter.Listener() { @Override public void onItemSelected(SearchSuggestion item) { if (mSearchListener != null) { mSearchListener.onSuggestionClicked(item); } mSkipTextChangeEvent = true; setSearchBarTitle(item.getBody()); setSearchFocusedInternal(false); } @Override public void onMoveItemToSearchClicked(SearchSuggestion item) { mSearchInput.setText(item.getBody()); //move cursor to end of text mSearchInput.setSelection(mSearchInput.getText().length()); } }); refreshShowMoveUpSuggestion(); mSuggestionsAdapter.setTextColor(this.mSuggestionTextColor); mSuggestionsAdapter.setRightIconColor(this.mSuggestionRightIconColor); mSuggestionsList.setAdapter(mSuggestionsAdapter); int cardViewBottomPadding = Util.dpToPx(CARD_VIEW_CORNERS_AND_TOP_BOTTOM_SHADOW_HEIGHT); //move up the suggestions section enough to cover the search bar //card's bottom left and right corners mSuggestionsSection.setTranslationY(-cardViewBottomPadding); } private void moveSuggestListToInitialPos() { //move the suggestions list to the collapsed position //which is translationY of -listContainerHeight mSuggestionListContainer.setTranslationY(-mSuggestionListContainer.getHeight()); } /** * Clears the current suggestions and replaces it * with the provided list of new suggestions. * * @param newSearchSuggestions a list containing the new suggestions */ public void swapSuggestions(final List<? extends SearchSuggestion> newSearchSuggestions) { Collections.reverse(newSearchSuggestions); swapSuggestions(newSearchSuggestions, true); } private void swapSuggestions(final List<? extends SearchSuggestion> newSearchSuggestions, final boolean withAnim) { mSuggestionsList.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { Util.removeGlobalLayoutObserver(mSuggestionsList, this); updateSuggestionsSectionHeight(newSearchSuggestions, withAnim); } }); mSuggestionsAdapter.swapData(newSearchSuggestions); mDivider.setVisibility(!newSearchSuggestions.isEmpty() ? View.VISIBLE : View.GONE); } private void updateSuggestionsSectionHeight(List<? extends SearchSuggestion> newSearchSuggestions, boolean withAnim) { final int cardTopBottomShadowPadding = Util.dpToPx(CARD_VIEW_CORNERS_AND_TOP_BOTTOM_SHADOW_HEIGHT); final int cardRadiusSize = Util.dpToPx(CARD_VIEW_TOP_BOTTOM_SHADOW_HEIGHT); int visibleSuggestionHeight = calculateSuggestionItemsHeight(newSearchSuggestions, mSuggestionListContainer.getHeight()); int diff = mSuggestionListContainer.getHeight() - visibleSuggestionHeight; int addedTranslationYForShadowOffsets = (diff <= cardTopBottomShadowPadding) ? -(cardTopBottomShadowPadding - diff) : diff < (mSuggestionListContainer.getHeight()-cardTopBottomShadowPadding) ? cardRadiusSize : 0; final float newTranslationY = -mSuggestionListContainer.getHeight() + visibleSuggestionHeight + addedTranslationYForShadowOffsets; final boolean animateAtEnd = newTranslationY >= mSuggestionListContainer.getTranslationY(); //todo go over final float fullyInvisibleTranslationY = -mSuggestionListContainer.getHeight() + cardRadiusSize; ViewCompat.animate(mSuggestionListContainer).cancel(); if (withAnim) { ViewCompat.animate(mSuggestionListContainer). setInterpolator(SUGGEST_ITEM_ADD_ANIM_INTERPOLATOR). setDuration(mSuggestionSectionAnimDuration). translationY(newTranslationY) .setUpdateListener(new ViewPropertyAnimatorUpdateListener() { @Override public void onAnimationUpdate(View view) { if (mOnSuggestionsListHeightChanged != null) { float newSuggestionsHeight = Math.abs(view.getTranslationY() - fullyInvisibleTranslationY); mOnSuggestionsListHeightChanged.onSuggestionsListHeightChanged(newSuggestionsHeight); } } }) .setListener(new ViewPropertyAnimatorListenerAdapter() { @Override public void onAnimationCancel(View view) { mSuggestionListContainer.setTranslationY(newTranslationY); } @Override public void onAnimationStart(View view) { if (!animateAtEnd) { mSuggestionsList.smoothScrollToPosition(0); } } @Override public void onAnimationEnd(View view) { if (animateAtEnd) { int lastPos = mSuggestionsList.getAdapter().getItemCount() - 1; if (lastPos > -1) { mSuggestionsList.smoothScrollToPosition(lastPos); } } } }).start(); } else { mSuggestionListContainer.setTranslationY(newTranslationY); if (mOnSuggestionsListHeightChanged != null) { float newSuggestionsHeight = Math.abs(mSuggestionListContainer.getTranslationY() - fullyInvisibleTranslationY); mOnSuggestionsListHeightChanged.onSuggestionsListHeightChanged(newSuggestionsHeight); } } } //returns the cumulative height that the current suggestion items take up or the given max if the //results is >= max. The max option allows us to avoid doing unnecessary and potentially long calculations. private int calculateSuggestionItemsHeight(List<? extends SearchSuggestion> suggestions, int max) { int visibleItemsHeight = 0; for (int i = 0; i < suggestions.size() && i < mSuggestionsList.getChildCount(); i++) { visibleItemsHeight += mSuggestionsList.getChildAt(i).getHeight(); if (visibleItemsHeight > max) { visibleItemsHeight = max; break; } } return visibleItemsHeight; } /** * Set a callback that will be called after each suggestion view in the suggestions recycler * list is bound. This allows for customized binding for specific items in the list. * * @param callback A callback to be called after a suggestion is bound by the suggestions list's * adapter. */ public void setOnBindSuggestionCallback(SearchSuggestionsAdapter.OnBindSuggestionCallback callback) { this.mOnBindSuggestionCallback = callback; if (mSuggestionsAdapter != null) { mSuggestionsAdapter.setOnBindSuggestionCallback(mOnBindSuggestionCallback); } } /** * Collapses the suggestions list and * then clears its suggestion items. */ public void clearSuggestions() { swapSuggestions(new ArrayList<SearchSuggestion>()); } public void clearSearchFocus() { setSearchFocusedInternal(false); } public boolean isSearchBarFocused() { return mIsFocused; } private void setSearchFocusedInternal(final boolean focused) { this.mIsFocused = focused; if (focused) { mSearchInput.requestFocus(); moveSuggestListToInitialPos(); mSuggestionsSection.setVisibility(VISIBLE); if (mDimBackground) { fadeInBackground(); } mMenuView.hideIfRoomItems(true); transitionInLeftSection(true); Util.showSoftKeyboard(getContext(), mSearchInput); if (mMenuOpen) { closeMenu(false); } if (mIsTitleSet) { mSkipTextChangeEvent = true; mSearchInput.setText(""); } if (mFocusChangeListener != null) { mFocusChangeListener.onFocus(); } } else { mMainLayout.requestFocus(); clearSuggestions(); if (mDimBackground) { fadeOutBackground(); } mMenuView.showIfRoomItems(true); transitionOutLeftSection(true); mClearButton.setVisibility(View.GONE); if (mHostActivity != null) { Util.closeSoftKeyboard(mHostActivity); } if (mIsTitleSet) { mSkipTextChangeEvent = true; mSearchInput.setText(mTitleText); } if (mFocusChangeListener != null) { mFocusChangeListener.onFocusCleared(); } } //if we don't have focus, we want to allow the client's views below our invisible //screen-covering view to handle touches mSuggestionsSection.setEnabled(focused); } private void changeIcon(ImageView imageView, Drawable newIcon, boolean withAnim) { imageView.setImageDrawable(newIcon); if (withAnim) { ObjectAnimator fadeInVoiceInputOrClear = ObjectAnimator.ofFloat(imageView, "alpha", 0.0f, 1.0f); fadeInVoiceInputOrClear.start(); } else { imageView.setAlpha(1.0f); } } private void transitionInLeftSection(boolean withAnim) { if(mSearchProgress.getVisibility() != View.VISIBLE) { mLeftAction.setVisibility(View.VISIBLE); }else { mLeftAction.setVisibility(View.INVISIBLE); } switch (mLeftActionMode) { case LEFT_ACTION_MODE_SHOW_HAMBURGER: openMenuDrawable(mMenuBtnDrawable, withAnim); if (!mMenuOpen) { break; } break; case LEFT_ACTION_MODE_SHOW_SEARCH: mLeftAction.setImageDrawable(mIconBackArrow); if (withAnim) { mLeftAction.setRotation(45); mLeftAction.setAlpha(0.0f); ObjectAnimator rotateAnim = ViewPropertyObjectAnimator.animate(mLeftAction).rotation(0).get(); ObjectAnimator fadeAnim = ViewPropertyObjectAnimator.animate(mLeftAction).alpha(1.0f).get(); AnimatorSet animSet = new AnimatorSet(); animSet.setDuration(500); animSet.playTogether(rotateAnim, fadeAnim); animSet.start(); } break; case LEFT_ACTION_MODE_SHOW_HOME: //do nothing break; case LEFT_ACTION_MODE_NO_LEFT_ACTION: mLeftAction.setImageDrawable(mIconBackArrow); if (withAnim) { ObjectAnimator searchInputTransXAnim = ViewPropertyObjectAnimator .animate(mSearchInputParent).translationX(0).get(); mLeftAction.setScaleX(0.5f); mLeftAction.setScaleY(0.5f); mLeftAction.setAlpha(0.0f); mLeftAction.setTranslationX(Util.dpToPx(8)); ObjectAnimator transXArrowAnim = ViewPropertyObjectAnimator.animate(mLeftAction).translationX(1.0f).get(); ObjectAnimator scaleXArrowAnim = ViewPropertyObjectAnimator.animate(mLeftAction).scaleX(1.0f).get(); ObjectAnimator scaleYArrowAnim = ViewPropertyObjectAnimator.animate(mLeftAction).scaleY(1.0f).get(); ObjectAnimator fadeArrowAnim = ViewPropertyObjectAnimator.animate(mLeftAction).alpha(1.0f).get(); transXArrowAnim.setStartDelay(150); scaleXArrowAnim.setStartDelay(150); scaleYArrowAnim.setStartDelay(150); fadeArrowAnim.setStartDelay(150); AnimatorSet animSet = new AnimatorSet(); animSet.setDuration(500); animSet.playTogether(searchInputTransXAnim, transXArrowAnim, scaleXArrowAnim, scaleYArrowAnim, fadeArrowAnim); animSet.start(); } else { mSearchInputParent.setTranslationX(0); } break; } } private void transitionOutLeftSection(boolean withAnim) { switch (mLeftActionMode) { case LEFT_ACTION_MODE_SHOW_HAMBURGER: closeMenuDrawable(mMenuBtnDrawable, withAnim); break; case LEFT_ACTION_MODE_SHOW_SEARCH: changeIcon(mLeftAction, mIconSearch, withAnim); break; case LEFT_ACTION_MODE_SHOW_HOME: //do nothing break; case LEFT_ACTION_MODE_NO_LEFT_ACTION: mLeftAction.setImageDrawable(mIconBackArrow); if (withAnim) { ObjectAnimator searchInputTransXAnim = ViewPropertyObjectAnimator.animate(mSearchInputParent) .translationX(-Util.dpToPx(LEFT_MENU_WIDTH_AND_MARGIN_START)).get(); ObjectAnimator scaleXArrowAnim = ViewPropertyObjectAnimator.animate(mLeftAction).scaleX(0.5f).get(); ObjectAnimator scaleYArrowAnim = ViewPropertyObjectAnimator.animate(mLeftAction).scaleY(0.5f).get(); ObjectAnimator fadeArrowAnim = ViewPropertyObjectAnimator.animate(mLeftAction).alpha(0.5f).get(); scaleXArrowAnim.setDuration(300); scaleYArrowAnim.setDuration(300); fadeArrowAnim.setDuration(300); scaleXArrowAnim.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { //restore normal state mLeftAction.setScaleX(1.0f); mLeftAction.setScaleY(1.0f); mLeftAction.setAlpha(1.0f); mLeftAction.setVisibility(View.INVISIBLE); } }); AnimatorSet animSet = new AnimatorSet(); animSet.setDuration(350); animSet.playTogether(scaleXArrowAnim, scaleYArrowAnim, fadeArrowAnim, searchInputTransXAnim); animSet.start(); } else { mLeftAction.setVisibility(View.INVISIBLE); } break; } } /** * Sets the listener that will be notified when the suggestion list's height * changes. * * @param onSuggestionsListHeightChanged the new suggestions list's height */ public void setOnSuggestionsListHeightChanged(OnSuggestionsListHeightChanged onSuggestionsListHeightChanged) { this.mOnSuggestionsListHeightChanged = onSuggestionsListHeightChanged; } /** * Sets the listener that will listen for query * changes as they are being typed. * * @param listener listener for query changes */ public void setOnQueryChangeListener(OnQueryChangeListener listener) { this.mQueryListener = listener; } /** * Sets the listener that will be called when * an action that completes the current search * session has occurred and the search lost focus. * <p/> * <p>When called, a client would ideally grab the * search or suggestion query from the callback parameter or * from {@link #getQuery() getquery} and perform the necessary * query against its data source.</p> * * @param listener listener for query completion */ public void setOnSearchListener(OnSearchListener listener) { this.mSearchListener = listener; } /** * Sets the listener that will be called when the focus * of the search has changed. * * @param listener listener for search focus changes */ public void setOnFocusChangeListener(OnFocusChangeListener listener) { this.mFocusChangeListener = listener; } /** * Sets the listener that will be called when the * left/start menu (or navigation menu) is clicked. * <p/> * <p>Note that this is different from the overflow menu * that has a separate listener.</p> * * @param listener */ public void setOnLeftMenuClickListener(OnLeftMenuClickListener listener) { this.mOnMenuClickListener = listener; } /** * Sets the listener that will be called when the * left/start home action (back arrow) is clicked. * * @param listener */ public void setOnHomeActionClickListener(OnHomeActionClickListener listener) { this.mOnHomeActionClickListener = listener; } /** * Sets the listener that will be called when * an item in the overflow menu is clicked. * * @param listener listener to listen to menu item clicks */ public void setOnMenuItemClickListener(OnMenuItemClickListener listener) { this.mActionMenuItemListener = listener; //todo reset menu view listener } private void openMenuDrawable(final DrawerArrowDrawable drawerArrowDrawable, boolean withAnim) { if (withAnim) { ValueAnimator anim = ValueAnimator.ofFloat(0.0f, 1.0f); anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float value = (Float) animation.getAnimatedValue(); drawerArrowDrawable.setProgress(value); } }); anim.setDuration(MENU_ICON_ANIM_DURATION); anim.start(); } else { drawerArrowDrawable.setProgress(1.0f); } } private void closeMenuDrawable(final DrawerArrowDrawable drawerArrowDrawable, boolean withAnim) { if (withAnim) { ValueAnimator anim = ValueAnimator.ofFloat(1.0f, 0.0f); anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float value = (Float) animation.getAnimatedValue(); drawerArrowDrawable.setProgress(value); } }); anim.setDuration(MENU_ICON_ANIM_DURATION); anim.start(); } else { drawerArrowDrawable.setProgress(0.0f); } } private void fadeOutBackground() { ValueAnimator anim = ValueAnimator.ofInt(BACKGROUND_DRAWABLE_ALPHA_SEARCH_FOCUSED, BACKGROUND_DRAWABLE_ALPHA_SEARCH_NOT_FOCUSED); anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { int value = (Integer) animation.getAnimatedValue(); mBackgroundDrawable.setAlpha(value); } }); anim.setDuration(BACKGROUND_FADE_ANIM_DURATION); anim.start(); } private void fadeInBackground() { ValueAnimator anim = ValueAnimator.ofInt(BACKGROUND_DRAWABLE_ALPHA_SEARCH_NOT_FOCUSED, BACKGROUND_DRAWABLE_ALPHA_SEARCH_FOCUSED); anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { int value = (Integer) animation.getAnimatedValue(); mBackgroundDrawable.setAlpha(value); } }); anim.setDuration(BACKGROUND_FADE_ANIM_DURATION); anim.start(); } private boolean isRTL() { Configuration config = getResources().getConfiguration(); return ViewCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_RTL; } @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState savedState = new SavedState(superState); savedState.suggestions = this.mSuggestionsAdapter.getDataSet(); savedState.isFocused = this.mIsFocused; savedState.query = getQuery(); savedState.suggestionTextSize = this.mSuggestionsTextSizePx; savedState.searchHint = this.mSearchHint; savedState.dismissOnOutsideClick = this.mDismissOnOutsideTouch; savedState.showMoveSuggestionUpBtn = this.mShowMoveUpSuggestion; savedState.showSearchKey = this.mShowSearchKey; savedState.isTitleSet = this.mIsTitleSet; savedState.backgroundColor = this.mBackgroundColor; savedState.suggestionsTextColor = this.mSuggestionTextColor; savedState.queryTextColor = this.mSearchInputTextColor; savedState.searchHintTextColor = this.mSearchInputHintColor; savedState.actionOverflowMenueColor = this.mOverflowIconColor; savedState.menuItemIconColor = this.mActionMenuItemColor; savedState.leftIconColor = this.mLeftActionIconColor; savedState.clearBtnColor = this.mClearBtnColor; savedState.suggestionUpBtnColor = this.mSuggestionTextColor; savedState.dividerColor = this.mDividerColor; savedState.menuId = mMenuId; savedState.leftActionMode = mLeftActionMode; savedState.dimBackground = mDimBackground; return savedState; } @Override public void onRestoreInstanceState(Parcelable state) { final SavedState savedState = (SavedState) state; super.onRestoreInstanceState(savedState.getSuperState()); this.mIsFocused = savedState.isFocused; this.mIsTitleSet = savedState.isTitleSet; this.mMenuId = savedState.menuId; this.mSuggestionSectionAnimDuration = savedState.suggestionsSectionAnimSuration; setSuggestionItemTextSize(savedState.suggestionTextSize); setDismissOnOutsideClick(savedState.dismissOnOutsideClick); setShowMoveUpSuggestion(savedState.showMoveSuggestionUpBtn); setShowSearchKey(savedState.showSearchKey); setSearchHint(savedState.searchHint); setBackgroundColor(savedState.backgroundColor); setSuggestionsTextColor(savedState.suggestionsTextColor); setQueryTextColor(savedState.queryTextColor); setHintTextColor(savedState.searchHintTextColor); setActionMenuOverflowColor(savedState.actionOverflowMenueColor); setMenuItemIconColor(savedState.menuItemIconColor); setLeftActionIconColor(savedState.leftIconColor); setClearBtnColor(savedState.clearBtnColor); setSuggestionRightIconColor(savedState.suggestionUpBtnColor); setDividerColor(savedState.dividerColor); setLeftActionMode(savedState.leftActionMode); setDimBackground(savedState.dimBackground); mSuggestionsSection.setEnabled(this.mIsFocused); if (this.mIsFocused) { mBackgroundDrawable.setAlpha(BACKGROUND_DRAWABLE_ALPHA_SEARCH_FOCUSED); mSkipTextChangeEvent = true; mSkipQueryFocusChangeEvent = true; mSuggestionsSection.setVisibility(VISIBLE); //restore suggestions list when suggestion section's height is fully set mSuggestionSecHeightListener = new OnSuggestionSecHeightSetListener() { @Override public void onSuggestionSecHeightSet() { swapSuggestions(savedState.suggestions, false); mSuggestionSecHeightListener = null; //todo refactor move to a better location transitionInLeftSection(false); } }; mClearButton.setVisibility((savedState.query.length() == 0) ? View.INVISIBLE : View.VISIBLE); mLeftAction.setVisibility(View.VISIBLE); Util.showSoftKeyboard(getContext(), mSearchInput); } } static class SavedState extends BaseSavedState { private List<? extends SearchSuggestion> suggestions = new ArrayList<>(); private boolean isFocused; private String query; private int suggestionTextSize; private String searchHint; private boolean dismissOnOutsideClick; private boolean showMoveSuggestionUpBtn; private boolean showSearchKey; private boolean isTitleSet; private int backgroundColor; private int suggestionsTextColor; private int queryTextColor; private int searchHintTextColor; private int actionOverflowMenueColor; private int menuItemIconColor; private int leftIconColor; private int clearBtnColor; private int suggestionUpBtnColor; private int dividerColor; private int menuId; private int leftActionMode; private boolean dimBackground; private long suggestionsSectionAnimSuration; SavedState(Parcelable superState) { super(superState); } private SavedState(Parcel in) { super(in); in.readList(suggestions, getClass().getClassLoader()); isFocused = (in.readInt() != 0); query = in.readString(); suggestionTextSize = in.readInt(); searchHint = in.readString(); dismissOnOutsideClick = (in.readInt() != 0); showMoveSuggestionUpBtn = (in.readInt() != 0); showSearchKey = (in.readInt() != 0); isTitleSet = (in.readInt() != 0); backgroundColor = in.readInt(); suggestionsTextColor = in.readInt(); queryTextColor = in.readInt(); searchHintTextColor = in.readInt(); actionOverflowMenueColor = in.readInt(); menuItemIconColor = in.readInt(); leftIconColor = in.readInt(); clearBtnColor = in.readInt(); suggestionUpBtnColor = in.readInt(); dividerColor = in.readInt(); menuId = in.readInt(); leftActionMode = in.readInt(); dimBackground = (in.readInt() != 0); suggestionsSectionAnimSuration = in.readLong(); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeList(suggestions); out.writeInt(isFocused ? 1 : 0); out.writeString(query); out.writeInt(suggestionTextSize); out.writeString(searchHint); out.writeInt(dismissOnOutsideClick ? 1 : 0); out.writeInt(showMoveSuggestionUpBtn ? 1 : 0); out.writeInt(showSearchKey ? 1 : 0); out.writeInt(isTitleSet ? 1 : 0); out.writeInt(backgroundColor); out.writeInt(suggestionsTextColor); out.writeInt(queryTextColor); out.writeInt(searchHintTextColor); out.writeInt(actionOverflowMenueColor); out.writeInt(menuItemIconColor); out.writeInt(leftIconColor); out.writeInt(clearBtnColor); out.writeInt(suggestionUpBtnColor); out.writeInt(dividerColor); out.writeInt(menuId); out.writeInt(leftActionMode); out.writeInt(dimBackground ? 1 : 0); out.writeLong(suggestionsSectionAnimSuration); } public static final Creator<SavedState> CREATOR = new Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); //remove any ongoing animations to prevent leaks //todo investigate if correct ViewCompat.animate(mSuggestionListContainer).cancel(); } }
library/src/main/java/com/arlib/floatingsearchview/FloatingSearchView.java
package com.arlib.floatingsearchview; /** * Copyright (C) 2015 Ari C. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.app.Activity; import android.content.Context; import android.content.ContextWrapper; import android.content.res.Configuration; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.IntDef; import android.support.v4.graphics.drawable.DrawableCompat; import android.support.v4.view.ViewCompat; import android.support.v4.view.ViewPropertyAnimatorListenerAdapter; import android.support.v4.view.ViewPropertyAnimatorUpdateListener; import android.support.v7.graphics.drawable.DrawerArrowDrawable; import android.support.v7.view.menu.MenuBuilder; import android.support.v7.widget.CardView; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.WindowManager; import android.view.animation.Interpolator; import android.view.animation.LinearInterpolator; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import com.arlib.floatingsearchview.suggestions.SearchSuggestionsAdapter; import com.arlib.floatingsearchview.suggestions.model.SearchSuggestion; import com.arlib.floatingsearchview.util.Util; import com.arlib.floatingsearchview.util.adapter.GestureDetectorListenerAdapter; import com.arlib.floatingsearchview.util.adapter.OnItemTouchListenerAdapter; import com.arlib.floatingsearchview.util.adapter.TextWatcherAdapter; import com.arlib.floatingsearchview.util.view.MenuView; import com.bartoszlipinski.viewpropertyobjectanimator.ViewPropertyObjectAnimator; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * A search UI widget that implements a floating search box also called persistent * search. */ public class FloatingSearchView extends FrameLayout { private static final String TAG = "FloatingSearchView"; private static final int CARD_VIEW_TOP_BOTTOM_SHADOW_HEIGHT = 3; private static final int CARD_VIEW_CORNERS_AND_TOP_BOTTOM_SHADOW_HEIGHT = 5; private static final long CLEAR_BTN_FADE_ANIM_DURATION = 500; private static final int CLEAR_BTN_WIDTH = 48; private static final int LEFT_MENU_WIDTH_AND_MARGIN_START = 52; private final int BACKGROUND_DRAWABLE_ALPHA_SEARCH_FOCUSED = 150; private final int BACKGROUND_DRAWABLE_ALPHA_SEARCH_NOT_FOCUSED = 0; private final int BACKGROUND_FADE_ANIM_DURATION = 250; private final int MENU_ICON_ANIM_DURATION = 250; private final int ATTRS_SEARCH_BAR_MARGIN_DEFAULT = 0; public final static int LEFT_ACTION_MODE_SHOW_HAMBURGER = 1; public final static int LEFT_ACTION_MODE_SHOW_SEARCH = 2; public final static int LEFT_ACTION_MODE_SHOW_HOME = 3; public final static int LEFT_ACTION_MODE_NO_LEFT_ACTION = 4; private final static int LEFT_ACTION_MODE_NOT_SET = -1; @Retention(RetentionPolicy.SOURCE) @IntDef({LEFT_ACTION_MODE_SHOW_HAMBURGER, LEFT_ACTION_MODE_SHOW_SEARCH, LEFT_ACTION_MODE_SHOW_HOME, LEFT_ACTION_MODE_NO_LEFT_ACTION, LEFT_ACTION_MODE_NOT_SET}) public @interface LeftActionMode { } @LeftActionMode private final int ATTRS_SEARCH_BAR_LEFT_ACTION_MODE_DEFAULT = LEFT_ACTION_MODE_NO_LEFT_ACTION; private final boolean ATTRS_SHOW_MOVE_UP_SUGGESTION_DEFAULT = false; private final boolean ATTRS_DISMISS_ON_OUTSIDE_TOUCH_DEFAULT = true; private final boolean ATTRS_SEARCH_BAR_SHOW_SEARCH_KEY_DEFAULT = true; private final int ATTRS_SUGGESTION_TEXT_SIZE_SP_DEFAULT = 18; private final boolean ATTRS_SHOW_DIM_BACKGROUND_DEFAULT = true; private final Interpolator SUGGEST_ITEM_ADD_ANIM_INTERPOLATOR = new LinearInterpolator(); private final int ATTRS_SUGGESTION_ANIM_DURATION_DEFAULT = 250; private Activity mHostActivity; private View mMainLayout; private Drawable mBackgroundDrawable; private boolean mDimBackground; private boolean mDismissOnOutsideTouch = true; private boolean mIsFocused; private OnFocusChangeListener mFocusChangeListener; private CardView mQuerySection; private OnSearchListener mSearchListener; private EditText mSearchInput; private String mTitleText; private boolean mIsTitleSet; private int mSearchInputTextColor = -1; private int mSearchInputHintColor = -1; private View mSearchInputParent; private String mOldQuery = ""; private OnQueryChangeListener mQueryListener; private ImageView mLeftAction; private OnLeftMenuClickListener mOnMenuClickListener; private OnHomeActionClickListener mOnHomeActionClickListener; private ProgressBar mSearchProgress; private DrawerArrowDrawable mMenuBtnDrawable; private Drawable mIconBackArrow; private Drawable mIconSearch; @LeftActionMode int mLeftActionMode = LEFT_ACTION_MODE_NOT_SET; private int mLeftActionIconColor; private String mSearchHint; private boolean mShowSearchKey; private boolean mMenuOpen = false; private MenuView mMenuView; private int mMenuId = -1; private int mActionMenuItemColor; private int mOverflowIconColor; private OnMenuItemClickListener mActionMenuItemListener; private ImageView mClearButton; private int mClearBtnColor; private Drawable mIconClear; private int mBackgroundColor; private boolean mSkipQueryFocusChangeEvent; private boolean mSkipTextChangeEvent; private View mDivider; private int mDividerColor; private RelativeLayout mSuggestionsSection; private View mSuggestionListContainer; private RecyclerView mSuggestionsList; private int mSuggestionTextColor = -1; private int mSuggestionRightIconColor; private SearchSuggestionsAdapter mSuggestionsAdapter; private SearchSuggestionsAdapter.OnBindSuggestionCallback mOnBindSuggestionCallback; private int mSuggestionsTextSizePx; private boolean mIsInitialLayout = true; private boolean mIsSuggestionsSecHeightSet; private boolean mShowMoveUpSuggestion = ATTRS_SHOW_MOVE_UP_SUGGESTION_DEFAULT; private OnSuggestionsListHeightChanged mOnSuggestionsListHeightChanged; private long mSuggestionSectionAnimDuration; //An interface for implementing a listener that will get notified when the suggestions //section's height is set. This is to be used internally only. private interface OnSuggestionSecHeightSetListener { void onSuggestionSecHeightSet(); } private OnSuggestionSecHeightSetListener mSuggestionSecHeightListener; /** * Interface for implementing a listener to listen * changes in suggestion list height that occur when the list is expands/shrinks * because of calls to {@link FloatingSearchView#swapSuggestions(List)} */ public interface OnSuggestionsListHeightChanged { void onSuggestionsListHeightChanged(float newHeight); } /** * Interface for implementing a listener to listen * to state changes in the query text. */ public interface OnQueryChangeListener { /** * Called when the query has changed. It will * be invoked when one or more characters in the * query was changed. * * @param oldQuery the previous query * @param newQuery the new query */ void onSearchTextChanged(String oldQuery, String newQuery); } /** * Interface for implementing a listener to listen * to when the current search has completed. */ public interface OnSearchListener { /** * Called when a suggestion was clicked indicating * that the current search has completed. * * @param searchSuggestion */ void onSuggestionClicked(SearchSuggestion searchSuggestion); /** * Called when the current search has completed * as a result of pressing search key in the keyboard. * <p/> * Note: This will only get called if * {@link FloatingSearchView#setShowSearchKey(boolean)}} is set to true. * * @param currentQuery the text that is currently set in the query TextView */ void onSearchAction(String currentQuery); } /** * Interface for implementing a callback to be * invoked when the left menu (navigation menu) is * clicked. * <p/> * Note: This is only relevant when leftActionMode is * set to {@value #LEFT_ACTION_MODE_SHOW_HAMBURGER} */ public interface OnLeftMenuClickListener { /** * Called when the menu button was * clicked and the menu's state is now opened. */ void onMenuOpened(); /** * Called when the back button was * clicked and the menu's state is now closed. */ void onMenuClosed(); } /** * Interface for implementing a callback to be * invoked when the home action button (the back arrow) * is clicked. * <p/> * Note: This is only relevant when leftActionMode is * set to {@value #LEFT_ACTION_MODE_SHOW_HOME} */ public interface OnHomeActionClickListener { /** * Called when the home button was * clicked. */ void onHomeClicked(); } /** * Interface for implementing a listener to listen * when an item in the action (the item can be presented as an action * ,or as a menu item in the overflow menu) menu has been selected. */ public interface OnMenuItemClickListener { /** * Called when a menu item in has been * selected. * * @param item the selected menu item. */ void onActionMenuItemSelected(MenuItem item); } /** * Interface for implementing a listener to listen * to for focus state changes. */ public interface OnFocusChangeListener { /** * Called when the search bar has gained focus * and listeners are now active. */ void onFocus(); /** * Called when the search bar has lost focus * and listeners are no more active. */ void onFocusCleared(); } public FloatingSearchView(Context context) { this(context, null); } public FloatingSearchView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } private void init(AttributeSet attrs) { mHostActivity = getHostActivity(); LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); mMainLayout = inflate(getContext(), R.layout.floating_search_layout, this); mBackgroundDrawable = new ColorDrawable(Color.BLACK); mQuerySection = (CardView) findViewById(R.id.search_query_section); mClearButton = (ImageView) findViewById(R.id.clear_btn); mSearchInput = (EditText) findViewById(R.id.search_bar_text); mSearchInputParent = findViewById(R.id.search_input_parent); mLeftAction = (ImageView) findViewById(R.id.left_action); mSearchProgress = (ProgressBar) findViewById(R.id.search_bar_search_progress); initDrawables(); mClearButton.setImageDrawable(mIconClear); mMenuView = (MenuView) findViewById(R.id.menu_view); mDivider = findViewById(R.id.divider); mSuggestionsSection = (RelativeLayout) findViewById(R.id.search_suggestions_section); mSuggestionListContainer = findViewById(R.id.suggestions_list_container); mSuggestionsList = (RecyclerView) findViewById(R.id.suggestions_list); setupViews(attrs); } private Activity getHostActivity() { Context context = getContext(); while (context instanceof ContextWrapper) { if (context instanceof Activity) { return (Activity) context; } context = ((ContextWrapper) context).getBaseContext(); } return null; } private void initDrawables() { mMenuBtnDrawable = new DrawerArrowDrawable(getContext()); mIconClear = Util.getWrappedDrawable(getContext(), R.drawable.ic_clear_black_24dp); mIconBackArrow = Util.getWrappedDrawable(getContext(), R.drawable.ic_arrow_back_black_24dp); mIconSearch = Util.getWrappedDrawable(getContext(), R.drawable.ic_search_black_24dp); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); if (mIsInitialLayout) { //we need to add 5dp to the mSuggestionsSection because we are //going to move it up by 5dp in order to cover the search bar's //shadow padding and rounded corners. We also need to add an additional 10dp to //mSuggestionsSection in order to hide mSuggestionListContainer's //rounded corners and shadow for both, top and bottom. int addedHeight = 3 * Util.dpToPx(CARD_VIEW_CORNERS_AND_TOP_BOTTOM_SHADOW_HEIGHT); final int finalHeight = mSuggestionsSection.getHeight() + addedHeight; mSuggestionsSection.getLayoutParams().height = finalHeight; mSuggestionsSection.requestLayout(); ViewTreeObserver vto = mSuggestionListContainer.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (mSuggestionsSection.getHeight() == finalHeight) { Util.removeGlobalLayoutObserver(mSuggestionListContainer, this); mIsSuggestionsSecHeightSet = true; moveSuggestListToInitialPos(); if (mSuggestionSecHeightListener != null) { mSuggestionSecHeightListener.onSuggestionSecHeightSet(); mSuggestionSecHeightListener = null; } } } }); mIsInitialLayout = false; refreshDimBackground(); if(isInEditMode()) { inflateOverflowMenu(mMenuId); } } } private void setupViews(AttributeSet attrs) { mSuggestionsSection.setEnabled(false); if (attrs != null) { applyXmlAttributes(attrs); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { setBackground(mBackgroundDrawable); } else { setBackgroundDrawable(mBackgroundDrawable); } setupQueryBar(); if (!isInEditMode()) { setupSuggestionSection(); } } private void applyXmlAttributes(AttributeSet attrs) { TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.FloatingSearchView); try { int searchBarWidth = a.getDimensionPixelSize( R.styleable.FloatingSearchView_floatingSearch_searchBarWidth, ViewGroup.LayoutParams.MATCH_PARENT); mQuerySection.getLayoutParams().width = searchBarWidth; mDivider.getLayoutParams().width = searchBarWidth; mSuggestionListContainer.getLayoutParams().width = searchBarWidth; int searchBarLeftMargin = a.getDimensionPixelSize( R.styleable.FloatingSearchView_floatingSearch_searchBarMarginLeft, ATTRS_SEARCH_BAR_MARGIN_DEFAULT); int searchBarTopMargin = a.getDimensionPixelSize( R.styleable.FloatingSearchView_floatingSearch_searchBarMarginTop, ATTRS_SEARCH_BAR_MARGIN_DEFAULT); int searchBarRightMargin = a.getDimensionPixelSize( R.styleable.FloatingSearchView_floatingSearch_searchBarMarginRight, ATTRS_SEARCH_BAR_MARGIN_DEFAULT); LayoutParams querySectionLP = (LayoutParams) mQuerySection.getLayoutParams(); LayoutParams dividerLP = (LayoutParams) mDivider.getLayoutParams(); LinearLayout.LayoutParams suggestListSectionLP = (LinearLayout.LayoutParams) mSuggestionsSection.getLayoutParams(); int cardPadding = Util.dpToPx(CARD_VIEW_TOP_BOTTOM_SHADOW_HEIGHT); querySectionLP.setMargins(searchBarLeftMargin, searchBarTopMargin, searchBarRightMargin, 0); dividerLP.setMargins(searchBarLeftMargin + cardPadding, 0, searchBarRightMargin + cardPadding, ((MarginLayoutParams) mDivider.getLayoutParams()).bottomMargin); suggestListSectionLP.setMargins(searchBarLeftMargin, 0, searchBarRightMargin, 0); mQuerySection.setLayoutParams(querySectionLP); mDivider.setLayoutParams(dividerLP); mSuggestionsSection.setLayoutParams(suggestListSectionLP); setSearchHint(a.getString(R.styleable.FloatingSearchView_floatingSearch_searchHint)); setShowSearchKey(a.getBoolean(R.styleable.FloatingSearchView_floatingSearch_showSearchKey, ATTRS_SEARCH_BAR_SHOW_SEARCH_KEY_DEFAULT)); setDismissOnOutsideClick(a.getBoolean(R.styleable.FloatingSearchView_floatingSearch_dismissOnOutsideTouch, ATTRS_DISMISS_ON_OUTSIDE_TOUCH_DEFAULT)); setSuggestionItemTextSize(a.getDimensionPixelSize( R.styleable.FloatingSearchView_floatingSearch_searchSuggestionTextSize, Util.spToPx(ATTRS_SUGGESTION_TEXT_SIZE_SP_DEFAULT))); //noinspection ResourceType mLeftActionMode = a.getInt(R.styleable.FloatingSearchView_floatingSearch_leftActionMode, ATTRS_SEARCH_BAR_LEFT_ACTION_MODE_DEFAULT); if (a.hasValue(R.styleable.FloatingSearchView_floatingSearch_menu)) { mMenuId = a.getResourceId(R.styleable.FloatingSearchView_floatingSearch_menu, -1); } setDimBackground(a.getBoolean(R.styleable.FloatingSearchView_floatingSearch_dimBackground, ATTRS_SHOW_DIM_BACKGROUND_DEFAULT)); setShowMoveUpSuggestion(a.getBoolean(R.styleable.FloatingSearchView_floatingSearch_showMoveSuggestionUp, ATTRS_SHOW_MOVE_UP_SUGGESTION_DEFAULT)); this.mSuggestionSectionAnimDuration = a.getInt(R.styleable.FloatingSearchView_floatingSearch_suggestionsListAnimDuration, ATTRS_SUGGESTION_ANIM_DURATION_DEFAULT); setBackgroundColor(a.getColor(R.styleable.FloatingSearchView_floatingSearch_backgroundColor , Util.getColor(getContext(), R.color.background))); setLeftActionIconColor(a.getColor(R.styleable.FloatingSearchView_floatingSearch_leftActionColor , Util.getColor(getContext(), R.color.left_action_icon))); setActionMenuOverflowColor(a.getColor(R.styleable.FloatingSearchView_floatingSearch_actionMenuOverflowColor , Util.getColor(getContext(), R.color.overflow_icon_color))); setMenuItemIconColor(a.getColor(R.styleable.FloatingSearchView_floatingSearch_menuItemIconColor , Util.getColor(getContext(), R.color.menu_icon_color))); setDividerColor(a.getColor(R.styleable.FloatingSearchView_floatingSearch_dividerColor , Util.getColor(getContext(), R.color.divider))); setClearBtnColor(a.getColor(R.styleable.FloatingSearchView_floatingSearch_clearBtnColor , Util.getColor(getContext(), R.color.clear_btn_color))); setViewTextColor(a.getColor(R.styleable.FloatingSearchView_floatingSearch_viewTextColor , Util.getColor(getContext(), R.color.dark_gray))); setHintTextColor(a.getColor(R.styleable.FloatingSearchView_floatingSearch_hintTextColor , Util.getColor(getContext(), R.color.hint_color))); setSuggestionRightIconColor(a.getColor(R.styleable.FloatingSearchView_floatingSearch_suggestionRightIconColor , Util.getColor(getContext(), R.color.gray_active_icon))); } finally { a.recycle(); } } private void setupQueryBar() { mSearchInput.setTextColor(mSearchInputTextColor); mSearchInput.setHintTextColor(mSearchInputHintColor); if (!isInEditMode() && mHostActivity != null) { mHostActivity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); } ViewTreeObserver vto = mQuerySection.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { Util.removeGlobalLayoutObserver(mQuerySection, this); inflateOverflowMenu(mMenuId); } }); mMenuView.setMenuCallback(new MenuBuilder.Callback() { @Override public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) { if (mActionMenuItemListener != null) { mActionMenuItemListener.onActionMenuItemSelected(item); } //todo check if we should care about this return or not return false; } @Override public void onMenuModeChange(MenuBuilder menu) { } }); mMenuView.setOnVisibleWidthChanged(new MenuView.OnVisibleWidthChangedListener() { @Override public void onItemsMenuVisibleWidthChanged(int newVisibleWidth) { if (newVisibleWidth == 0) { mClearButton.setTranslationX(-Util.dpToPx(4)); int paddingRight = newVisibleWidth + Util.dpToPx(4); if (mIsFocused) { paddingRight += Util.dpToPx(CLEAR_BTN_WIDTH); } mSearchInput.setPadding(0, 0, paddingRight, 0); } else { mClearButton.setTranslationX(-newVisibleWidth); int paddingRight = newVisibleWidth; if (mIsFocused) { paddingRight += Util.dpToPx(CLEAR_BTN_WIDTH); } mSearchInput.setPadding(0, 0, paddingRight, 0); } } }); mMenuView.setActionIconColor(mActionMenuItemColor); mMenuView.setOverflowColor(mOverflowIconColor); mClearButton.setVisibility(View.INVISIBLE); mClearButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mSearchInput.setText(""); } }); mSearchInput.addTextChangedListener(new TextWatcherAdapter() { public void onTextChanged(final CharSequence s, int start, int before, int count) { //todo investigate why this is called twice when pressing back on the keyboard if (mSkipTextChangeEvent || !mIsFocused) { mSkipTextChangeEvent = false; } else { if (mSearchInput.getText().toString().length() != 0 && mClearButton.getVisibility() == View.INVISIBLE) { mClearButton.setAlpha(0.0f); mClearButton.setVisibility(View.VISIBLE); ViewCompat.animate(mClearButton).alpha(1.0f).setDuration(CLEAR_BTN_FADE_ANIM_DURATION).start(); } else if (mSearchInput.getText().toString().length() == 0) { mClearButton.setVisibility(View.INVISIBLE); } if (mQueryListener != null && mIsFocused && !mOldQuery.equals(mSearchInput.getText().toString())) { mQueryListener.onSearchTextChanged(mOldQuery, mSearchInput.getText().toString()); } mOldQuery = mSearchInput.getText().toString(); } } }); mSearchInput.setOnFocusChangeListener(new TextView.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (mSkipQueryFocusChangeEvent) { mSkipQueryFocusChangeEvent = false; } else if (hasFocus != mIsFocused) { setSearchFocusedInternal(hasFocus); } } }); mSearchInput.setOnKeyListener(new OnKeyListener() { public boolean onKey(View view, int keyCode, KeyEvent keyEvent) { if (mShowSearchKey && keyCode == KeyEvent.KEYCODE_ENTER) { if (mSearchListener != null) { mSearchListener.onSearchAction(getQuery()); } mSkipTextChangeEvent = true; setSearchBarTitle(getQuery()); setSearchFocusedInternal(false); return true; } return false; } }); mLeftAction.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (isSearchBarFocused()) { setSearchFocusedInternal(false); } else { switch (mLeftActionMode) { case LEFT_ACTION_MODE_SHOW_HAMBURGER: toggleLeftMenu(); break; case LEFT_ACTION_MODE_SHOW_SEARCH: setSearchFocusedInternal(true); break; case LEFT_ACTION_MODE_SHOW_HOME: if (mOnHomeActionClickListener != null) { mOnHomeActionClickListener.onHomeClicked(); } break; case LEFT_ACTION_MODE_NO_LEFT_ACTION: //do nothing break; } } } }); refreshLeftIcon(); } private int actionMenuAvailWidth() { if(isInEditMode()){ return mQuerySection.getMeasuredWidth() / 2; } return mQuerySection.getWidth() / 2; } /** * Sets the menu button's color. * * @param color the color to be applied to the * left menu button. */ public void setLeftActionIconColor(int color) { mLeftActionIconColor = color; mMenuBtnDrawable.setColor(color); DrawableCompat.setTint(mIconBackArrow, color); DrawableCompat.setTint(mIconSearch, color); } /** * Sets the clear button's color. * * @param color the color to be applied to the * clear button. */ public void setClearBtnColor(int color) { mClearBtnColor = color; DrawableCompat.setTint(mIconClear, mClearBtnColor); } /** * Sets the action menu icons' color. * * @param color the color to be applied to the * action menu items. */ public void setMenuItemIconColor(int color) { this.mActionMenuItemColor = color; if (mMenuView != null) { mMenuView.setActionIconColor(this.mActionMenuItemColor); } } /** * Sets the action menu overflow icon's color. * * @param color the color to be applied to the * overflow icon. */ public void setActionMenuOverflowColor(int color) { this.mOverflowIconColor = color; if (mMenuView != null) { mMenuView.setOverflowColor(this.mOverflowIconColor); } } /** * Sets the background color of the search * view including the suggestions section. * * @param color the color to be applied to the search bar and * the suggestion section background. */ public void setBackgroundColor(int color) { mBackgroundColor = color; if (mQuerySection != null && mSuggestionsList != null) { mQuerySection.setCardBackgroundColor(color); mSuggestionsList.setBackgroundColor(color); } } /** * Sets the text color of the search * and suggestion text. * * @param color the color to be applied to the search and suggestion * text. */ public void setViewTextColor(int color) { setSuggestionsTextColor(color); setQueryTextColor(color); } /** * Sets the text color of suggestion text. * * @param color */ public void setSuggestionsTextColor(int color) { mSuggestionTextColor = color; if (mSuggestionsAdapter != null) { mSuggestionsAdapter.setTextColor(mSuggestionTextColor); } } /** * Set the duration for the suggestions list expand/collapse * animation. * * @param duration */ public void setSuggestionsAnimDuration(long duration) { this.mSuggestionSectionAnimDuration = duration; } /** * Sets the text color of the search text. * * @param color */ public void setQueryTextColor(int color) { mSearchInputTextColor = color; if (mSearchInput != null) { mSearchInput.setTextColor(mSearchInputTextColor); } } /** * Sets the text color of the search * hint. * * @param color the color to be applied to the search hint. */ public void setHintTextColor(int color) { this.mSearchInputHintColor = color; if (mSearchInput != null) { mSearchInput.setHintTextColor(color); } } /** * Sets the color of the search divider that * divides the search section from the suggestions. * * @param color the color to be applied the divider. */ public void setDividerColor(int color) { mDividerColor = color; if (mDivider != null) { mDivider.setBackgroundColor(mDividerColor); } } /** * Set the tint of the suggestion items' right btn (move suggestion to * query) * * @param color */ public void setSuggestionRightIconColor(int color) { this.mSuggestionRightIconColor = color; if (mSuggestionsAdapter != null) { mSuggestionsAdapter.setRightIconColor(this.mSuggestionRightIconColor); } } /** * Set the text size of the suggestion items. * * @param sizePx */ private void setSuggestionItemTextSize(int sizePx) { //todo implement dynamic suggestionTextSize setter and expose method this.mSuggestionsTextSizePx = sizePx; } /** * Set the mode for the left action button. * * @param mode */ public void setLeftActionMode(@LeftActionMode int mode) { mLeftActionMode = mode; refreshLeftIcon(); } private void refreshLeftIcon() { int leftActionWidthAndMarginLeft = Util.dpToPx(LEFT_MENU_WIDTH_AND_MARGIN_START); int queryTranslationX = 0; mLeftAction.setVisibility(VISIBLE); switch (mLeftActionMode) { case LEFT_ACTION_MODE_SHOW_HAMBURGER: mLeftAction.setImageDrawable(mMenuBtnDrawable); break; case LEFT_ACTION_MODE_SHOW_SEARCH: mLeftAction.setImageDrawable(mIconSearch); break; case LEFT_ACTION_MODE_SHOW_HOME: mLeftAction.setImageDrawable(mMenuBtnDrawable); mMenuBtnDrawable.setProgress(1.0f); break; case LEFT_ACTION_MODE_NO_LEFT_ACTION: mLeftAction.setVisibility(View.INVISIBLE); queryTranslationX = -leftActionWidthAndMarginLeft; break; } mSearchInputParent.setTranslationX(queryTranslationX); } private void toggleLeftMenu() { if (mMenuOpen) { closeMenu(true); } else { openMenu(true); } } /** * <p/> * Enables clients to directly manipulate * the menu icon's progress. * <p/> * Useful for custom animation/behaviors. * * @param progress the desired progress of the menu * icon's rotation: 0.0 == hamburger * shape, 1.0 == back arrow shape */ public void setMenuIconProgress(float progress) { mMenuBtnDrawable.setProgress(progress); if (progress == 0) { closeMenu(false); } else if (progress == 1.0) { openMenu(false); } } /** * Mimics a menu click that opens the menu. Useful when for navigation * drawers when they open as a result of dragging. */ public void openMenu(boolean withAnim) { mMenuOpen = true; openMenuDrawable(mMenuBtnDrawable, withAnim); if (mOnMenuClickListener != null) { mOnMenuClickListener.onMenuOpened(); } } /** * Mimics a menu click that closes. Useful when fo navigation * drawers when they close as a result of selecting and item. * * @param withAnim true, will close the menu button with * the Material animation */ public void closeMenu(boolean withAnim) { mMenuOpen = false; closeMenuDrawable(mMenuBtnDrawable, withAnim); if (mOnMenuClickListener != null) { mOnMenuClickListener.onMenuClosed(); } } /** * Set the hamburger menu to open or closed without * animating hamburger to arrow and without calling listeners. * * @param isOpen */ public void setLeftMenuOpen(boolean isOpen) { mMenuOpen = isOpen; mMenuBtnDrawable.setProgress(isOpen ? 1.0f : 0.0f); } /** * Shows a circular progress on top of the * menu action button. * <p/> * Call hidProgress() * to change back to normal and make the menu * action visible. */ public void showProgress() { mLeftAction.setVisibility(View.GONE); mSearchProgress.setAlpha(0.0f); mSearchProgress.setVisibility(View.VISIBLE); ObjectAnimator.ofFloat(mSearchProgress, "alpha", 0.0f, 1.0f).start(); } /** * Hides the progress bar after * a prior call to showProgress() */ public void hideProgress() { mSearchProgress.setVisibility(View.GONE); mLeftAction.setAlpha(0.0f); mLeftAction.setVisibility(View.VISIBLE); ObjectAnimator.ofFloat(mLeftAction, "alpha", 0.0f, 1.0f).start(); } /** * Inflates the menu items from * an xml resource. * * @param menuId a menu xml resource reference */ public void inflateOverflowMenu(int menuId) { mMenuId = menuId; mMenuView.reset(menuId, actionMenuAvailWidth()); if (mIsFocused) { mMenuView.hideIfRoomItems(false); } } /** * Set a hint that will appear in the * search input. Default hint is R.string.abc_search_hint * which is "search..." (when device language is set to english) * * @param searchHint */ public void setSearchHint(String searchHint) { mSearchHint = searchHint != null ? searchHint : getResources().getString(R.string.abc_search_hint); mSearchInput.setHint(mSearchHint); } /** * Sets whether the the button with the search icon * will appear in the soft-keyboard or not. * * @param show to show the search button in * the soft-keyboard. */ public void setShowSearchKey(boolean show) { mShowSearchKey = show; if (show) { mSearchInput.setImeOptions(EditorInfo.IME_ACTION_SEARCH); } else { mSearchInput.setImeOptions(EditorInfo.IME_ACTION_NONE); } } /** * Set whether a touch outside of the * search bar's bounds will cause the search bar to * loos focus. * * @param enable true to dismiss on outside touch, false otherwise. */ public void setDismissOnOutsideClick(boolean enable) { mDismissOnOutsideTouch = enable; mSuggestionsSection.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { //todo check if this is called twice if (mDismissOnOutsideTouch && mIsFocused) { setSearchFocusedInternal(false); } return true; } }); } /** * Sets whether a dim background will show when the search is focused * * @param dimEnabled True to show dim */ public void setDimBackground(boolean dimEnabled) { this.mDimBackground = dimEnabled; refreshDimBackground(); } private void refreshDimBackground() { if (this.mDimBackground && mIsFocused) { mBackgroundDrawable.setAlpha(BACKGROUND_DRAWABLE_ALPHA_SEARCH_FOCUSED); } else { mBackgroundDrawable.setAlpha(BACKGROUND_DRAWABLE_ALPHA_SEARCH_NOT_FOCUSED); } } /** * Sets the arrow up of suggestion items to be enabled and visible or * disabled and invisible. * * @param show */ public void setShowMoveUpSuggestion(boolean show) { mShowMoveUpSuggestion = show; refreshShowMoveUpSuggestion(); } private void refreshShowMoveUpSuggestion() { if (mSuggestionsAdapter != null) { mSuggestionsAdapter.setShowMoveUpIcon(mShowMoveUpSuggestion); } } /** * Wrapper implementation for EditText.setFocusable(boolean focusable) * * @param focusable true, to make search focus when * clicked. */ public void setSearchFocusable(boolean focusable) { mSearchInput.setFocusable(focusable); } /** * Sets the title for the search bar. * <p/> * Note that after the title is set, when * the search gains focus, the title will be replaced * by the search hint. * * @param title the title to be shown when search * is not focused */ public void setSearchBarTitle(CharSequence title) { this.mTitleText = title.toString(); mIsTitleSet = true; mSearchInput.setText(title); } /** * Sets the search text. * <p/> * Note that this is the different from * {@link #setSearchBarTitle(CharSequence title) setSearchBarTitle} in * that it keeps the text when the search gains focus. * * @param text the text to be set for the search * input. */ public void setSearchText(CharSequence text) { mIsTitleSet = false; mSearchInput.setText(text); } /** * Returns the current query text. * * @return the current query */ public String getQuery() { return mSearchInput.getText().toString(); } public void clearQuery() { mSearchInput.setText(""); } /** * Sets whether the search is focused or not. * * @param focused true, to set the search to be active/focused. * @return true if the search was focused and will now become not focused. Useful for * calling supper.onBackPress() in the hosting activity only if this method returns false */ public boolean setSearchFocused(final boolean focused) { boolean updatedToNotFocused = !focused && this.mIsFocused; if ((focused != this.mIsFocused) && mSuggestionSecHeightListener == null) { if (mIsSuggestionsSecHeightSet) { setSearchFocusedInternal(focused); } else { mSuggestionSecHeightListener = new OnSuggestionSecHeightSetListener() { @Override public void onSuggestionSecHeightSet() { setSearchFocusedInternal(focused); mSuggestionSecHeightListener = null; } }; } } return updatedToNotFocused; } private void setupSuggestionSection() { LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, true); mSuggestionsList.setLayoutManager(layoutManager); mSuggestionsList.setItemAnimator(null); final GestureDetector gestureDetector = new GestureDetector(getContext(), new GestureDetectorListenerAdapter() { @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { if (mHostActivity != null) { Util.closeSoftKeyboard(mHostActivity); } return false; } }); mSuggestionsList.addOnItemTouchListener(new OnItemTouchListenerAdapter() { @Override public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) { gestureDetector.onTouchEvent(e); return false; } }); mSuggestionsAdapter = new SearchSuggestionsAdapter(getContext(), mSuggestionsTextSizePx, new SearchSuggestionsAdapter.Listener() { @Override public void onItemSelected(SearchSuggestion item) { if (mSearchListener != null) { mSearchListener.onSuggestionClicked(item); } mSkipTextChangeEvent = true; setSearchBarTitle(item.getBody()); setSearchFocusedInternal(false); } @Override public void onMoveItemToSearchClicked(SearchSuggestion item) { mSearchInput.setText(item.getBody()); //move cursor to end of text mSearchInput.setSelection(mSearchInput.getText().length()); } }); refreshShowMoveUpSuggestion(); mSuggestionsAdapter.setTextColor(this.mSuggestionTextColor); mSuggestionsAdapter.setRightIconColor(this.mSuggestionRightIconColor); mSuggestionsList.setAdapter(mSuggestionsAdapter); int cardViewBottomPadding = Util.dpToPx(CARD_VIEW_CORNERS_AND_TOP_BOTTOM_SHADOW_HEIGHT); //move up the suggestions section enough to cover the search bar //card's bottom left and right corners mSuggestionsSection.setTranslationY(-cardViewBottomPadding); } private void moveSuggestListToInitialPos() { //move the suggestions list to the collapsed position //which is translationY of -listContainerHeight mSuggestionListContainer.setTranslationY(-mSuggestionListContainer.getHeight()); } /** * Clears the current suggestions and replaces it * with the provided list of new suggestions. * * @param newSearchSuggestions a list containing the new suggestions */ public void swapSuggestions(final List<? extends SearchSuggestion> newSearchSuggestions) { Collections.reverse(newSearchSuggestions); swapSuggestions(newSearchSuggestions, true); } private void swapSuggestions(final List<? extends SearchSuggestion> newSearchSuggestions, final boolean withAnim) { mSuggestionsList.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { Util.removeGlobalLayoutObserver(mSuggestionsList, this); updateSuggestionsSectionHeight(newSearchSuggestions, withAnim); } }); mSuggestionsAdapter.swapData(newSearchSuggestions); mDivider.setVisibility(!newSearchSuggestions.isEmpty() ? View.VISIBLE : View.GONE); } private void updateSuggestionsSectionHeight(List<? extends SearchSuggestion> newSearchSuggestions, boolean withAnim) { final int cardTopBottomShadowPadding = Util.dpToPx(CARD_VIEW_CORNERS_AND_TOP_BOTTOM_SHADOW_HEIGHT); final int cardRadiusSize = Util.dpToPx(CARD_VIEW_TOP_BOTTOM_SHADOW_HEIGHT); int visibleSuggestionHeight = calculateSuggestionItemsHeight(newSearchSuggestions, mSuggestionListContainer.getHeight()); int diff = mSuggestionListContainer.getHeight() - visibleSuggestionHeight; int addedTranslationYForShadowOffsets = (diff <= cardTopBottomShadowPadding) ? -(cardTopBottomShadowPadding - diff) : diff < (mSuggestionListContainer.getHeight()-cardTopBottomShadowPadding) ? cardRadiusSize : 0; final float newTranslationY = -mSuggestionListContainer.getHeight() + visibleSuggestionHeight + addedTranslationYForShadowOffsets; final boolean animateAtEnd = newTranslationY >= mSuggestionListContainer.getTranslationY(); //todo go over final float fullyInvisibleTranslationY = -mSuggestionListContainer.getHeight() + cardRadiusSize; ViewCompat.animate(mSuggestionListContainer).cancel(); if (withAnim) { ViewCompat.animate(mSuggestionListContainer). setInterpolator(SUGGEST_ITEM_ADD_ANIM_INTERPOLATOR). setDuration(mSuggestionSectionAnimDuration). translationY(newTranslationY) .setUpdateListener(new ViewPropertyAnimatorUpdateListener() { @Override public void onAnimationUpdate(View view) { if (mOnSuggestionsListHeightChanged != null) { float newSuggestionsHeight = Math.abs(view.getTranslationY() - fullyInvisibleTranslationY); mOnSuggestionsListHeightChanged.onSuggestionsListHeightChanged(newSuggestionsHeight); } } }) .setListener(new ViewPropertyAnimatorListenerAdapter() { @Override public void onAnimationCancel(View view) { mSuggestionListContainer.setTranslationY(newTranslationY); } @Override public void onAnimationStart(View view) { if (!animateAtEnd) { mSuggestionsList.smoothScrollToPosition(0); } } @Override public void onAnimationEnd(View view) { if (animateAtEnd) { int lastPos = mSuggestionsList.getAdapter().getItemCount() - 1; if (lastPos > -1) { mSuggestionsList.smoothScrollToPosition(lastPos); } } } }).start(); } else { mSuggestionListContainer.setTranslationY(newTranslationY); if (mOnSuggestionsListHeightChanged != null) { float newSuggestionsHeight = Math.abs(mSuggestionListContainer.getTranslationY() - fullyInvisibleTranslationY); mOnSuggestionsListHeightChanged.onSuggestionsListHeightChanged(newSuggestionsHeight); } } } //returns the cumulative height that the current suggestion items take up or the given max if the //results is >= max. The max option allows us to avoid doing unnecessary and potentially long calculations. private int calculateSuggestionItemsHeight(List<? extends SearchSuggestion> suggestions, int max) { int visibleItemsHeight = 0; for (int i = 0; i < suggestions.size() && i < mSuggestionsList.getChildCount(); i++) { visibleItemsHeight += mSuggestionsList.getChildAt(i).getHeight(); if (visibleItemsHeight > max) { visibleItemsHeight = max; break; } } return visibleItemsHeight; } /** * Set a callback that will be called after each suggestion view in the suggestions recycler * list is bound. This allows for customized binding for specific items in the list. * * @param callback A callback to be called after a suggestion is bound by the suggestions list's * adapter. */ public void setOnBindSuggestionCallback(SearchSuggestionsAdapter.OnBindSuggestionCallback callback) { this.mOnBindSuggestionCallback = callback; if (mSuggestionsAdapter != null) { mSuggestionsAdapter.setOnBindSuggestionCallback(mOnBindSuggestionCallback); } } /** * Collapses the suggestions list and * then clears its suggestion items. */ public void clearSuggestions() { swapSuggestions(new ArrayList<SearchSuggestion>()); } public void clearSearchFocus() { setSearchFocusedInternal(false); } public boolean isSearchBarFocused() { return mIsFocused; } private void setSearchFocusedInternal(final boolean focused) { this.mIsFocused = focused; if (focused) { mSearchInput.requestFocus(); moveSuggestListToInitialPos(); mSuggestionsSection.setVisibility(VISIBLE); if (mDimBackground) { fadeInBackground(); } mMenuView.hideIfRoomItems(true); transitionInLeftSection(true); Util.showSoftKeyboard(getContext(), mSearchInput); if (mMenuOpen) { closeMenu(false); } if (mIsTitleSet) { mSkipTextChangeEvent = true; mSearchInput.setText(""); } if (mFocusChangeListener != null) { mFocusChangeListener.onFocus(); } } else { mMainLayout.requestFocus(); clearSuggestions(); if (mDimBackground) { fadeOutBackground(); } mMenuView.showIfRoomItems(true); transitionOutLeftSection(true); mClearButton.setVisibility(View.GONE); if (mHostActivity != null) { Util.closeSoftKeyboard(mHostActivity); } if (mIsTitleSet) { mSkipTextChangeEvent = true; mSearchInput.setText(mTitleText); } if (mFocusChangeListener != null) { mFocusChangeListener.onFocusCleared(); } } //if we don't have focus, we want to allow the client's views below our invisible //screen-covering view to handle touches mSuggestionsSection.setEnabled(focused); } private void changeIcon(ImageView imageView, Drawable newIcon, boolean withAnim) { imageView.setImageDrawable(newIcon); if (withAnim) { ObjectAnimator fadeInVoiceInputOrClear = ObjectAnimator.ofFloat(imageView, "alpha", 0.0f, 1.0f); fadeInVoiceInputOrClear.start(); } else { imageView.setAlpha(1.0f); } } private void transitionInLeftSection(boolean withAnim) { mLeftAction.setVisibility(View.VISIBLE); switch (mLeftActionMode) { case LEFT_ACTION_MODE_SHOW_HAMBURGER: openMenuDrawable(mMenuBtnDrawable, withAnim); if (!mMenuOpen) { break; } break; case LEFT_ACTION_MODE_SHOW_SEARCH: mLeftAction.setImageDrawable(mIconBackArrow); if (withAnim) { mLeftAction.setRotation(45); mLeftAction.setAlpha(0.0f); ObjectAnimator rotateAnim = ViewPropertyObjectAnimator.animate(mLeftAction).rotation(0).get(); ObjectAnimator fadeAnim = ViewPropertyObjectAnimator.animate(mLeftAction).alpha(1.0f).get(); AnimatorSet animSet = new AnimatorSet(); animSet.setDuration(500); animSet.playTogether(rotateAnim, fadeAnim); animSet.start(); } break; case LEFT_ACTION_MODE_SHOW_HOME: //do nothing break; case LEFT_ACTION_MODE_NO_LEFT_ACTION: mLeftAction.setImageDrawable(mIconBackArrow); if (withAnim) { ObjectAnimator searchInputTransXAnim = ViewPropertyObjectAnimator .animate(mSearchInputParent).translationX(0).get(); mLeftAction.setScaleX(0.5f); mLeftAction.setScaleY(0.5f); mLeftAction.setAlpha(0.0f); mLeftAction.setTranslationX(Util.dpToPx(8)); ObjectAnimator transXArrowAnim = ViewPropertyObjectAnimator.animate(mLeftAction).translationX(1.0f).get(); ObjectAnimator scaleXArrowAnim = ViewPropertyObjectAnimator.animate(mLeftAction).scaleX(1.0f).get(); ObjectAnimator scaleYArrowAnim = ViewPropertyObjectAnimator.animate(mLeftAction).scaleY(1.0f).get(); ObjectAnimator fadeArrowAnim = ViewPropertyObjectAnimator.animate(mLeftAction).alpha(1.0f).get(); transXArrowAnim.setStartDelay(150); scaleXArrowAnim.setStartDelay(150); scaleYArrowAnim.setStartDelay(150); fadeArrowAnim.setStartDelay(150); AnimatorSet animSet = new AnimatorSet(); animSet.setDuration(500); animSet.playTogether(searchInputTransXAnim, transXArrowAnim, scaleXArrowAnim, scaleYArrowAnim, fadeArrowAnim); animSet.start(); } else { mSearchInputParent.setTranslationX(0); } break; } } private void transitionOutLeftSection(boolean withAnim) { switch (mLeftActionMode) { case LEFT_ACTION_MODE_SHOW_HAMBURGER: closeMenuDrawable(mMenuBtnDrawable, withAnim); break; case LEFT_ACTION_MODE_SHOW_SEARCH: changeIcon(mLeftAction, mIconSearch, withAnim); break; case LEFT_ACTION_MODE_SHOW_HOME: //do nothing break; case LEFT_ACTION_MODE_NO_LEFT_ACTION: mLeftAction.setImageDrawable(mIconBackArrow); if (withAnim) { ObjectAnimator searchInputTransXAnim = ViewPropertyObjectAnimator.animate(mSearchInputParent) .translationX(-Util.dpToPx(LEFT_MENU_WIDTH_AND_MARGIN_START)).get(); ObjectAnimator scaleXArrowAnim = ViewPropertyObjectAnimator.animate(mLeftAction).scaleX(0.5f).get(); ObjectAnimator scaleYArrowAnim = ViewPropertyObjectAnimator.animate(mLeftAction).scaleY(0.5f).get(); ObjectAnimator fadeArrowAnim = ViewPropertyObjectAnimator.animate(mLeftAction).alpha(0.5f).get(); scaleXArrowAnim.setDuration(300); scaleYArrowAnim.setDuration(300); fadeArrowAnim.setDuration(300); scaleXArrowAnim.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { //restore normal state mLeftAction.setScaleX(1.0f); mLeftAction.setScaleY(1.0f); mLeftAction.setAlpha(1.0f); mLeftAction.setVisibility(View.INVISIBLE); } }); AnimatorSet animSet = new AnimatorSet(); animSet.setDuration(350); animSet.playTogether(scaleXArrowAnim, scaleYArrowAnim, fadeArrowAnim, searchInputTransXAnim); animSet.start(); } else { mLeftAction.setVisibility(View.INVISIBLE); } break; } } /** * Sets the listener that will be notified when the suggestion list's height * changes. * * @param onSuggestionsListHeightChanged the new suggestions list's height */ public void setOnSuggestionsListHeightChanged(OnSuggestionsListHeightChanged onSuggestionsListHeightChanged) { this.mOnSuggestionsListHeightChanged = onSuggestionsListHeightChanged; } /** * Sets the listener that will listen for query * changes as they are being typed. * * @param listener listener for query changes */ public void setOnQueryChangeListener(OnQueryChangeListener listener) { this.mQueryListener = listener; } /** * Sets the listener that will be called when * an action that completes the current search * session has occurred and the search lost focus. * <p/> * <p>When called, a client would ideally grab the * search or suggestion query from the callback parameter or * from {@link #getQuery() getquery} and perform the necessary * query against its data source.</p> * * @param listener listener for query completion */ public void setOnSearchListener(OnSearchListener listener) { this.mSearchListener = listener; } /** * Sets the listener that will be called when the focus * of the search has changed. * * @param listener listener for search focus changes */ public void setOnFocusChangeListener(OnFocusChangeListener listener) { this.mFocusChangeListener = listener; } /** * Sets the listener that will be called when the * left/start menu (or navigation menu) is clicked. * <p/> * <p>Note that this is different from the overflow menu * that has a separate listener.</p> * * @param listener */ public void setOnLeftMenuClickListener(OnLeftMenuClickListener listener) { this.mOnMenuClickListener = listener; } /** * Sets the listener that will be called when the * left/start home action (back arrow) is clicked. * * @param listener */ public void setOnHomeActionClickListener(OnHomeActionClickListener listener) { this.mOnHomeActionClickListener = listener; } /** * Sets the listener that will be called when * an item in the overflow menu is clicked. * * @param listener listener to listen to menu item clicks */ public void setOnMenuItemClickListener(OnMenuItemClickListener listener) { this.mActionMenuItemListener = listener; //todo reset menu view listener } private void openMenuDrawable(final DrawerArrowDrawable drawerArrowDrawable, boolean withAnim) { if (withAnim) { ValueAnimator anim = ValueAnimator.ofFloat(0.0f, 1.0f); anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float value = (Float) animation.getAnimatedValue(); drawerArrowDrawable.setProgress(value); } }); anim.setDuration(MENU_ICON_ANIM_DURATION); anim.start(); } else { drawerArrowDrawable.setProgress(1.0f); } } private void closeMenuDrawable(final DrawerArrowDrawable drawerArrowDrawable, boolean withAnim) { if (withAnim) { ValueAnimator anim = ValueAnimator.ofFloat(1.0f, 0.0f); anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float value = (Float) animation.getAnimatedValue(); drawerArrowDrawable.setProgress(value); } }); anim.setDuration(MENU_ICON_ANIM_DURATION); anim.start(); } else { drawerArrowDrawable.setProgress(0.0f); } } private void fadeOutBackground() { ValueAnimator anim = ValueAnimator.ofInt(BACKGROUND_DRAWABLE_ALPHA_SEARCH_FOCUSED, BACKGROUND_DRAWABLE_ALPHA_SEARCH_NOT_FOCUSED); anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { int value = (Integer) animation.getAnimatedValue(); mBackgroundDrawable.setAlpha(value); } }); anim.setDuration(BACKGROUND_FADE_ANIM_DURATION); anim.start(); } private void fadeInBackground() { ValueAnimator anim = ValueAnimator.ofInt(BACKGROUND_DRAWABLE_ALPHA_SEARCH_NOT_FOCUSED, BACKGROUND_DRAWABLE_ALPHA_SEARCH_FOCUSED); anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { int value = (Integer) animation.getAnimatedValue(); mBackgroundDrawable.setAlpha(value); } }); anim.setDuration(BACKGROUND_FADE_ANIM_DURATION); anim.start(); } private boolean isRTL() { Configuration config = getResources().getConfiguration(); return ViewCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_RTL; } @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState savedState = new SavedState(superState); savedState.suggestions = this.mSuggestionsAdapter.getDataSet(); savedState.isFocused = this.mIsFocused; savedState.query = getQuery(); savedState.suggestionTextSize = this.mSuggestionsTextSizePx; savedState.searchHint = this.mSearchHint; savedState.dismissOnOutsideClick = this.mDismissOnOutsideTouch; savedState.showMoveSuggestionUpBtn = this.mShowMoveUpSuggestion; savedState.showSearchKey = this.mShowSearchKey; savedState.isTitleSet = this.mIsTitleSet; savedState.backgroundColor = this.mBackgroundColor; savedState.suggestionsTextColor = this.mSuggestionTextColor; savedState.queryTextColor = this.mSearchInputTextColor; savedState.searchHintTextColor = this.mSearchInputHintColor; savedState.actionOverflowMenueColor = this.mOverflowIconColor; savedState.menuItemIconColor = this.mActionMenuItemColor; savedState.leftIconColor = this.mLeftActionIconColor; savedState.clearBtnColor = this.mClearBtnColor; savedState.suggestionUpBtnColor = this.mSuggestionTextColor; savedState.dividerColor = this.mDividerColor; savedState.menuId = mMenuId; savedState.leftActionMode = mLeftActionMode; savedState.dimBackground = mDimBackground; return savedState; } @Override public void onRestoreInstanceState(Parcelable state) { final SavedState savedState = (SavedState) state; super.onRestoreInstanceState(savedState.getSuperState()); this.mIsFocused = savedState.isFocused; this.mIsTitleSet = savedState.isTitleSet; this.mMenuId = savedState.menuId; this.mSuggestionSectionAnimDuration = savedState.suggestionsSectionAnimSuration; setSuggestionItemTextSize(savedState.suggestionTextSize); setDismissOnOutsideClick(savedState.dismissOnOutsideClick); setShowMoveUpSuggestion(savedState.showMoveSuggestionUpBtn); setShowSearchKey(savedState.showSearchKey); setSearchHint(savedState.searchHint); setBackgroundColor(savedState.backgroundColor); setSuggestionsTextColor(savedState.suggestionsTextColor); setQueryTextColor(savedState.queryTextColor); setHintTextColor(savedState.searchHintTextColor); setActionMenuOverflowColor(savedState.actionOverflowMenueColor); setMenuItemIconColor(savedState.menuItemIconColor); setLeftActionIconColor(savedState.leftIconColor); setClearBtnColor(savedState.clearBtnColor); setSuggestionRightIconColor(savedState.suggestionUpBtnColor); setDividerColor(savedState.dividerColor); setLeftActionMode(savedState.leftActionMode); setDimBackground(savedState.dimBackground); mSuggestionsSection.setEnabled(this.mIsFocused); if (this.mIsFocused) { mBackgroundDrawable.setAlpha(BACKGROUND_DRAWABLE_ALPHA_SEARCH_FOCUSED); mSkipTextChangeEvent = true; mSkipQueryFocusChangeEvent = true; mSuggestionsSection.setVisibility(VISIBLE); //restore suggestions list when suggestion section's height is fully set mSuggestionSecHeightListener = new OnSuggestionSecHeightSetListener() { @Override public void onSuggestionSecHeightSet() { swapSuggestions(savedState.suggestions, false); mSuggestionSecHeightListener = null; //todo refactor move to a better location transitionInLeftSection(false); } }; mClearButton.setVisibility((savedState.query.length() == 0) ? View.INVISIBLE : View.VISIBLE); mLeftAction.setVisibility(View.VISIBLE); Util.showSoftKeyboard(getContext(), mSearchInput); } } static class SavedState extends BaseSavedState { private List<? extends SearchSuggestion> suggestions = new ArrayList<>(); private boolean isFocused; private String query; private int suggestionTextSize; private String searchHint; private boolean dismissOnOutsideClick; private boolean showMoveSuggestionUpBtn; private boolean showSearchKey; private boolean isTitleSet; private int backgroundColor; private int suggestionsTextColor; private int queryTextColor; private int searchHintTextColor; private int actionOverflowMenueColor; private int menuItemIconColor; private int leftIconColor; private int clearBtnColor; private int suggestionUpBtnColor; private int dividerColor; private int menuId; private int leftActionMode; private boolean dimBackground; private long suggestionsSectionAnimSuration; SavedState(Parcelable superState) { super(superState); } private SavedState(Parcel in) { super(in); in.readList(suggestions, getClass().getClassLoader()); isFocused = (in.readInt() != 0); query = in.readString(); suggestionTextSize = in.readInt(); searchHint = in.readString(); dismissOnOutsideClick = (in.readInt() != 0); showMoveSuggestionUpBtn = (in.readInt() != 0); showSearchKey = (in.readInt() != 0); isTitleSet = (in.readInt() != 0); backgroundColor = in.readInt(); suggestionsTextColor = in.readInt(); queryTextColor = in.readInt(); searchHintTextColor = in.readInt(); actionOverflowMenueColor = in.readInt(); menuItemIconColor = in.readInt(); leftIconColor = in.readInt(); clearBtnColor = in.readInt(); suggestionUpBtnColor = in.readInt(); dividerColor = in.readInt(); menuId = in.readInt(); leftActionMode = in.readInt(); dimBackground = (in.readInt() != 0); suggestionsSectionAnimSuration = in.readLong(); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeList(suggestions); out.writeInt(isFocused ? 1 : 0); out.writeString(query); out.writeInt(suggestionTextSize); out.writeString(searchHint); out.writeInt(dismissOnOutsideClick ? 1 : 0); out.writeInt(showMoveSuggestionUpBtn ? 1 : 0); out.writeInt(showSearchKey ? 1 : 0); out.writeInt(isTitleSet ? 1 : 0); out.writeInt(backgroundColor); out.writeInt(suggestionsTextColor); out.writeInt(queryTextColor); out.writeInt(searchHintTextColor); out.writeInt(actionOverflowMenueColor); out.writeInt(menuItemIconColor); out.writeInt(leftIconColor); out.writeInt(clearBtnColor); out.writeInt(suggestionUpBtnColor); out.writeInt(dividerColor); out.writeInt(menuId); out.writeInt(leftActionMode); out.writeInt(dimBackground ? 1 : 0); out.writeLong(suggestionsSectionAnimSuration); } public static final Creator<SavedState> CREATOR = new Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); //remove any ongoing animations to prevent leaks //todo investigate if correct ViewCompat.animate(mSuggestionListContainer).cancel(); } }
fix issue #69 progress bar showing with left icon
library/src/main/java/com/arlib/floatingsearchview/FloatingSearchView.java
fix issue #69 progress bar showing with left icon
Java
apache-2.0
7ad2b83510b031c777e8a84324c3446bcae696b0
0
reportportal/commons-model
/* * Copyright 2018 EPAM Systems * * 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.epam.ta.reportportal.ws.model; import com.epam.ta.reportportal.ws.annotations.NotEmpty; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.io.Serializable; import static com.epam.ta.reportportal.ws.model.ValidationConstraints.MAX_ATTRIBUTE_LENGTH; import static com.epam.ta.reportportal.ws.model.ValidationConstraints.MIN_ITEM_ATTRIBUTE_VALUE_LENGTH; /** * @author <a href="mailto:[email protected]">Ihar Kahadouski</a> */ public class ItemAttributeResource implements Serializable { @Size(max = MAX_ATTRIBUTE_LENGTH) private String key; @NotNull @NotEmpty @Size(min = MIN_ITEM_ATTRIBUTE_VALUE_LENGTH, max = MAX_ATTRIBUTE_LENGTH) private String value; public ItemAttributeResource() { } public ItemAttributeResource(String key, String value) { this.key = key; this.value = value; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } @Override public String toString() { final StringBuilder sb = new StringBuilder("ItemAttributeResource{"); sb.append("key='").append(key).append('\''); sb.append(", value='").append(value).append('\''); sb.append('}'); return sb.toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ItemAttributeResource that = (ItemAttributeResource) o; if (key != null ? !key.equals(that.key) : that.key != null) { return false; } return value != null ? value.equals(that.value) : that.value == null; } @Override public int hashCode() { int result = key != null ? key.hashCode() : 0; result = 31 * result + (value != null ? value.hashCode() : 0); return result; } }
src/main/java/com/epam/ta/reportportal/ws/model/ItemAttributeResource.java
/* * Copyright 2018 EPAM Systems * * 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.epam.ta.reportportal.ws.model; import com.epam.ta.reportportal.ws.annotations.NotEmpty; import com.fasterxml.jackson.annotation.JsonProperty; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.io.Serializable; import static com.epam.ta.reportportal.ws.model.ValidationConstraints.MAX_ATTRIBUTE_LENGTH; import static com.epam.ta.reportportal.ws.model.ValidationConstraints.MIN_ITEM_ATTRIBUTE_VALUE_LENGTH; /** * @author <a href="mailto:[email protected]">Ihar Kahadouski</a> */ public class ItemAttributeResource implements Serializable { @Size(max = MAX_ATTRIBUTE_LENGTH) private String key; @NotNull @NotEmpty @Size(min = MIN_ITEM_ATTRIBUTE_VALUE_LENGTH, max = MAX_ATTRIBUTE_LENGTH) private String value; @JsonProperty(defaultValue = "false") private boolean system = false; public ItemAttributeResource() { } public ItemAttributeResource(String key, String value) { this.key = key; this.value = value; } public ItemAttributeResource(String key, String value, boolean system) { this.key = key; this.value = value; this.system = system; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public boolean isSystem() { return system; } public void setSystem(boolean system) { this.system = system; } @Override public String toString() { final StringBuilder sb = new StringBuilder("ItemAttributeResource{"); sb.append("key='").append(key).append('\''); sb.append(", value='").append(value).append('\''); sb.append(", system=").append(system); sb.append('}'); return sb.toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ItemAttributeResource that = (ItemAttributeResource) o; if (system != that.system) { return false; } if (key != null ? !key.equals(that.key) : that.key != null) { return false; } return value != null ? value.equals(that.value) : that.value == null; } @Override public int hashCode() { int result = key != null ? key.hashCode() : 0; result = 31 * result + (value != null ? value.hashCode() : 0); result = 31 * result + (system ? 1 : 0); return result; } }
remove system field from item attributes
src/main/java/com/epam/ta/reportportal/ws/model/ItemAttributeResource.java
remove system field from item attributes
Java
apache-2.0
0755eb6b3fdfd81499a64e049189ef73e0940974
0
ksokol/carldav
/* * Copyright 2006-2007 Open Source Applications Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.unitedinternet.cosmo.dav.impl; import net.fortuna.ical4j.model.Calendar; import net.fortuna.ical4j.model.Component; import net.fortuna.ical4j.model.Period; import net.fortuna.ical4j.model.component.VFreeBusy; import net.fortuna.ical4j.model.component.VTimeZone; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.jackrabbit.webdav.io.InputContext; import org.apache.jackrabbit.webdav.property.DavPropertyName; import org.apache.jackrabbit.webdav.property.DavPropertySet; import org.unitedinternet.cosmo.calendar.query.CalendarFilter; import org.unitedinternet.cosmo.dao.ModelValidationException; import org.unitedinternet.cosmo.dav.CosmoDavException; import org.unitedinternet.cosmo.dav.DavCollection; import org.unitedinternet.cosmo.dav.DavResourceFactory; import org.unitedinternet.cosmo.dav.DavResourceLocator; import org.unitedinternet.cosmo.dav.LockedException; import org.unitedinternet.cosmo.dav.ProtectedPropertyModificationException; import org.unitedinternet.cosmo.dav.UnprocessableEntityException; import org.unitedinternet.cosmo.dav.WebDavResource; import org.unitedinternet.cosmo.dav.caldav.CaldavConstants; import org.unitedinternet.cosmo.dav.caldav.InvalidCalendarLocationException; import org.unitedinternet.cosmo.dav.caldav.InvalidCalendarResourceException; import org.unitedinternet.cosmo.dav.caldav.MaxResourceSizeException; import org.unitedinternet.cosmo.dav.caldav.TimeZoneExtractor; import org.unitedinternet.cosmo.dav.caldav.UidConflictException; import org.unitedinternet.cosmo.dav.caldav.XCaldavConstants; import org.unitedinternet.cosmo.dav.caldav.property.CalendarColor; import org.unitedinternet.cosmo.dav.caldav.property.CalendarDescription; import org.unitedinternet.cosmo.dav.caldav.property.CalendarTimezone; import org.unitedinternet.cosmo.dav.caldav.property.CalendarVisibility; import org.unitedinternet.cosmo.dav.caldav.property.GetCTag; import org.unitedinternet.cosmo.dav.caldav.property.MaxResourceSize; import org.unitedinternet.cosmo.dav.caldav.property.SupportedCalendarComponentSet; import org.unitedinternet.cosmo.dav.caldav.property.SupportedCalendarData; import org.unitedinternet.cosmo.dav.caldav.property.SupportedCollationSet; import org.unitedinternet.cosmo.dav.property.DisplayName; import org.unitedinternet.cosmo.dav.property.WebDavProperty; import org.unitedinternet.cosmo.icalendar.ICalendarConstants; import org.unitedinternet.cosmo.model.CalendarCollectionStamp; import org.unitedinternet.cosmo.model.CollectionItem; import org.unitedinternet.cosmo.model.CollectionLockedException; import org.unitedinternet.cosmo.model.ContentItem; import org.unitedinternet.cosmo.model.DataSizeException; import org.unitedinternet.cosmo.model.EntityFactory; import org.unitedinternet.cosmo.model.EventStamp; import org.unitedinternet.cosmo.model.IcalUidInUseException; import org.unitedinternet.cosmo.model.Item; import org.unitedinternet.cosmo.model.NoteItem; import org.unitedinternet.cosmo.model.StampUtils; import org.unitedinternet.cosmo.model.hibernate.EntityConverter; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; import javax.xml.namespace.QName; /** * Extends <code>DavCollection</code> to adapt the Cosmo * <code>CalendarCollectionItem</code> to the DAV resource model. * * This class defines the following live properties: * * <ul> * <li><code>CALDAV:calendar-description</code></li> * <li><code>CALDAV:calendar-timezone</code></li> * <li><code>CALDAV:calendar-supported-calendar-component-set</code> * (protected)</li> * <li><code>CALDAV:supported-calendar-data</code> (protected)</li> * <li><code>CALDAV:max-resource-size</code> (protected)</li> * <li><code>CS:getctag</code> (protected)</li> * <li><code>XC:calendar-color</code></li> * <li><code>XC:calendar-visible</code></li> * </ul> * * @see DavCollection * @see CalendarCollectionItem */ public class DavCalendarCollection extends DavCollectionBase implements CaldavConstants, ICalendarConstants { private static final Log LOG = LogFactory.getLog(DavCalendarCollection.class); private static final Set<String> DEAD_PROPERTY_FILTER = new HashSet<String>(); static { registerLiveProperty(CALENDARDESCRIPTION); registerLiveProperty(CALENDARTIMEZONE); registerLiveProperty(SUPPORTEDCALENDARCOMPONENTSET); registerLiveProperty(SUPPORTEDCALENDARDATA); registerLiveProperty(MAXRESOURCESIZE); registerLiveProperty(GET_CTAG); registerLiveProperty(XCaldavConstants.CALENDAR_COLOR); registerLiveProperty(XCaldavConstants.CALENDAR_VISIBLE); DEAD_PROPERTY_FILTER.add(CalendarCollectionStamp.class.getName()); } /** */ public DavCalendarCollection(CollectionItem collection, DavResourceLocator locator, DavResourceFactory factory, EntityFactory entityFactory) throws CosmoDavException { super(collection, locator, factory, entityFactory); } /** */ public DavCalendarCollection(DavResourceLocator locator, DavResourceFactory factory, EntityFactory entityFactory) throws CosmoDavException { this(entityFactory.createCollection(), locator, factory, entityFactory); getItem().addStamp(entityFactory.createCalendarCollectionStamp((CollectionItem) getItem())); } // Jackrabbit WebDavResource /** */ public String getSupportedMethods() { // calendar collections not allowed inside calendar collections return "OPTIONS, GET, HEAD, TRACE, PROPFIND, PROPPATCH, PUT, COPY, DELETE, MOVE, MKTICKET, DELTICKET, REPORT"; } /** */ public void move(org.apache.jackrabbit.webdav.DavResource destination) throws org.apache.jackrabbit.webdav.DavException { validateDestination(destination); super.move(destination); } /** */ public void copy(org.apache.jackrabbit.webdav.DavResource destination, boolean shallow) throws org.apache.jackrabbit.webdav.DavException { validateDestination(destination); super.copy(destination, shallow); } // DavCollection public boolean isCalendarCollection() { return true; } // our methods /** * Returns the member resources in this calendar collection matching * the given filter. */ public Set<DavCalendarResource> findMembers(CalendarFilter filter) throws CosmoDavException { Set<DavCalendarResource> members = new HashSet<DavCalendarResource>(); CollectionItem collection = (CollectionItem) getItem(); for (ContentItem memberItem : getCalendarQueryProcesor().filterQuery(collection, filter)) { WebDavResource resource = memberToResource(memberItem); if(resource!=null) { members.add((DavCalendarResource) resource); } } return members; } /** * Returns a VFREEBUSY component containing * the freebusy periods for the calendar collection for the * specified time range. * @param period time range for freebusy information * @return VFREEBUSY component containing FREEBUSY periods for * specified timerange */ public VFreeBusy generateFreeBusy(Period period) { VFreeBusy vfb = this.getCalendarQueryProcesor().freeBusyQuery( (CollectionItem) getItem(), period); return vfb; } /** * @return The default timezone for this calendar collection, if * one has been set. */ public VTimeZone getTimeZone() { Calendar obj = getCalendarCollectionStamp().getTimezoneCalendar(); if (obj == null) { return null; } return (VTimeZone) obj.getComponents().getComponent(Component.VTIMEZONE); } protected Set<QName> getResourceTypes() { Set<QName> rt = super.getResourceTypes(); rt.add(RESOURCE_TYPE_CALENDAR); return rt; } public CalendarCollectionStamp getCalendarCollectionStamp() { return StampUtils.getCalendarCollectionStamp(getItem()); } /** */ protected void populateItem(InputContext inputContext) throws CosmoDavException { super.populateItem(inputContext); CalendarCollectionStamp cc = getCalendarCollectionStamp(); try { cc.setDescription(getItem().getName()); // XXX: language should come from the input context } catch (DataSizeException e) { throw new MaxResourceSizeException(e.getMessage()); } } /** */ protected void loadLiveProperties(DavPropertySet properties) { super.loadLiveProperties(properties); CalendarCollectionStamp cc = getCalendarCollectionStamp(); if (cc == null) { return; } if (cc.getDescription() != null) { properties.add(new CalendarDescription(cc.getDescription(), cc.getLanguage())); } if (cc.getTimezoneCalendar() != null) { properties.add(new CalendarTimezone(cc.getTimezoneCalendar().toString())); } // add CS:getctag property, which is the collection's entitytag // if it exists Item item = getItem(); if(item!=null && item.getEntityTag()!=null) { properties.add(new GetCTag(item.getEntityTag())); } properties.add(new SupportedCalendarComponentSet()); properties.add(new SupportedCollationSet()); properties.add(new SupportedCalendarData()); properties.add(new MaxResourceSize()); if(cc.getVisibility() != null){ properties.add(new CalendarVisibility(cc.getVisibility())); } if(cc.getColor() != null){ properties.add(new CalendarColor(cc.getColor())); } if(cc.getDisplayName() != null){ properties.add(new DisplayName(cc.getDisplayName())); } } /** * The CALDAV:supported-calendar-component-set property is used to specify restrictions on the calendar component types that calendar object resources may contain in a calendar collection. Any attempt by the client to store calendar object resources with component types not listed in this property, if it exists, MUST result in an error, with the CALDAV:supported-calendar-component precondition (Section 5.3.2.1) being violated. Since this property is protected, it cannot be changed by clients using a PROPPATCH request. * */ protected void setLiveProperty(WebDavProperty property, boolean create) throws CosmoDavException { super.setLiveProperty(property, create); CalendarCollectionStamp cc = getCalendarCollectionStamp(); if (cc == null) { return; } DavPropertyName name = property.getName(); if (property.getValue() == null) { throw new UnprocessableEntityException("Property " + name + " requires a value"); } if(!(create && name.equals(SUPPORTEDCALENDARCOMPONENTSET)) && (name.equals(SUPPORTEDCALENDARCOMPONENTSET) || name.equals(SUPPORTEDCALENDARDATA) || name.equals(MAXRESOURCESIZE) || name.equals(GET_CTAG))) { throw new ProtectedPropertyModificationException(name); } if (name.equals(CALENDARDESCRIPTION)) { cc.setDescription(property.getValueText()); cc.setLanguage(property.getLanguage()); return; } if (name.equals(CALENDARTIMEZONE)) { cc.setTimezoneCalendar(TimeZoneExtractor.extract(property)); } if(name.equals(XCaldavConstants.CALENDAR_COLOR)){ cc.setColor(property.getValueText()); } if(name.equals(XCaldavConstants.CALENDAR_VISIBLE)){ cc.setVisibility(Boolean.parseBoolean(property.getValueText())); } } /** */ protected void removeLiveProperty(DavPropertyName name) throws CosmoDavException { super.removeLiveProperty(name); CalendarCollectionStamp cc = getCalendarCollectionStamp(); if (cc == null) { return; } if (name.equals(SUPPORTEDCALENDARCOMPONENTSET) || name.equals(SUPPORTEDCALENDARDATA) || name.equals(MAXRESOURCESIZE) || name.equals(GET_CTAG)) { throw new ProtectedPropertyModificationException(name); } if (name.equals(CALENDARDESCRIPTION)) { cc.setDescription(null); cc.setLanguage(null); return; } if (name.equals(CALENDARTIMEZONE)) { cc.setTimezoneCalendar(null); return; } if(name.equals(XCaldavConstants.CALENDAR_COLOR)){ cc.setColor(null); } if(name.equals(XCaldavConstants.CALENDAR_VISIBLE)){ cc.setVisibility(null); } } /** */ protected Set<String> getDeadPropertyFilter() { Set<String> copy = new HashSet<String>(); copy.addAll(super.getDeadPropertyFilter()); copy.addAll(DEAD_PROPERTY_FILTER); return copy; } /** */ protected void saveContent(DavItemContent member) throws CosmoDavException { if (! (member instanceof DavCalendarResource)) { throw new IllegalArgumentException("member not DavCalendarResource"); } if (member instanceof DavEvent) { saveEvent(member); } else { try { super.saveContent(member); } catch (IcalUidInUseException e) { throw new UidConflictException(e); } } } private void saveEvent(DavItemContent member) throws CosmoDavException { ContentItem content = (ContentItem) member.getItem(); EventStamp event = StampUtils.getEventStamp(content); EntityConverter converter = new EntityConverter(getEntityFactory()); Set<ContentItem> toUpdate = new LinkedHashSet<ContentItem>(); try { // convert icalendar representation to cosmo data model toUpdate.addAll(converter.convertEventCalendar( (NoteItem) content, event.getEventCalendar())); } catch (ModelValidationException e) { throw new InvalidCalendarResourceException(e.getMessage()); } if (event.getCreationDate()!=null) { if (LOG.isDebugEnabled()) { LOG.debug("updating event " + member.getResourcePath()); } try { getContentService().updateContentItems(content.getParents(), toUpdate); } catch (IcalUidInUseException e) { throw new UidConflictException(e); } catch (CollectionLockedException e) { throw new LockedException(); } } else { if (LOG.isDebugEnabled()) { LOG.debug("creating event " + member.getResourcePath()); } try { getContentService().createContentItems( (CollectionItem) getItem(), toUpdate); } catch (IcalUidInUseException e) { throw new UidConflictException(e); } catch (CollectionLockedException e) { throw new LockedException(); } } member.setItem(content); } /** */ protected void removeContent(DavItemContent member) throws CosmoDavException { if (! (member instanceof DavCalendarResource)) { throw new IllegalArgumentException("member not DavCalendarResource"); } ContentItem content = (ContentItem) member.getItem(); CollectionItem parent = (CollectionItem) getItem(); // XXX: what exceptions need to be caught? if (LOG.isDebugEnabled()) { LOG.debug("removing event " + member.getResourcePath()); } try { if(content instanceof NoteItem) { getContentService().removeItemFromCollection(content, parent); } else { getContentService().removeContent(content); } } catch (CollectionLockedException e) { throw new LockedException(); } } private void validateDestination(org.apache.jackrabbit.webdav.DavResource destination) throws CosmoDavException { if (destination instanceof WebDavResource && ((WebDavResource)destination).getParent() instanceof DavCalendarCollection) { throw new InvalidCalendarLocationException("Parent collection of destination must not be a calendar collection"); } } }
src/main/java/org/unitedinternet/cosmo/dav/impl/DavCalendarCollection.java
/* * Copyright 2006-2007 Open Source Applications Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.unitedinternet.cosmo.dav.impl; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; import javax.xml.namespace.QName; import net.fortuna.ical4j.model.Calendar; import net.fortuna.ical4j.model.Component; import net.fortuna.ical4j.model.Period; import net.fortuna.ical4j.model.component.VFreeBusy; import net.fortuna.ical4j.model.component.VTimeZone; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.jackrabbit.webdav.io.InputContext; import org.apache.jackrabbit.webdav.property.DavPropertyName; import org.apache.jackrabbit.webdav.property.DavPropertySet; import org.unitedinternet.cosmo.calendar.query.CalendarFilter; import org.unitedinternet.cosmo.dao.ModelValidationException; import org.unitedinternet.cosmo.dav.DavCollection; import org.unitedinternet.cosmo.dav.CosmoDavException; import org.unitedinternet.cosmo.dav.WebDavResource; import org.unitedinternet.cosmo.dav.DavResourceFactory; import org.unitedinternet.cosmo.dav.DavResourceLocator; import org.unitedinternet.cosmo.dav.LockedException; import org.unitedinternet.cosmo.dav.ProtectedPropertyModificationException; import org.unitedinternet.cosmo.dav.UnprocessableEntityException; import org.unitedinternet.cosmo.dav.caldav.CaldavConstants; import org.unitedinternet.cosmo.dav.caldav.InvalidCalendarLocationException; import org.unitedinternet.cosmo.dav.caldav.InvalidCalendarResourceException; import org.unitedinternet.cosmo.dav.caldav.MaxResourceSizeException; import org.unitedinternet.cosmo.dav.caldav.TimeZoneExtractor; import org.unitedinternet.cosmo.dav.caldav.UidConflictException; import org.unitedinternet.cosmo.dav.caldav.XCaldavConstants; import org.unitedinternet.cosmo.dav.caldav.property.CalendarColor; import org.unitedinternet.cosmo.dav.caldav.property.CalendarDescription; import org.unitedinternet.cosmo.dav.caldav.property.CalendarTimezone; import org.unitedinternet.cosmo.dav.caldav.property.CalendarVisibility; import org.unitedinternet.cosmo.dav.caldav.property.GetCTag; import org.unitedinternet.cosmo.dav.caldav.property.MaxResourceSize; import org.unitedinternet.cosmo.dav.caldav.property.SupportedCalendarComponentSet; import org.unitedinternet.cosmo.dav.caldav.property.SupportedCalendarData; import org.unitedinternet.cosmo.dav.caldav.property.SupportedCollationSet; import org.unitedinternet.cosmo.dav.property.DisplayName; import org.unitedinternet.cosmo.dav.property.WebDavProperty; import org.unitedinternet.cosmo.icalendar.ICalendarConstants; import org.unitedinternet.cosmo.model.CalendarCollectionStamp; import org.unitedinternet.cosmo.model.CollectionItem; import org.unitedinternet.cosmo.model.CollectionLockedException; import org.unitedinternet.cosmo.model.ContentItem; import org.unitedinternet.cosmo.model.DataSizeException; import org.unitedinternet.cosmo.model.EntityFactory; import org.unitedinternet.cosmo.model.EventStamp; import org.unitedinternet.cosmo.model.IcalUidInUseException; import org.unitedinternet.cosmo.model.Item; import org.unitedinternet.cosmo.model.NoteItem; import org.unitedinternet.cosmo.model.StampUtils; import org.unitedinternet.cosmo.model.hibernate.EntityConverter; /** * Extends <code>DavCollection</code> to adapt the Cosmo * <code>CalendarCollectionItem</code> to the DAV resource model. * * This class defines the following live properties: * * <ul> * <li><code>CALDAV:calendar-description</code></li> * <li><code>CALDAV:calendar-timezone</code></li> * <li><code>CALDAV:calendar-supported-calendar-component-set</code> * (protected)</li> * <li><code>CALDAV:supported-calendar-data</code> (protected)</li> * <li><code>CALDAV:max-resource-size</code> (protected)</li> * <li><code>CS:getctag</code> (protected)</li> * <li><code>XC:calendar-color</code></li> * <li><code>XC:calendar-visible</code></li> * </ul> * * @see DavCollection * @see CalendarCollectionItem */ public class DavCalendarCollection extends DavCollectionBase implements CaldavConstants, ICalendarConstants { private static final Log LOG = LogFactory.getLog(DavCalendarCollection.class); private static final Set<String> DEAD_PROPERTY_FILTER = new HashSet<String>(); static { registerLiveProperty(CALENDARDESCRIPTION); registerLiveProperty(CALENDARTIMEZONE); registerLiveProperty(SUPPORTEDCALENDARCOMPONENTSET); registerLiveProperty(SUPPORTEDCALENDARDATA); registerLiveProperty(MAXRESOURCESIZE); registerLiveProperty(GET_CTAG); registerLiveProperty(XCaldavConstants.CALENDAR_COLOR); registerLiveProperty(XCaldavConstants.CALENDAR_VISIBLE); DEAD_PROPERTY_FILTER.add(CalendarCollectionStamp.class.getName()); } /** */ public DavCalendarCollection(CollectionItem collection, DavResourceLocator locator, DavResourceFactory factory, EntityFactory entityFactory) throws CosmoDavException { super(collection, locator, factory, entityFactory); } /** */ public DavCalendarCollection(DavResourceLocator locator, DavResourceFactory factory, EntityFactory entityFactory) throws CosmoDavException { this(entityFactory.createCollection(), locator, factory, entityFactory); getItem().addStamp(entityFactory.createCalendarCollectionStamp((CollectionItem) getItem())); } // Jackrabbit WebDavResource /** */ public String getSupportedMethods() { // calendar collections not allowed inside calendar collections return "OPTIONS, GET, HEAD, TRACE, PROPFIND, PROPPATCH, PUT, COPY, DELETE, MOVE, MKTICKET, DELTICKET, REPORT"; } /** */ public void move(org.apache.jackrabbit.webdav.DavResource destination) throws org.apache.jackrabbit.webdav.DavException { validateDestination(destination); super.move(destination); } /** */ public void copy(org.apache.jackrabbit.webdav.DavResource destination, boolean shallow) throws org.apache.jackrabbit.webdav.DavException { validateDestination(destination); super.copy(destination, shallow); } // DavCollection public boolean isCalendarCollection() { return true; } // our methods /** * Returns the member resources in this calendar collection matching * the given filter. */ public Set<DavCalendarResource> findMembers(CalendarFilter filter) throws CosmoDavException { Set<DavCalendarResource> members = new HashSet<DavCalendarResource>(); CollectionItem collection = (CollectionItem) getItem(); for (ContentItem memberItem : getCalendarQueryProcesor().filterQuery(collection, filter)) { WebDavResource resource = memberToResource(memberItem); if(resource!=null) { members.add((DavCalendarResource) resource); } } return members; } /** * Returns the member collection resources in this calendar collection. * */ public Set<CollectionItem> findCollectionMembers(DavCollectionBase collectionBase) throws CosmoDavException { CollectionItem collection = (CollectionItem) collectionBase.getItem(); return getContentService().findCollectionItems(collection); } /** * Returns a VFREEBUSY component containing * the freebusy periods for the calendar collection for the * specified time range. * @param period time range for freebusy information * @return VFREEBUSY component containing FREEBUSY periods for * specified timerange */ public VFreeBusy generateFreeBusy(Period period) { VFreeBusy vfb = this.getCalendarQueryProcesor().freeBusyQuery( (CollectionItem) getItem(), period); return vfb; } /** * @return The default timezone for this calendar collection, if * one has been set. */ public VTimeZone getTimeZone() { Calendar obj = getCalendarCollectionStamp().getTimezoneCalendar(); if (obj == null) { return null; } return (VTimeZone) obj.getComponents().getComponent(Component.VTIMEZONE); } protected Set<QName> getResourceTypes() { Set<QName> rt = super.getResourceTypes(); rt.add(RESOURCE_TYPE_CALENDAR); return rt; } public CalendarCollectionStamp getCalendarCollectionStamp() { return StampUtils.getCalendarCollectionStamp(getItem()); } /** */ protected void populateItem(InputContext inputContext) throws CosmoDavException { super.populateItem(inputContext); CalendarCollectionStamp cc = getCalendarCollectionStamp(); try { cc.setDescription(getItem().getName()); // XXX: language should come from the input context } catch (DataSizeException e) { throw new MaxResourceSizeException(e.getMessage()); } } /** */ protected void loadLiveProperties(DavPropertySet properties) { super.loadLiveProperties(properties); CalendarCollectionStamp cc = getCalendarCollectionStamp(); if (cc == null) { return; } if (cc.getDescription() != null) { properties.add(new CalendarDescription(cc.getDescription(), cc.getLanguage())); } if (cc.getTimezoneCalendar() != null) { properties.add(new CalendarTimezone(cc.getTimezoneCalendar().toString())); } // add CS:getctag property, which is the collection's entitytag // if it exists Item item = getItem(); if(item!=null && item.getEntityTag()!=null) { properties.add(new GetCTag(item.getEntityTag())); } properties.add(new SupportedCalendarComponentSet()); properties.add(new SupportedCollationSet()); properties.add(new SupportedCalendarData()); properties.add(new MaxResourceSize()); if(cc.getVisibility() != null){ properties.add(new CalendarVisibility(cc.getVisibility())); } if(cc.getColor() != null){ properties.add(new CalendarColor(cc.getColor())); } if(cc.getDisplayName() != null){ properties.add(new DisplayName(cc.getDisplayName())); } } /** * The CALDAV:supported-calendar-component-set property is used to specify restrictions on the calendar component types that calendar object resources may contain in a calendar collection. Any attempt by the client to store calendar object resources with component types not listed in this property, if it exists, MUST result in an error, with the CALDAV:supported-calendar-component precondition (Section 5.3.2.1) being violated. Since this property is protected, it cannot be changed by clients using a PROPPATCH request. * */ protected void setLiveProperty(WebDavProperty property, boolean create) throws CosmoDavException { super.setLiveProperty(property, create); CalendarCollectionStamp cc = getCalendarCollectionStamp(); if (cc == null) { return; } DavPropertyName name = property.getName(); if (property.getValue() == null) { throw new UnprocessableEntityException("Property " + name + " requires a value"); } if(!(create && name.equals(SUPPORTEDCALENDARCOMPONENTSET)) && (name.equals(SUPPORTEDCALENDARCOMPONENTSET) || name.equals(SUPPORTEDCALENDARDATA) || name.equals(MAXRESOURCESIZE) || name.equals(GET_CTAG))) { throw new ProtectedPropertyModificationException(name); } if (name.equals(CALENDARDESCRIPTION)) { cc.setDescription(property.getValueText()); cc.setLanguage(property.getLanguage()); return; } if (name.equals(CALENDARTIMEZONE)) { cc.setTimezoneCalendar(TimeZoneExtractor.extract(property)); } if(name.equals(XCaldavConstants.CALENDAR_COLOR)){ cc.setColor(property.getValueText()); } if(name.equals(XCaldavConstants.CALENDAR_VISIBLE)){ cc.setVisibility(Boolean.parseBoolean(property.getValueText())); } } /** */ protected void removeLiveProperty(DavPropertyName name) throws CosmoDavException { super.removeLiveProperty(name); CalendarCollectionStamp cc = getCalendarCollectionStamp(); if (cc == null) { return; } if (name.equals(SUPPORTEDCALENDARCOMPONENTSET) || name.equals(SUPPORTEDCALENDARDATA) || name.equals(MAXRESOURCESIZE) || name.equals(GET_CTAG)) { throw new ProtectedPropertyModificationException(name); } if (name.equals(CALENDARDESCRIPTION)) { cc.setDescription(null); cc.setLanguage(null); return; } if (name.equals(CALENDARTIMEZONE)) { cc.setTimezoneCalendar(null); return; } if(name.equals(XCaldavConstants.CALENDAR_COLOR)){ cc.setColor(null); } if(name.equals(XCaldavConstants.CALENDAR_VISIBLE)){ cc.setVisibility(null); } } /** */ protected Set<String> getDeadPropertyFilter() { Set<String> copy = new HashSet<String>(); copy.addAll(super.getDeadPropertyFilter()); copy.addAll(DEAD_PROPERTY_FILTER); return copy; } /** */ protected void saveContent(DavItemContent member) throws CosmoDavException { if (! (member instanceof DavCalendarResource)) { throw new IllegalArgumentException("member not DavCalendarResource"); } if (member instanceof DavEvent) { saveEvent(member); } else { try { super.saveContent(member); } catch (IcalUidInUseException e) { throw new UidConflictException(e); } } } private void saveEvent(DavItemContent member) throws CosmoDavException { ContentItem content = (ContentItem) member.getItem(); EventStamp event = StampUtils.getEventStamp(content); EntityConverter converter = new EntityConverter(getEntityFactory()); Set<ContentItem> toUpdate = new LinkedHashSet<ContentItem>(); try { // convert icalendar representation to cosmo data model toUpdate.addAll(converter.convertEventCalendar( (NoteItem) content, event.getEventCalendar())); } catch (ModelValidationException e) { throw new InvalidCalendarResourceException(e.getMessage()); } if (event.getCreationDate()!=null) { if (LOG.isDebugEnabled()) { LOG.debug("updating event " + member.getResourcePath()); } try { getContentService().updateContentItems(content.getParents(), toUpdate); } catch (IcalUidInUseException e) { throw new UidConflictException(e); } catch (CollectionLockedException e) { throw new LockedException(); } } else { if (LOG.isDebugEnabled()) { LOG.debug("creating event " + member.getResourcePath()); } try { getContentService().createContentItems( (CollectionItem) getItem(), toUpdate); } catch (IcalUidInUseException e) { throw new UidConflictException(e); } catch (CollectionLockedException e) { throw new LockedException(); } } member.setItem(content); } /** */ protected void removeContent(DavItemContent member) throws CosmoDavException { if (! (member instanceof DavCalendarResource)) { throw new IllegalArgumentException("member not DavCalendarResource"); } ContentItem content = (ContentItem) member.getItem(); CollectionItem parent = (CollectionItem) getItem(); // XXX: what exceptions need to be caught? if (LOG.isDebugEnabled()) { LOG.debug("removing event " + member.getResourcePath()); } try { if(content instanceof NoteItem) { getContentService().removeItemFromCollection(content, parent); } else { getContentService().removeContent(content); } } catch (CollectionLockedException e) { throw new LockedException(); } } private void validateDestination(org.apache.jackrabbit.webdav.DavResource destination) throws CosmoDavException { if (destination instanceof WebDavResource && ((WebDavResource)destination).getParent() instanceof DavCalendarCollection) { throw new InvalidCalendarLocationException("Parent collection of destination must not be a calendar collection"); } } }
removed unused code in DavCalendarCollection
src/main/java/org/unitedinternet/cosmo/dav/impl/DavCalendarCollection.java
removed unused code in DavCalendarCollection
Java
apache-2.0
936db413f10c24b1f78700b7e066ca33604fca53
0
CMPUT301W15T07/TravelTracker,CMPUT301W15T07/TravelTracker,CMPUT301W15T07/TravelTracker
package cmput301w15t07.TravelTracker.activity; /* * Copyright 2015 Kirby Banman, * Stuart Bildfell, * Elliot Colp, * Christian Ellinger, * Braedy Kuzma, * Ryan Thornhill * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.UUID; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.text.format.DateFormat; import android.util.SparseArray; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ScrollView; import android.widget.Space; import android.widget.TextView; import android.widget.Toast; import cmput301w15t07.TravelTracker.R; import cmput301w15t07.TravelTracker.model.ApproverComment; import cmput301w15t07.TravelTracker.model.Claim; import cmput301w15t07.TravelTracker.model.Item; import cmput301w15t07.TravelTracker.model.User; import cmput301w15t07.TravelTracker.model.UserData; import cmput301w15t07.TravelTracker.model.UserRole; import cmput301w15t07.TravelTracker.serverinterface.MultiCallback; import cmput301w15t07.TravelTracker.serverinterface.ResultCallback; import cmput301w15t07.TravelTracker.util.ApproverCommentAdapter; import cmput301w15t07.TravelTracker.util.ClaimUtilities; import cmput301w15t07.TravelTracker.util.DatePickerFragment; import cmput301w15t07.TravelTracker.util.NonScrollListView; /** * Activity for managing an individual Claim. Possible as a Claimant or * an Approver. * * @author kdbanman, * therabidsquirel, * colp * */ public class ClaimInfoActivity extends TravelTrackerActivity { /** String used to retrieve user data from intent */ public static final String USER_DATA = "cmput301w15t07.TravelTracker.userData"; /** String used to retrieve claim UUID from intent */ public static final String CLAIM_UUID = "cmput301w15t07.TravelTracker.claimUUID"; /** ID used to retrieve items from MutliCallback. */ public static final int MULTI_ITEMS_ID = 0; /** ID used to retrieve claimant from MutliCallback. */ public static final int MULTI_CLAIMANT_ID = 1; /** ID used to retrieve last approver from MutliCallback. */ public static final int MULTI_LAST_APPROVER_ID = 2; /** Data about the logged-in user. */ private UserData userData; /** UUID of the claim. */ private UUID claimID; /** The current claim. */ Claim claim; /** The currently open date picker fragment. */ private DatePickerFragment datePicker = null; @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.claim_info_menu, menu); // Menu items MenuItem addDestinationMenuItem = menu.findItem(R.id.claim_info_add_destination); MenuItem addItemMenuItem = menu.findItem(R.id.claim_info_add_item); MenuItem deleteClaimMenuItem = menu.findItem(R.id.claim_info_delete_claim); if (userData.getRole().equals(UserRole.CLAIMANT)) { } else if (userData.getRole().equals(UserRole.APPROVER)) { // Menu items an approver doesn't need to see or have access to addDestinationMenuItem.setEnabled(false).setVisible(false); addItemMenuItem.setEnabled(false).setVisible(false); deleteClaimMenuItem.setEnabled(false).setVisible(false); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.claim_info_add_destination: addDestination(); break; case R.id.claim_info_add_item: addItem(); break; case R.id.claim_info_delete_claim: promptDeleteClaim(); break; case R.id.claim_info_sign_out: signOut(); break; default: break; } return super.onOptionsItemSelected(item); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Retrieve user info from bundle Bundle bundle = getIntent().getExtras(); userData = (UserData) bundle.getSerializable(USER_DATA); // Get claim info claimID = (UUID) bundle.getSerializable(CLAIM_UUID); appendNameToTitle(userData.getName()); } @Override protected void onResume() { super.onResume(); // Show loading circle setContentView(R.layout.loading_indeterminate); datasource.getClaim(claimID, new ClaimCallback()); } public void onGetAllData(final Collection<Item> items, User claimant, User approver) { setContentView(R.layout.claim_info_activity); populateClaimInfo(claim, items, claimant, approver); // Claim attributes TextView claimantNameTextView = (TextView) findViewById(R.id.claimInfoClaimantNameTextView); TextView statusTextView = (TextView) findViewById(R.id.claimInfoStatusTextView); // Tags list LinearLayout tagsLinearLayout = (LinearLayout) findViewById(R.id.claimInfoTagsLinearLayout); Space tagsSpace = (Space) findViewById(R.id.claimInfoTagsSpace); // Claimant claim modifiers Button submitClaimButton = (Button) findViewById(R.id.claimInfoClaimSubmitButton); // Approver claim modifiers LinearLayout approverButtonsLinearLayout = (LinearLayout) findViewById(R.id.claimInfoApproverButtonsLinearLayout); Button returnClaimButton = (Button) findViewById(R.id.claimInfoClaimReturnButton); Button approveClaimButton = (Button) findViewById(R.id.claimInfoClaimApproveButton); EditText commentEditText = (EditText) findViewById(R.id.claimInfoCommentEditText); // Attach view items listener to view items button Button viewItemsButton = (Button) findViewById(R.id.claimInfoViewItemsButton); viewItemsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { viewItems(); } }); if (userData.getRole().equals(UserRole.CLAIMANT)) { // Attach edit date listener to start date button final Button startDateButton = (Button) findViewById(R.id.claimInfoStartDateButton); startDateButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startDatePressed(); } }); // Attach edit date listener to end date button final Button endDateButton = (Button) findViewById(R.id.claimInfoEndDateButton); endDateButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { endDatePressed(); } }); // Attach submit claim listener to submit claim button submitClaimButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { submitClaim(); } }); // Views a claimant doesn't need to see or have access to claimantNameTextView.setVisibility(View.GONE); approverButtonsLinearLayout.setVisibility(View.GONE); returnClaimButton.setVisibility(View.GONE); approveClaimButton.setVisibility(View.GONE); commentEditText.setVisibility(View.GONE); } else if (userData.getRole().equals(UserRole.APPROVER)) { // Attach return claim listener to return claim button returnClaimButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { returnClaim(); } }); // Attach approve claim listener to approve claim button approveClaimButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { approveClaim(); } }); // Views an approver doesn't need to see or have access to statusTextView.setVisibility(View.GONE); tagsLinearLayout.setVisibility(View.GONE); tagsSpace.setVisibility(View.GONE); submitClaimButton.setVisibility(View.GONE); // No last approver if (approver == null) { TextView lastApproverTextView = (TextView) findViewById(R.id.claimInfoLastApproverTextView); lastApproverTextView.setVisibility(View.GONE); } } onLoaded(); } public void addDestination() { // TODO Auto-generated method stub } public void addItem() { // TODO Auto-generated method stub } /** * Prompt for deleting the claim. */ public void promptDeleteClaim() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.claim_info_delete_message) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { deleteClaim(); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Do nothing } }); builder.create().show(); } /** * Delete the claim and finish the activity. */ public void deleteClaim() { datasource.deleteClaim(claimID, new DeleteCallback()); } /** * Populate the fields with data. * @param claim The claim being viewed. * @param items All items (which will be filtered by claim UUID). * @param user The claimant, or null if the current user is the claimant. * @param approver The last approver, or null if there isn't one. */ public void populateClaimInfo(Claim claim, Collection<Item> items, User claimant, User approver) { Button startDateButton = (Button) findViewById(R.id.claimInfoStartDateButton); setButtonDate(startDateButton, claim.getStartDate()); Button endDateButton = (Button) findViewById(R.id.claimInfoEndDateButton); setButtonDate(endDateButton, claim.getEndDate()); String statusString = getString(R.string.claim_info_claim_status) + " " + claim.getStatus().getString(this); TextView statusTextView = (TextView) findViewById(R.id.claimInfoStatusTextView); statusTextView.setText(statusString); // Get list of claim items ArrayList<Item> claimItems = new ArrayList<Item>(); for (Item item : items) { if (item.getClaim() == claim.getUUID()) { claimItems.add(item); } } // Format string for view items button String formatString = getString(R.string.claim_info_view_items); String viewItemsButtonText = String.format(formatString, claimItems.size()); Button viewItemsButton = (Button) findViewById(R.id.claimInfoViewItemsButton); viewItemsButton.setText(viewItemsButtonText); // List totals ArrayList<String> totals = ClaimUtilities.getTotals(claimItems); String totalsString = TextUtils.join("\n", totals); TextView totalsTextView = (TextView) findViewById(R.id.claimInfoCurrencyTotalsListTextView); totalsTextView.setText(totalsString); // Show approver comments NonScrollListView commentsLinearLayout = (NonScrollListView) findViewById(R.id.claimInfoCommentsListView); commentsLinearLayout.setAdapter(new ApproverCommentAdapter(this, datasource, claim.getComments())); if (userData.getRole() == UserRole.APPROVER) { // Claimant name TextView claimantNameTextView = (TextView) findViewById(R.id.claimInfoClaimantNameTextView); String claimantString = getString(R.string.claim_info_claimant_name) + " " + claimant.getUserName(); claimantNameTextView.setText(claimantString); } // Approver name (if there is one) if (approver != null) { TextView lastApproverTextView = (TextView) findViewById(R.id.claimInfoLastApproverTextView); String lastApproverString = getString(R.string.claim_info_last_approver) + " " + approver.getUserName(); lastApproverTextView.setText(lastApproverString); } // Scroll to top now in case comment list has extended the layout // Referenced http://stackoverflow.com/a/4488149 on 12/03/15 final ScrollView scrollView = (ScrollView) findViewById(R.id.claimInfoScrollView); scrollView.post(new Runnable() { @Override public void run() { scrollView.fullScroll(ScrollView.FOCUS_UP); } }); } public void viewItems() { // Start next activity Intent intent = new Intent(this, ExpenseItemsListActivity.class); intent.putExtra(ExpenseItemsListActivity.USER_DATA, userData); intent.putExtra(ExpenseItemsListActivity.CLAIM_UUID, claimID); startActivity(intent); } public void startDatePressed() { Date date = claim.getStartDate(); datePicker = new DatePickerFragment(date, new StartDateCallback()); datePicker.show(getFragmentManager(), "datePicker"); } public void endDatePressed() { Date date = claim.getEndDate(); datePicker = new DatePickerFragment(date, new EndDateCallback()); datePicker.show(getFragmentManager(), "datePicker"); } public void submitClaim() { // TODO Auto-generated method stub } public void returnClaim() { // TODO Auto-generated method stub } public void approveClaim() { // TODO Auto-generated method stub } /** * Get the currently displayed date picker fragment. * @return The DatePickerFragment, or null if there isn't one. */ public DatePickerFragment getDatePickerFragment() { return datePicker; } private void setButtonDate(Button dateButton, Date date) { java.text.DateFormat dateFormat = DateFormat.getMediumDateFormat(this); String dateString = dateFormat.format(date); dateButton.setText(dateString); } /** * Callback for claim data. */ class ClaimCallback implements ResultCallback<Claim> { @Override public void onResult(Claim claim) { ClaimInfoActivity.this.claim = claim; // Determine the number of approver comments ArrayList<ApproverComment> comments = claim.getComments(); // Retrieve data MultiCallback multi = new MultiCallback(new ClaimDataMultiCallback()); // Create callbacks for MultiCallback datasource.getAllItems(multi.<Collection<Item>>createCallback(MULTI_ITEMS_ID)); datasource.getUser(claim.getUser(), multi.<User>createCallback(MULTI_CLAIMANT_ID)); if (comments.size() > 0) { ApproverComment comment = comments.get(0); datasource.getUser(comment.getApprover(), multi.<User>createCallback(MULTI_LAST_APPROVER_ID)); } multi.ready(); } @Override public void onError(String message) { Toast.makeText(ClaimInfoActivity.this, message, Toast.LENGTH_LONG).show(); } } /** * Callback for multiple types of claim data. */ class ClaimDataMultiCallback implements ResultCallback<SparseArray<Object>> { @Override public void onResult(SparseArray<Object> result) { User claimant = (User) result.get(MULTI_CLAIMANT_ID); User approver = (User) result.get(MULTI_LAST_APPROVER_ID); // We know the return result is the right type, so an unchecked // cast shouldn't be problematic @SuppressWarnings("unchecked") Collection<Item> items = (Collection<Item>) result.get(MULTI_ITEMS_ID); onGetAllData(items, claimant, approver); } @Override public void onError(String message) { Toast.makeText(ClaimInfoActivity.this, message, Toast.LENGTH_LONG).show(); } } /** * Callback for claim deletion. */ class DeleteCallback implements ResultCallback<Void> { @Override public void onResult(Void result) { finish(); } @Override public void onError(String message) { Toast.makeText(ClaimInfoActivity.this, message, Toast.LENGTH_LONG).show(); } } /** * Callback for when a new start date is selected. */ class StartDateCallback implements DatePickerFragment.ResultCallback { @Override public void onDatePickerFragmentResult(Date result) { // Error if invalid date if (result.after(claim.getEndDate())) { String error = getString(R.string.claim_info_start_date_error); Toast.makeText(ClaimInfoActivity.this, error, Toast.LENGTH_LONG).show(); // Update date button and date } else { claim.setStartDate(result); Button button = (Button) findViewById(R.id.claimInfoStartDateButton); setButtonDate(button, result); } datePicker = null; } @Override public void onDatePickerFragmentCancelled() { datePicker = null; } } /** * Callback for when a new end date is selected. */ class EndDateCallback implements DatePickerFragment.ResultCallback { @Override public void onDatePickerFragmentResult(Date result) { // Error if invalid date if (result.before(claim.getStartDate())) { String error = getString(R.string.claim_info_end_date_error); Toast.makeText(ClaimInfoActivity.this, error, Toast.LENGTH_LONG).show(); // Update date button and calendar } else { claim.setEndDate(result); Button button = (Button) findViewById(R.id.claimInfoEndDateButton); setButtonDate(button, result); } datePicker = null; } @Override public void onDatePickerFragmentCancelled() { datePicker = null; } } }
src/cmput301w15t07/TravelTracker/activity/ClaimInfoActivity.java
package cmput301w15t07.TravelTracker.activity; /* * Copyright 2015 Kirby Banman, * Stuart Bildfell, * Elliot Colp, * Christian Ellinger, * Braedy Kuzma, * Ryan Thornhill * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.UUID; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.text.format.DateFormat; import android.util.SparseArray; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ScrollView; import android.widget.Space; import android.widget.TextView; import android.widget.Toast; import cmput301w15t07.TravelTracker.R; import cmput301w15t07.TravelTracker.model.ApproverComment; import cmput301w15t07.TravelTracker.model.Claim; import cmput301w15t07.TravelTracker.model.Item; import cmput301w15t07.TravelTracker.model.User; import cmput301w15t07.TravelTracker.model.UserData; import cmput301w15t07.TravelTracker.model.UserRole; import cmput301w15t07.TravelTracker.serverinterface.MultiCallback; import cmput301w15t07.TravelTracker.serverinterface.ResultCallback; import cmput301w15t07.TravelTracker.util.ApproverCommentAdapter; import cmput301w15t07.TravelTracker.util.ClaimUtilities; import cmput301w15t07.TravelTracker.util.DatePickerFragment; import cmput301w15t07.TravelTracker.util.NonScrollListView; /** * Activity for managing an individual Claim. Possible as a Claimant or * an Approver. * * @author kdbanman, * therabidsquirel, * colp * */ public class ClaimInfoActivity extends TravelTrackerActivity { /** String used to retrieve user data from intent */ public static final String USER_DATA = "cmput301w15t07.TravelTracker.userData"; /** String used to retrieve claim UUID from intent */ public static final String CLAIM_UUID = "cmput301w15t07.TravelTracker.claimUUID"; /** ID used to retrieve items from MutliCallback. */ public static final int MULTI_ITEMS_ID = 0; /** ID used to retrieve claimant from MutliCallback. */ public static final int MULTI_CLAIMANT_ID = 1; /** ID used to retrieve last approver from MutliCallback. */ public static final int MULTI_LAST_APPROVER_ID = 2; /** Data about the logged-in user. */ private UserData userData; /** UUID of the claim. */ private UUID claimID; /** The current claim. */ Claim claim; /** The currently open date picker fragment. */ private DatePickerFragment datePicker = null; @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.claim_info_menu, menu); // Menu items MenuItem addDestinationMenuItem = menu.findItem(R.id.claim_info_add_destination); MenuItem addItemMenuItem = menu.findItem(R.id.claim_info_add_item); MenuItem deleteClaimMenuItem = menu.findItem(R.id.claim_info_delete_claim); if (userData.getRole().equals(UserRole.CLAIMANT)) { } else if (userData.getRole().equals(UserRole.APPROVER)) { // Menu items an approver doesn't need to see or have access to addDestinationMenuItem.setEnabled(false).setVisible(false); addItemMenuItem.setEnabled(false).setVisible(false); deleteClaimMenuItem.setEnabled(false).setVisible(false); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.claim_info_add_destination: addDestination(); break; case R.id.claim_info_add_item: addItem(); break; case R.id.claim_info_delete_claim: promptDeleteClaim(); break; case R.id.claim_info_sign_out: signOut(); break; default: break; } return super.onOptionsItemSelected(item); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Retrieve user info from bundle Bundle bundle = getIntent().getExtras(); userData = (UserData) bundle.getSerializable(USER_DATA); // Get claim info claimID = (UUID) bundle.getSerializable(CLAIM_UUID); appendNameToTitle(userData.getName()); } @Override protected void onResume() { super.onResume(); // Show loading circle setContentView(R.layout.loading_indeterminate); datasource.getClaim(claimID, new ResultCallback<Claim>() { @Override public void onResult(final Claim claim) { // Determine the number of approver comments ArrayList<ApproverComment> comments = claim.getComments(); // Retrieve data MultiCallback multi = new MultiCallback(new ResultCallback<SparseArray<Object>>() { @Override public void onResult(SparseArray<Object> result) { User claimant = (User) result.get(MULTI_CLAIMANT_ID); User approver = (User) result.get(MULTI_LAST_APPROVER_ID); // We know the return result is the right type, so an unchecked // cast shouldn't be problematic @SuppressWarnings("unchecked") Collection<Item> items = (Collection<Item>) result.get(MULTI_ITEMS_ID); onGetAllData(claim, items, claimant, approver); } @Override public void onError(String message) { Toast.makeText(ClaimInfoActivity.this, message, Toast.LENGTH_LONG).show(); } }); // Create callbacks for MultiCallback datasource.getAllItems(multi.<Collection<Item>>createCallback(MULTI_ITEMS_ID)); datasource.getUser(claim.getUser(), multi.<User>createCallback(MULTI_CLAIMANT_ID)); if (comments.size() > 0) { ApproverComment comment = comments.get(0); datasource.getUser(comment.getApprover(), multi.<User>createCallback(MULTI_LAST_APPROVER_ID)); } multi.ready(); } @Override public void onError(String message) { Toast.makeText(ClaimInfoActivity.this, message, Toast.LENGTH_LONG).show(); } }); } public void onGetAllData(final Claim claim, final Collection<Item> items, User claimant, User approver) { this.claim = claim; setContentView(R.layout.claim_info_activity); populateClaimInfo(claim, items, claimant, approver); // Claim attributes TextView claimantNameTextView = (TextView) findViewById(R.id.claimInfoClaimantNameTextView); TextView statusTextView = (TextView) findViewById(R.id.claimInfoStatusTextView); // Tags list LinearLayout tagsLinearLayout = (LinearLayout) findViewById(R.id.claimInfoTagsLinearLayout); Space tagsSpace = (Space) findViewById(R.id.claimInfoTagsSpace); // Claimant claim modifiers Button submitClaimButton = (Button) findViewById(R.id.claimInfoClaimSubmitButton); // Approver claim modifiers LinearLayout approverButtonsLinearLayout = (LinearLayout) findViewById(R.id.claimInfoApproverButtonsLinearLayout); Button returnClaimButton = (Button) findViewById(R.id.claimInfoClaimReturnButton); Button approveClaimButton = (Button) findViewById(R.id.claimInfoClaimApproveButton); EditText commentEditText = (EditText) findViewById(R.id.claimInfoCommentEditText); // Attach view items listener to view items button Button viewItemsButton = (Button) findViewById(R.id.claimInfoViewItemsButton); viewItemsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { viewItems(); } }); if (userData.getRole().equals(UserRole.CLAIMANT)) { // Attach edit date listener to start date button final Button startDateButton = (Button) findViewById(R.id.claimInfoStartDateButton); startDateButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startDatePressed(); } }); // Attach edit date listener to end date button final Button endDateButton = (Button) findViewById(R.id.claimInfoEndDateButton); endDateButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { endDatePressed(); } }); // Attach submit claim listener to submit claim button submitClaimButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { submitClaim(); } }); // Views a claimant doesn't need to see or have access to claimantNameTextView.setVisibility(View.GONE); approverButtonsLinearLayout.setVisibility(View.GONE); returnClaimButton.setVisibility(View.GONE); approveClaimButton.setVisibility(View.GONE); commentEditText.setVisibility(View.GONE); } else if (userData.getRole().equals(UserRole.APPROVER)) { // Attach return claim listener to return claim button returnClaimButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { returnClaim(); } }); // Attach approve claim listener to approve claim button approveClaimButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { approveClaim(); } }); // Views an approver doesn't need to see or have access to statusTextView.setVisibility(View.GONE); tagsLinearLayout.setVisibility(View.GONE); tagsSpace.setVisibility(View.GONE); submitClaimButton.setVisibility(View.GONE); // No last approver if (approver == null) { TextView lastApproverTextView = (TextView) findViewById(R.id.claimInfoLastApproverTextView); lastApproverTextView.setVisibility(View.GONE); } } onLoaded(); } public void addDestination() { // TODO Auto-generated method stub } public void addItem() { // TODO Auto-generated method stub } /** * Prompt for deleting the claim. */ public void promptDeleteClaim() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.claim_info_delete_message) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { deleteClaim(); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Do nothing } }); builder.create().show(); } /** * Delete the claim and finish the activity. */ public void deleteClaim() { datasource.deleteClaim(claimID, new ResultCallback<Void>() { @Override public void onResult(Void result) { finish(); } @Override public void onError(String message) { Toast.makeText(ClaimInfoActivity.this, message, Toast.LENGTH_LONG).show(); } }); } /** * Populate the fields with data. * @param claim The claim being viewed. * @param items All items (which will be filtered by claim UUID). * @param user The claimant, or null if the current user is the claimant. * @param approver The last approver, or null if there isn't one. */ public void populateClaimInfo(Claim claim, Collection<Item> items, User claimant, User approver) { Button startDateButton = (Button) findViewById(R.id.claimInfoStartDateButton); setButtonDate(startDateButton, claim.getStartDate()); Button endDateButton = (Button) findViewById(R.id.claimInfoEndDateButton); setButtonDate(endDateButton, claim.getEndDate()); String statusString = getString(R.string.claim_info_claim_status) + " " + claim.getStatus().getString(this); TextView statusTextView = (TextView) findViewById(R.id.claimInfoStatusTextView); statusTextView.setText(statusString); // Get list of claim items ArrayList<Item> claimItems = new ArrayList<Item>(); for (Item item : items) { if (item.getClaim() == claim.getUUID()) { claimItems.add(item); } } // Format string for view items button String formatString = getString(R.string.claim_info_view_items); String viewItemsButtonText = String.format(formatString, claimItems.size()); Button viewItemsButton = (Button) findViewById(R.id.claimInfoViewItemsButton); viewItemsButton.setText(viewItemsButtonText); // List totals ArrayList<String> totals = ClaimUtilities.getTotals(claimItems); String totalsString = TextUtils.join("\n", totals); TextView totalsTextView = (TextView) findViewById(R.id.claimInfoCurrencyTotalsListTextView); totalsTextView.setText(totalsString); // Show approver comments NonScrollListView commentsLinearLayout = (NonScrollListView) findViewById(R.id.claimInfoCommentsListView); commentsLinearLayout.setAdapter(new ApproverCommentAdapter(this, datasource, claim.getComments())); if (userData.getRole() == UserRole.APPROVER) { // Claimant name TextView claimantNameTextView = (TextView) findViewById(R.id.claimInfoClaimantNameTextView); String claimantString = getString(R.string.claim_info_claimant_name) + " " + claimant.getUserName(); claimantNameTextView.setText(claimantString); } // Approver name (if there is one) if (approver != null) { TextView lastApproverTextView = (TextView) findViewById(R.id.claimInfoLastApproverTextView); String lastApproverString = getString(R.string.claim_info_last_approver) + " " + approver.getUserName(); lastApproverTextView.setText(lastApproverString); } // Scroll to top now in case comment list has extended the layout // Referenced http://stackoverflow.com/a/4488149 on 12/03/15 final ScrollView scrollView = (ScrollView) findViewById(R.id.claimInfoScrollView); scrollView.post(new Runnable() { @Override public void run() { scrollView.fullScroll(ScrollView.FOCUS_UP); } }); } public void viewItems() { // Start next activity Intent intent = new Intent(this, ExpenseItemsListActivity.class); intent.putExtra(ExpenseItemsListActivity.USER_DATA, userData); intent.putExtra(ExpenseItemsListActivity.CLAIM_UUID, claimID); startActivity(intent); } public void startDatePressed() { final Button dateButton = (Button) findViewById(R.id.claimInfoStartDateButton); final Date date = claim.getStartDate(); datePicker = new DatePickerFragment(date, new DatePickerFragment.ResultCallback() { @Override public void onDatePickerFragmentResult(Date result) { // Error if invalid date if (result.after(claim.getEndDate())) { String error = getString(R.string.claim_info_start_date_error); Toast.makeText(ClaimInfoActivity.this, error, Toast.LENGTH_LONG).show(); // Update date button and calendar } else { date.setTime(result.getTime()); setButtonDate(dateButton, result); } datePicker = null; } @Override public void onDatePickerFragmentCancelled() { datePicker = null; } }); datePicker.show(getFragmentManager(), "datePicker"); } public void endDatePressed() { final Button dateButton = (Button) findViewById(R.id.claimInfoEndDateButton); final Date date = claim.getEndDate(); datePicker = new DatePickerFragment(date, new DatePickerFragment.ResultCallback() { @Override public void onDatePickerFragmentResult(Date result) { // Error if invalid date if (result.before(claim.getStartDate())) { String error = getString(R.string.claim_info_end_date_error); Toast.makeText(ClaimInfoActivity.this, error, Toast.LENGTH_LONG).show(); // Update date button and calendar } else { date.setTime(result.getTime()); setButtonDate(dateButton, result); } datePicker = null; } @Override public void onDatePickerFragmentCancelled() { datePicker = null; } }); datePicker.show(getFragmentManager(), "datePicker"); } public void submitClaim() { // TODO Auto-generated method stub } public void returnClaim() { // TODO Auto-generated method stub } public void approveClaim() { // TODO Auto-generated method stub } /** * Get the currently displayed date picker fragment. * @return The DatePickerFragment, or null if there isn't one. */ public DatePickerFragment getDatePickerFragment() { return datePicker; } private void setButtonDate(Button dateButton, Date date) { java.text.DateFormat dateFormat = DateFormat.getMediumDateFormat(this); String dateString = dateFormat.format(date); dateButton.setText(dateString); } }
Refactored anonymous callback classes into nested classes
src/cmput301w15t07/TravelTracker/activity/ClaimInfoActivity.java
Refactored anonymous callback classes into nested classes
Java
apache-2.0
4f1f735fa35b6d5c03c413d35f940de1e82a6a1b
0
aulonm/INF2100,aulonm/INF2100
package no.uio.ifi.alboc.syntax; /* * module Syntax */ import no.uio.ifi.alboc.alboc.AlboC; import no.uio.ifi.alboc.code.Code; import no.uio.ifi.alboc.error.Error; import no.uio.ifi.alboc.log.Log; import no.uio.ifi.alboc.scanner.Scanner; import no.uio.ifi.alboc.scanner.Token; import static no.uio.ifi.alboc.scanner.Token.*; import no.uio.ifi.alboc.types.*; /* * Creates a syntax tree by parsing an AlboC program; * prints the parse tree (if requested); * checks it; * generates executable code. */ public class Syntax { static DeclList library; static Program program; public static void init() { // -- Must be changed in part 1+2: library = new GlobalDeclList(); library.addDecl(new FuncDecl("exit", Types.intType, "status")); library.addDecl(new FuncDecl("getchar", Types.intType, null)); library.addDecl(new FuncDecl("getint", Types.intType, null)); library.addDecl(new FuncDecl("putchar", Types.intType, "c")); library.addDecl(new FuncDecl("putint", Types.intType, "c")); Scanner.readNext(); Scanner.readNext(); } public static void finish() { // -- Must be changed in part 1+2: } public static void checkProgram() { program.check(library); } public static void genCode() { program.genCode(null); } public static void parseProgram() { program = Program.parse(); } public static void printProgram() { program.printTree(); } } /* * Super class for all syntactic units. (This class is not mentioned in the * syntax diagrams.) */ abstract class SyntaxUnit { int lineNum; SyntaxUnit() { lineNum = Scanner.curLine; } abstract void check(DeclList curDecls); abstract void genCode(FuncDecl curFunc); abstract void printTree(); void error(String message) { Error.error(lineNum, message); } } /* * A <program> */ class Program extends SyntaxUnit { DeclList progDecls; @Override void check(DeclList curDecls) { progDecls.check(curDecls); if (!AlboC.noLink) { // Check that 'main' has been declared properly: // -- Must be changed in part 2: FuncDecl main; Declaration d = progDecls.findDecl("main", null); Log.noteBinding("main", 0, d.lineNum); main = (FuncDecl) d; if(main.type != Types.intType) error("'main' should return type 'int'"); } } @Override void genCode(FuncDecl curFunc) { progDecls.genCode(null); } static Program parse() { Log.enterParser("<program>"); Program p = new Program(); p.progDecls = GlobalDeclList.parse(); if (Scanner.curToken != eofToken) { Error.expected("A declaration"); } //System.out.println(Log.ut + " what " + Log.inn); Log.leaveParser("</program>"); return p; } @Override void printTree() { progDecls.printTree(); } } /* * A declaration list. (This class is not mentioned in the syntax diagrams.) */ abstract class DeclList extends SyntaxUnit { Declaration firstDecl = null; DeclList outerScope; DeclList() { // -- Must be changed in part 1: } @Override void check(DeclList curDecls) { outerScope = curDecls; Declaration dx = firstDecl; while (dx != null) { dx.check(this); dx = dx.nextDecl; } } @Override void printTree() { // -- Must be changed in part 1: Declaration currDecl = firstDecl; while(currDecl != null){ currDecl.printTree(); currDecl = currDecl.nextDecl; } } // Lager FIFO liste void addDecl(Declaration d) { // -- Must be changed in part 1: if(firstDecl == null){ firstDecl = d; } else{ Declaration prevDecl = firstDecl; while(prevDecl.nextDecl != null){ if(prevDecl.name.equals(d.name)) d.error("name " + d.name + " already declared"); prevDecl = prevDecl.nextDecl; } if(prevDecl.name.equals(d.name)) d.error("name " + d.name + " already declared"); prevDecl.nextDecl = d; } } int dataSize() { Declaration dx = firstDecl; int res = 0; while (dx != null) { res += dx.declSize(); dx = dx.nextDecl; } return res; } Declaration findDecl(String name, SyntaxUnit use) { // -- Must be changed in part 2: Declaration dx = firstDecl; while(dx != null){ if(dx.name.equals(name) && dx.visible == true){ System.out.println(dx.name); return dx; } dx = dx.nextDecl; } if(outerScope != null){ return outerScope.findDecl(name, use); }else{ if(use != null){ Error.error("unknown"); }else{ Error.error("unknown2"); } } Error.error("name " + name + " is unknown"); return null; } } /* * A list of global declarations. (This class is not mentioned in the syntax * diagrams.) */ class GlobalDeclList extends DeclList { @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: Declaration gdl = firstDecl; while(gdl != null){ gdl.genCode(curFunc); gdl = gdl.nextDecl; } } static GlobalDeclList parse() { GlobalDeclList gdl = new GlobalDeclList(); while (Scanner.curToken == intToken) { DeclType ts = DeclType.parse(); gdl.addDecl(Declaration.parse(ts)); } return gdl; } } /* * A list of local declarations. (This class is not mentioned in the syntax * diagrams.) */ class LocalDeclList extends DeclList { @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: if(firstDecl != null) { // Declaration ldl = firstDecl; // while(ldl != null){ // ldl.genCode(curFunc); // ldl = ldl.nextDecl; // } Declaration ldl = firstDecl; if(ldl.nextDecl != null) { ldl.nextDecl.genCode(curFunc); } ldl.genCode(curFunc); } } static LocalDeclList parse() { // -- Must be changed in part 1: LocalDeclList ldl = new LocalDeclList(); while(Scanner.curToken == intToken){ DeclType ts = DeclType.parse(); ldl.addDecl(LocalVarDecl.parse(ts)); } return ldl; } } /* * A list of parameter declarations. (This class is not mentioned in the syntax * diagrams.) */ class ParamDeclList extends DeclList { static int length = 0; @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2:' if(firstDecl != null) { Declaration pdl = firstDecl; if(pdl.nextDecl != null) { pdl.nextDecl.genCode(curFunc); } pdl.genCode(curFunc); } // Declaration pdl = firstDecl; // while(pdl != null){ // pdl.genCode(curFunc); // pdl = pdl.nextDecl; // } } static ParamDeclList parse() { // -- Must be changed in part 1: ParamDeclList pdl = new ParamDeclList(); while(Scanner.curToken == intToken){ DeclType ts = DeclType.parse(); pdl.addDecl(ParamDecl.parse(ts)); length++; } return pdl; } @Override void printTree() { Declaration px = firstDecl; while (px != null) { px.printTree(); px = px.nextDecl; if (px != null) Log.wTree(", "); } } } /* * A <type> */ class DeclType extends SyntaxUnit { int numStars = 0; Type type; @Override void check(DeclList curDecls) { type = Types.intType; for (int i = 1; i <= numStars; ++i) type = new PointerType(type); } @Override void genCode(FuncDecl curFunc) { } static DeclType parse() { Log.enterParser("<type>"); DeclType dt = new DeclType(); Scanner.skip(intToken); while (Scanner.curToken == starToken) { ++dt.numStars; Scanner.readNext(); } Log.leaveParser("</type>"); return dt; } @Override void printTree() { Log.wTree("int"); for (int i = 1; i <= numStars; ++i) Log.wTree("*"); } } /* * Any kind of declaration. */ abstract class Declaration extends SyntaxUnit { String name, assemblerName; DeclType typeSpec; Type type; boolean visible = false; Declaration nextDecl = null; int offset = 0; Declaration(String n) { name = n; } abstract int declSize(); static Declaration parse(DeclType dt) { Declaration d = null; if (Scanner.curToken == nameToken && Scanner.nextToken == leftParToken) { d = FuncDecl.parse(dt); } else if (Scanner.curToken == nameToken) { d = GlobalVarDecl.parse(dt); } else { Error.expected("A declaration name"); } d.typeSpec = dt; return d; } /** * checkWhetherVariable: Utility method to check whether this Declaration is * really a variable. The compiler must check that a name is used properly; * for instance, using a variable name a in "a()" is illegal. This is * handled in the following way: * <ul> * <li>When a name a is found in a setting which implies that should be a * variable, the parser will first search for a's declaration d. * <li>The parser will call d.checkWhetherVariable(this). * <li>Every sub-class of Declaration will implement a checkWhetherVariable. * If the declaration is indeed a variable, checkWhetherVariable will do * nothing, but if it is not, the method will give an error message. * </ul> * Examples * <dl> * <dt>GlobalVarDecl.checkWhetherVariable(...)</dt> * <dd>will do nothing, as everything is all right.</dd> * <dt>FuncDecl.checkWhetherVariable(...)</dt> * <dd>will give an error message.</dd> * </dl> */ abstract void checkWhetherVariable(SyntaxUnit use); /** * checkWhetherFunction: Utility method to check whether this Declaration is * really a function. * * @param nParamsUsed * Number of parameters used in the actual call. (The method will * give an error message if the function was used with too many * or too few parameters.) * @param use * From where is the check performed? * @see //checkWhetherVariable */ abstract void checkWhetherFunction(int nParamsUsed, SyntaxUnit use); } /* * A <var decl> */ abstract class VarDecl extends Declaration { boolean isArray = false; int numElems = 0; VarDecl(String n) { super(n); } @Override void check(DeclList curDecls) { // -- Must be changed in part 2: visible = true; typeSpec.check(curDecls); if(isArray){ type = new ArrayType(typeSpec.type, numElems); }else { type = typeSpec.type; } } @Override void printTree() { typeSpec.printTree(); Log.wTree(" " + name); Log.wTreeLn(";"); } @Override int declSize() { return type.size(); } @Override void checkWhetherFunction(int nParamsUsed, SyntaxUnit use) { use.error(name + " is a variable and no function!"); } @Override void checkWhetherVariable(SyntaxUnit use) { // OK } } /* * A global <var decl>. */ class GlobalVarDecl extends VarDecl { GlobalVarDecl(String n) { super(n); assemblerName = (AlboC.underscoredGlobals() ? "_" : "") + n; } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: // set offset if(isArray){ Code.genVar(assemblerName, true, numElems, type.size()/numElems, type + " " + name); } else{ Code.genVar(assemblerName, true, 1, type.size(), type + " " + name); } } static GlobalVarDecl parse(DeclType dt) { Log.enterParser("<var decl>"); // -- Must be changed in part 1: GlobalVarDecl gv = new GlobalVarDecl(Scanner.curName); gv.typeSpec = dt; Scanner.skip(nameToken); if(Scanner.curToken == leftBracketToken) { // we found an array. gv.isArray = true; Scanner.skip(leftBracketToken); // skip this leftbracket gv.numElems = Scanner.curNum; Scanner.skip(numberToken); // skip the array size Scanner.skip(rightBracketToken); // skip the next right bracket token } Scanner.skip(semicolonToken); Log.leaveParser("</var decl>"); return gv; } } /* * A local variable declaration */ class LocalVarDecl extends VarDecl { LocalVarDecl(String n) { super(n); } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: assemblerName = "-"+curFunc.localOffset+"(%ebp)"; curFunc.localOffset -= 4; } static LocalVarDecl parse(DeclType dt) { Log.enterParser("<var decl>"); LocalVarDecl vv = new LocalVarDecl(Scanner.curName); vv.typeSpec = dt; Scanner.skip(nameToken); if(Scanner.curToken == leftBracketToken){ vv.isArray = true; Scanner.skip(leftBracketToken); vv.numElems = Scanner.curNum; Scanner.skip(numberToken); // skip the array size Scanner.skip(rightBracketToken); // skip the next right bracket token } Scanner.skip(semicolonToken); Log.leaveParser("</var decl>"); // -- Must be changed in part 1: return vv; } } /* * A <param decl> */ class ParamDecl extends VarDecl { ParamDecl(String n) { super(n); } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: curFunc.paramOffset -= 4; assemblerName = curFunc.paramOffset+"(%ebp)"; } static ParamDecl parse(DeclType dt) { Log.enterParser("<param decl>"); // -- Must be changed in part 1: ParamDecl pd = new ParamDecl(Scanner.curName); pd.typeSpec = dt; Scanner.skip(nameToken); if(Scanner.curToken == commaToken){ Scanner.skip(commaToken); } Log.leaveParser("</param decl>"); return pd; } @Override void printTree() { typeSpec.printTree(); Log.wTree(" " + name); } } /* * A <func decl> */ class FuncDecl extends Declaration { ParamDeclList funcParams; LocalDeclList funcVars; StatmList funcBody; String exitLabel; int paramOffset = 8; int localOffset = 0; FuncDecl(String n) { // Used for user functions: super(n); assemblerName = (AlboC.underscoredGlobals() ? "_" : "") + n; // -- Must be changed in part 1: } FuncDecl(String n, Type rt, String t){ super(n); visible = true; assemblerName = (AlboC.underscoredGlobals() ? "_" : "") + n; this.type = rt; funcParams = new ParamDeclList(); if(t != null){ ParamDecl p = new ParamDecl(t); funcParams.addDecl(p); funcParams.firstDecl.type = Types.intType; } } @Override int declSize() { return 0; } @Override void check(DeclList curDecls) { // -- Must be changed in part 2: visible = true; typeSpec.check(curDecls); type = typeSpec.type; if(funcParams != null) { funcParams.check(curDecls); funcVars.check(funcParams); } else{ funcVars.check(curDecls); } funcBody.check(funcVars); } @Override void checkWhetherFunction(int nParamsUsed, SyntaxUnit use) { // -- Must be changed in part 2: if(funcParams != null && funcParams.length != nParamsUsed){ Error.error("FUCK THIS"); } } @Override void checkWhetherVariable(SyntaxUnit use) { // -- Must be changed in part 2: use.error(name + " is a function and no variable!"); } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: Code.genInstr("", ".globl", assemblerName, ""); Code.genInstr(assemblerName, "enter", "$"+funcVars.dataSize()+",$0", "Start function " + name); if(funcParams != null){ paramOffset += funcParams.dataSize(); funcParams.genCode(this); } localOffset += funcVars.dataSize(); funcVars.genCode(this); funcBody.genCode(this); Code.genInstr(".exit$"+name,"","",""); Code.genInstr("","leave","",""); Code.genInstr("","ret","","End function " + name); } static FuncDecl parse(DeclType ts) { // -- Must be changed in part 1: /* What to do: first parse ParamDecList and save to funcParams. next we need to parse a local declaration list then we need some sort of function body, which would be a statmList i guess. then we return the object. */ Log.enterParser("<func decl>"); FuncDecl fd = new FuncDecl(Scanner.curName); // start with creating a new object fd.typeSpec = ts; Scanner.skip(nameToken); Scanner.skip(leftParToken); fd.funcParams = ParamDeclList.parse(); Scanner.skip(rightParToken); Log.enterParser("<func body>"); Scanner.skip(leftCurlToken); fd.funcVars = LocalDeclList.parse(); fd.funcBody = StatmList.parse(); Log.leaveParser("</func body>"); Log.leaveParser("</func delc>"); return fd; } @Override void printTree() { // -- Must be changed in part 1: typeSpec.printTree(); Log.wTree(" " +name); Log.wTree("("); funcParams.printTree(); Log.wTree(")"); Log.wTreeLn("{"); Log.indentTree(); funcVars.printTree(); funcBody.printTree(); Log.wTreeLn(); Log.outdentTree(); Log.wTreeLn("}"); } } /* * A <statm list>. */ class StatmList extends SyntaxUnit { // -- Must be changed in part 1: Statement first = null; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: if(first != null){ Statement s = first; s.check(curDecls); while(s.nextStatm != null){ // sjekker alle statements i lista s = s.nextStatm; s.check(curDecls); } } } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: if(first != null){ Statement s = first; s.genCode(curFunc); while(s.nextStatm != null){ s = s.nextStatm; s.genCode(curFunc); } } } static StatmList parse() { Log.enterParser("<statm list>"); StatmList sl = new StatmList(); while (Scanner.curToken != rightCurlToken) { // -- Must be changed in part 1: if(sl.first == null){ sl.first = Statement.parse(); } else{ Statement lastStatm = null; lastStatm = sl.first; while(lastStatm.nextStatm != null){ lastStatm = lastStatm.nextStatm; } lastStatm.nextStatm = Statement.parse(); } } Scanner.skip(rightCurlToken); Log.leaveParser("</statm list>"); return sl; } @Override void printTree() { // -- Must be changed in part 1: Statement currStatm = first; while(currStatm != null){ currStatm.printTree(); currStatm = currStatm.nextStatm; } } } /* * A <statement>. */ abstract class Statement extends SyntaxUnit { Statement nextStatm = null; static Statement parse() { Log.enterParser("<statement>"); Statement s = null; if (Scanner.curToken == nameToken && Scanner.nextToken == leftParToken) { // -- Must be changed in part 1: s = CallStatm.parse(); } else if (Scanner.curToken == nameToken || Scanner.curToken == starToken) { // -- Must be changed in part 1: s = AssignStatm.parse(); } else if (Scanner.curToken == forToken) { // -- Must be changed in part 1: s = ForStatm.parse(); } else if (Scanner.curToken == ifToken) { s = IfStatm.parse(); } else if (Scanner.curToken == returnToken) { // -- Must be changed in part 1: s = ReturnStatm.parse(); } else if (Scanner.curToken == whileToken) { s = WhileStatm.parse(); } else if (Scanner.curToken == semicolonToken) { s = EmptyStatm.parse(); } else { Error.expected("A statement"); } Log.leaveParser("</statement>"); return s; } } /* * An <call-statm>. */ class CallStatm extends Statement { // -- Must be changed in part 1+2: FunctionCall fc; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: fc.check(curDecls); } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: fc.genCode(curFunc); } static CallStatm parse() { // -- Must be changed in part 1: Log.enterParser("<call-statm>"); CallStatm cs = new CallStatm(); cs.fc = FunctionCall.parse(); Scanner.skip(semicolonToken); Log.leaveParser("</call-statm>"); return cs; } @Override void printTree() { // -- Must be changed in part 1: fc.printTree(); Log.wTreeLn(";"); } } /* * An <empty statm>. */ class EmptyStatm extends Statement { // -- Must be changed in part 1+2: @Override void check(DeclList curDecls) { // -- Must be changed in part 2: } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: } static EmptyStatm parse() { // -- Must be changed in part 1: EmptyStatm es = new EmptyStatm(); Log.enterParser("<empty-statm>"); Scanner.skip(semicolonToken); Log.leaveParser("</empty-statm>"); return es; } @Override void printTree() { // -- Must be changed in part 1: Log.wTreeLn(";"); } } /* * A <for-statm>. */ class ForStatm extends Statement { // -- Must be changed in part 1+2: ForControl control; StatmList statmlist; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: control.check(curDecls); statmlist.check(curDecls); } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: // Sender med statm list til forControl // Saa slipper man control.first.gencode(), naar // man kan heller bare skrive first.gencode :P control.statmlist = statmlist; control.genCode(curFunc); } static ForStatm parse() { // -- Must be changed in part 1: Log.enterParser("<for-statm>"); ForStatm fs = new ForStatm(); Scanner.skip(forToken); Scanner.skip(leftParToken); fs.control = ForControl.parse(); Scanner.skip(rightParToken); Scanner.skip(leftCurlToken); fs.statmlist = StatmList.parse(); //Scanner.skip(rightCurlToken); Log.leaveParser("</for-statm>"); return fs; } @Override void printTree() { // -- Must be changed in part 1: Log.wTree("for ("); control.printTree(); Log.wTreeLn(") {"); Log.indentTree(); statmlist.printTree(); Log.outdentTree(); Log.wTreeLn("}"); } } /* * a <for-control> */ class ForControl extends Statement { // -- Must be changed in part 1+2: Expression e; Assignment first, second; StatmList statmlist = null; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: first.check(curDecls); second.check(curDecls); e.check(curDecls); } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: String testLabel = Code.getLocalLabel(), endLabel = Code .getLocalLabel(); Code.genInstr("", "", "", "Start for-statement"); first.genCode(curFunc); Code.genInstr(testLabel, "", "", ""); e.genCode(curFunc); Code.genInstr("", "cmpl", "$0,%eax", ""); Code.genInstr("", "je", endLabel, ""); statmlist.genCode(curFunc); second.genCode(curFunc); Code.genInstr("", "jmp", testLabel, ""); Code.genInstr(endLabel, "", "", "End for-statement"); } static ForControl parse() { // -- Must be changed in part 1: ForControl fc = new ForControl(); // Usikker om dette trengs? Greit aa dobbeltsjekke kanskje? if(Scanner.curToken == nameToken || Scanner.curToken == starToken){ fc.first = Assignment.parse(); } Scanner.skip(semicolonToken); fc.e = Expression.parse(); Scanner.skip(semicolonToken); if(Scanner.curToken == nameToken || Scanner.curToken == starToken){ fc.second = Assignment.parse(); } return fc; } @Override void printTree() { // -- Must be changed in part 1: first.printTree(); Log.wTree(";"); e.printTree(); Log.wTree("}"); second.printTree(); } } /* * An <if-statm>. */ class IfStatm extends Statement { // -- Must be changed in part 1+2: Expression e; StatmList ifList; StatmList elseList; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: e.check(curDecls); ifList.check(curDecls); if(elseList != null){elseList.check(curDecls);} } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: String endLabel = Code.getLocalLabel(), elseLabel = ""; if(elseList != null){elseLabel = Code.getLocalLabel();} Code.genInstr("", "","", "Start if-statement"); e.genCode(curFunc); Code.genInstr("", "cmpl", "$0,%eax", ""); Code.genInstr("", "je", (elseList != null) ? elseLabel : endLabel, ""); ifList.genCode(curFunc); if(elseList != null){ Code.genInstr("", "jmp", endLabel, ""); Code.genInstr(elseLabel, "", "", " else-part"); elseList.genCode(curFunc); } Code.genInstr(endLabel, "", "", "End if-statement"); } static IfStatm parse() { // -- Must be changed in part 1: Log.enterParser("<if-statm>"); IfStatm is = new IfStatm(); Scanner.skip(ifToken); Scanner.skip(leftParToken); is.e = Expression.parse(); Scanner.skip(rightParToken); Scanner.skip(leftCurlToken); is.ifList = StatmList.parse(); //Scanner.skip(rightCurlToken); if(Scanner.curToken == Token.elseToken){ Log.enterParser("<else-part>"); Scanner.skip(elseToken); Scanner.skip(leftCurlToken); is.elseList = StatmList.parse(); //Scanner.skip(rightCurlToken); Log.leaveParser("</else-part>"); } Log.leaveParser("</if-statm>"); return is; } @Override void printTree() { // -- Must be changed in part 1: Log.wTree("if ("); e.printTree(); Log.wTreeLn(") {"); Log.indentTree(); ifList.printTree(); Log.wTreeLn("}"); Log.outdentTree(); if(elseList != null) { Log.wTreeLn("else {"); Log.indentTree(); elseList.printTree(); Log.wTreeLn(); Log.wTreeLn("}"); Log.outdentTree(); } } } /* * A <return-statm>. */ class ReturnStatm extends Statement{ // -- mUST BE CHANGED IN PART 1+2 Expression e; @Override void check(DeclList curDecls) { e.check(curDecls); // -- Must be changed in part 2: } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: System.out.println(""+curFunc.assemblerName); e.genCode(curFunc); Code.genInstr("", "jmp", ".exit$"+curFunc.name, "Return-statement"); } static ReturnStatm parse() { // -- Must be changed in part 1: Log.enterParser("<return-statm>"); ReturnStatm rs = new ReturnStatm(); Scanner.skip(returnToken); rs.e = Expression.parse(); Scanner.skip(semicolonToken); Log.leaveParser("</return-statm>"); return rs; } @Override void printTree() { // -- Must be changed in part 1: Log.wTree("return "); e.printTree(); Log.wTree(";"); } } /* * A <while-statm>. */ class WhileStatm extends Statement { Expression test; StatmList body; @Override void check(DeclList curDecls) { test.check(curDecls); body.check(curDecls); Log.noteTypeCheck("while (t) ...", test.type, "t", lineNum); if (test.type instanceof ValueType) { // OK } else { error("While-test must be a value."); } } @Override void genCode(FuncDecl curFunc) { String testLabel = Code.getLocalLabel(), endLabel = Code .getLocalLabel(); Code.genInstr(testLabel, "", "", "Start while-statement"); test.genCode(curFunc); Code.genInstr("", "cmpl", "$0,%eax", ""); Code.genInstr("", "je", endLabel, ""); body.genCode(curFunc); Code.genInstr("", "jmp", testLabel, ""); Code.genInstr(endLabel, "", "", "End while-statement"); } static WhileStatm parse() { Log.enterParser("<while-statm>"); WhileStatm ws = new WhileStatm(); Scanner.skip(whileToken); Scanner.skip(leftParToken); ws.test = Expression.parse(); Scanner.skip(rightParToken); Scanner.skip(leftCurlToken); ws.body = StatmList.parse(); //Scanner.skip(rightCurlToken); Log.leaveParser("</while-statm>"); return ws; } @Override void printTree() { Log.wTree("while ("); test.printTree(); Log.wTreeLn(") {"); Log.indentTree(); body.printTree(); Log.outdentTree(); Log.wTreeLn("}"); } } /* * An <Lhs-variable> */ class LhsVariable extends SyntaxUnit { int numStars = 0; Variable var; Type type; @Override void check(DeclList curDecls) { var.check(curDecls); type = var.type; for (int i = 1; i <= numStars; ++i) { Type e = type.getElemType(); if (e == null) error("Type error in left-hand side variable!"); type = e; } } @Override void genCode(FuncDecl curFunc) { var.genAddressCode(curFunc); for (int i = 1; i <= numStars; ++i) Code.genInstr("", "movl", "(%eax),%eax", " *"); } static LhsVariable parse() { Log.enterParser("<lhs-variable>"); LhsVariable lhs = new LhsVariable(); while (Scanner.curToken == starToken) { ++lhs.numStars; Scanner.skip(starToken); } Scanner.check(nameToken); lhs.var = Variable.parse(); Log.leaveParser("</lhs-variable>"); return lhs; } @Override void printTree() { for (int i = 1; i <= numStars; ++i) Log.wTree("*"); var.printTree(); } } /* * An <assign-statm> */ class AssignStatm extends Statement{ // -- mUST BE CHANGED IN PART 1+2 Assignment a; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: a.check(curDecls); } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: a.genCode(curFunc); } static AssignStatm parse() { // -- Must be changed in part 1: Log.enterParser("<assign-statm>"); AssignStatm as = new AssignStatm(); as.a = Assignment.parse(); Scanner.skip(semicolonToken); Log.leaveParser("</assign-statm>"); return as; } @Override void printTree() { // -- Must be changed in part 1: a.printTree(); Log.wTreeLn(";"); } } /* * An <assignment> */ class Assignment extends Statement{ // -- mUST BE CHANGED IN PART 1+2 Expression e; LhsVariable lhs; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: lhs.check(curDecls); e.check(curDecls); } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: lhs.genCode(curFunc); Code.genInstr("", "pushl", "%eax", ""); e.genCode(curFunc); Code.genInstr("", "popl", "%edx", ""); Code.genInstr("", "movl", "%eax,(%edx)", " ="); } static Assignment parse() { // -- Must be changed in part 1: Log.enterParser("<assignment>"); Assignment ass = new Assignment(); ass.lhs = LhsVariable.parse(); Scanner.skip(assignToken); ass.e = Expression.parse(); Log.leaveParser("</assignment>"); return ass; } @Override void printTree() { // -- Must be changed in part 1: lhs.printTree(); Log.wTree("="); e.printTree(); } } /* * An <expression list>. */ class ExprList extends SyntaxUnit { Expression firstExpr = null; static int length = 0; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: Expression e = firstExpr; while(e != null){ // sjekker alle exprs i exprlisten e.check(curDecls); e = e.nextExpr; } } @Override void genCode(FuncDecl curFunc) { //-- Must be changed in part 2: Expression curr = firstExpr; while(curr != null){ curr.genCodeRec(curFunc, 0); curr = curr.nextExpr; } /* if(firstExpr != null) { Expression curr = firstExpr; if(curr.nextExpr != null) { curr.nextExpr.genCode(curFunc); Code.genInstr("", "pushl", "%eax", "Push parameter #"+(++length)); curr = curr.nextExpr; } curr.genCode(curFunc); Code.genInstr("", "pushl", "%eax", "Push parameter #"+(++length)); }*/ } static ExprList parse() { Expression lastExpr = null; Log.enterParser("<expr list>"); // -- Must be changed in part 1: ExprList el = new ExprList(); length = 1; if(Scanner.curToken != rightParToken) { // makes sure the firstExpr is null if there's no expressions while (Scanner.curToken != rightParToken) { if (el.firstExpr == null) { el.firstExpr = Expression.parse(); } else { Expression prevExpr = el.firstExpr; while (prevExpr.nextExpr != null) { prevExpr = prevExpr.nextExpr; } length++; prevExpr.nextExpr = Expression.parse(); } if (Scanner.curToken != rightParToken) { Scanner.skip(commaToken); } } } else { el.firstExpr = null; } Scanner.skip(rightParToken); Log.leaveParser("</expr list>"); return el; } @Override void printTree() { // -- Must be changed in part 1: Expression currExpr = firstExpr; while(currExpr != null){ currExpr.printTree(); if(currExpr.nextExpr != null){ Log.wTree(", "); } currExpr = currExpr.nextExpr; } } // -- Must be changed in part 1: } /* * An <expression> */ class Expression extends SyntaxUnit { Expression nextExpr = null; Term firstTerm, secondTerm = null; Operator relOpr = null; Type type = null; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: firstTerm.check(curDecls); if(secondTerm == null) { type = firstTerm.type; } else{ secondTerm.check(curDecls); if(relOpr.oprToken == equalToken || relOpr.oprToken == notEqualToken){ if(firstTerm.type instanceof ValueType && secondTerm.type instanceof ValueType && (firstTerm.type.isSameType(secondTerm.type) || firstTerm.type == Types.intType || secondTerm.type == Types.intType)){ type = Types.intType; }else{ Error.error("Type of x was " + firstTerm.type + " and type for y was " + secondTerm.type + ". Both should have been intType"); } }else if(Token.isRelOperator(relOpr.oprToken)){ if(firstTerm.type == Types.intType && secondTerm.type == Types.intType){ type = Types.intType; }else{ Error.error("Expected both to be intTypes, x was " + firstTerm.type + " and y was " + secondTerm.type); } }else{ Error.error("Not a valid expression"); } } } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: // Assignment already redcued away pointer values, so we're left with the actual value firstTerm.genCode(curFunc); if(secondTerm != null){ Code.genInstr("", "pushl", "%eax", ""); // mellomlagrer first term paa stacken secondTerm.genCode(curFunc); // execute second term relOpr.genCode(curFunc); // naar denne kjores ligger term2 i eax og term1 paa toppen av stack } } void genCodeRec(FuncDecl curFunc, int paramN){ if(nextExpr == null){ genCode(curFunc); paramN++; Code.genInstr("", "pushl", "%eax", "Push parameter #"+paramN); return; } nextExpr.genCodeRec(curFunc, ++paramN); } static Expression parse() { Log.enterParser("<expression>"); Expression e = new Expression(); e.firstTerm = Term.parse(); if (Token.isRelOperator(Scanner.curToken)) { e.relOpr = RelOpr.parse(); e.secondTerm = Term.parse(); } Log.leaveParser("</expression>"); return e; } @Override void printTree() { // -- Must be changed in part 1: firstTerm.printTree(); if(relOpr != null){ relOpr.printTree(); } if(secondTerm != null){ secondTerm.printTree(); } } } /* * A <term> */ class Term extends SyntaxUnit { // -- Must be changed in part 1+2: Factor first; Term second; TermOpr termOpr; Type type; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: first.check(curDecls); if(second == null){ type = first.type; }else{ second.check(curDecls); if(first.type == Types.intType && second.type == Types.intType){ type = first.type; } else{ Error.error("Not declared as intType, was declared as " + first.type); } } } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: // if (first != null){ first.genCode(curFunc); // } //second.genCode(curFunc); if(second != null) { Code.genInstr("", "pushl", "%eax", ""); // mellomlagrer paa stacken second.genCode(curFunc); termOpr.genCode(curFunc); } } static Term parse() { // -- Must be changed in part 1: Log.enterParser("<term>"); Term t = new Term(); t.first = Factor.parse(); if(Token.isTermOperator(Scanner.curToken)) { t.termOpr = TermOpr.parse(); t.second = Term.parse(); } Log.leaveParser("</term>"); return t; } @Override void printTree() { // -- Must be changed in part 1: first.printTree(); if(termOpr != null){ termOpr.printTree(); } if(second != null){ second.printTree(); } } } /* * A <factor> */ class Factor extends SyntaxUnit { // -- Must be changed in part 1+2: FactorOpr factorOpr; Primary first; Factor second; Type type; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: first.check(curDecls); if(second == null){ type = first.type; }else{ second.check(curDecls); if(first.type == Types.intType && second.type == Types.intType){ type = Types.intType; }else{ Error.error("Not declared as intType, was declared as " + first.type); } } } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: first.genCode(curFunc); if(second != null) { Code.genInstr("", "pushl", "%eax", ""); // mellomlagrer first paa stacken second.genCode(curFunc); factorOpr.genCode(curFunc); } } static Factor parse() { // -- Must be changed in part 1: Log.enterParser("<factor>"); Factor f = new Factor(); f.first = Primary.parse(); if(Token.isFactorOperator(Scanner.curToken)){ f.factorOpr = FactorOpr.parse(); f.second = Factor.parse(); } Log.leaveParser("</factor>"); return f; } @Override void printTree() { // -- Must be changed in part 1: first.printTree(); if(factorOpr != null){ factorOpr.printTree(); } if(second != null){ second.printTree(); } } } /* * A <primary> */ class Primary extends SyntaxUnit { // -- Must be changed in part 1+2: Operand first; PrefixOpr prefix; Type type; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: first.check(curDecls); if(prefix == null){ // System.out.println("hei1"); type = first.type; } else if(prefix.oprToken == starToken){ if(first.type instanceof PointerType) type = first.type.getElemType(); else{ Error.error("Expected pointerType, got " + first.type); } }else if(prefix.oprToken == subtractToken){ if(first.type == Types.intType){ type = Types.intType; }else{ Error.error("Expected intType, got " + first.type); } } } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: first.genCode(curFunc); System.out.println(first.lineNum + " " + first); if(prefix != null) { Code.genInstr("", "pushl", "%eax", ""); prefix.genCode(curFunc); } } static Primary parse() { // -- Must be changed in part 1: Log.enterParser("<primary>"); Primary p = new Primary(); // System.out.println(Scanner.curToken); if(Token.isPrefixOperator(Scanner.curToken)){ p.prefix = PrefixOpr.parse(); } p.first = Operand.parse(); // System.out.println(p.first.lineNum +""); Log.leaveParser("</primary>"); return p; } @Override void printTree() { // -- Must be changed in part 1: if(prefix != null){ prefix.printTree(); } first.printTree(); } } /* * An <operator> */ abstract class Operator extends SyntaxUnit { Operator nextOpr = null; Token oprToken; @Override void check(DeclList curDecls) { } // Never needed. } /* * A <term opr> (+ or -) */ class TermOpr extends Operator{ @Override void genCode(FuncDecl curFunc){ // PART 2 Code.genInstr("", "movl", "%eax,%ecx", ""); Code.genInstr("", "popl", "%eax", ""); if(oprToken == addToken) {Code.genInstr("", "addl", "%ecx,%eax", "Compute + ");} else if(oprToken == subtractToken){Code.genInstr("", "subl", "%ecx,%eax", "Compute -");} } static TermOpr parse(){ // PART 1 Log.enterParser("<term opr>"); TermOpr to = new TermOpr(); to.oprToken = Scanner.curToken; Scanner.readNext(); Log.leaveParser("</term opr>"); return to; } @Override void printTree(){ // MUST BE CHANGED IN PART 1 if(oprToken == addToken){Log.wTree(" + ");} else if(oprToken == subtractToken){Log.wTree(" - ");} } } /* * A <factor opr> (* or /) */ class FactorOpr extends Operator{ @Override void genCode(FuncDecl curFunc){ // PART 2 Code.genInstr("", "movl", "%eax,%ecx", ""); Code.genInstr("", "popl", "%eax", ""); if(oprToken == divideToken){ Code.genInstr("", "cdq", "", ""); Code.genInstr("", "idivl", "%ecx", "Compute / "); } else if(oprToken == starToken){Code.genInstr("", "imull", "%ecx,%eax", "Compute * ");} } static FactorOpr parse(){ // PART 1 Log.enterParser("<factor opr>"); FactorOpr fo = new FactorOpr(); fo.oprToken = Scanner.curToken; Scanner.readNext(); Log.leaveParser("</factor opr>"); return fo; } @Override void printTree(){ // MUST BE CHANGED IN PART 1 if(oprToken == starToken){Log.wTree(" * ");} else if(oprToken == divideToken){Log.wTree(" / ");} } } /* * A <prefix opr> (- or *) */ class PrefixOpr extends Operator{ @Override void genCode(FuncDecl curFunc){ // PART 2 if(oprToken == subtractToken){Code.genInstr("", "negl", "%eax", " negative nr");} else if(oprToken == starToken){Code.genInstr("", "movl", "(%eax),%eax", "peker");} } static PrefixOpr parse(){ // PART 1 Log.enterParser("<prefix opr>"); PrefixOpr po = new PrefixOpr(); po.oprToken = Scanner.curToken; Scanner.readNext(); Log.leaveParser("</prefix opr>"); return po; } @Override void printTree(){ // MUST BE CHANGED IN PART 1 if(oprToken == subtractToken){Log.wTree("-");} else if(oprToken == starToken){Log.wTree("*");} } } /* * A <rel opr> (==, !=, <, <=, > or >=). */ class RelOpr extends Operator { @Override void genCode(FuncDecl curFunc) { Code.genInstr("", "popl", "%ecx", ""); Code.genInstr("", "cmpl", "%eax,%ecx", ""); Code.genInstr("", "movl", "$0,%eax", ""); switch (oprToken) { case equalToken: Code.genInstr("", "sete", "%al", "Test =="); break; case notEqualToken: Code.genInstr("", "setne", "%al", "Test !="); break; case lessToken: Code.genInstr("", "setl", "%al", "Test <"); break; case lessEqualToken: Code.genInstr("", "setle", "%al", "Test <="); break; case greaterToken: Code.genInstr("", "setg", "%al", "Test >"); break; case greaterEqualToken: Code.genInstr("", "setge", "%al", "Test >="); break; } } static RelOpr parse() { Log.enterParser("<rel opr>"); RelOpr ro = new RelOpr(); ro.oprToken = Scanner.curToken; Scanner.readNext(); Log.leaveParser("</rel opr>"); return ro; } @Override void printTree() { String op = "?"; switch (oprToken) { case equalToken: op = "=="; break; case notEqualToken: op = "!="; break; case lessToken: op = "<"; break; case lessEqualToken: op = "<="; break; case greaterToken: op = ">"; break; case greaterEqualToken: op = ">="; break; } Log.wTree(" " + op + " "); } } /* * An <operand> */ abstract class Operand extends SyntaxUnit { Operand nextOperand = null; Type type; static Operand parse() { Log.enterParser("<operand>"); Operand o = null; if (Scanner.curToken == numberToken) { o = Number.parse(); } else if (Scanner.curToken == nameToken && Scanner.nextToken == leftParToken) { o = FunctionCall.parse(); } else if (Scanner.curToken == nameToken) { o = Variable.parse(); } else if (Scanner.curToken == ampToken) { o = Address.parse(); } else if (Scanner.curToken == leftParToken) { o = InnerExpr.parse(); } else { Error.expected("An operand"); } Log.leaveParser("</operand>"); return o; } } /* * A <function call>. */ class FunctionCall extends Operand { // -- Must be changed in part 1+2: String funcName; ExprList el; FuncDecl declRef = null; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: if(el == null){ Error.error("ExprList is null"); } Declaration d = curDecls.findDecl(funcName, this); Log.noteBinding(funcName, lineNum, d.lineNum); //d.checkWhetherFunction(el.length, this); type = d.type; declRef = (FuncDecl) d; //Check params el.check(curDecls); // check func Declaration declTmp = declRef.funcParams.firstDecl; Expression callTmp = el.firstExpr; while(declTmp != null && callTmp != null){ if(declTmp == null || callTmp == null){ Error.error("FunctionDecl and callDecl parameterlist are not equal length"); } //if(!declTmp.type.isSameType(callTmp.type) || !callTmp.type.isSameType(Types.intType)) { // Error.error("Function call parameter type not equal to function declaration type or int is " + callTmp.type + " " +callTmp.lineNum); //} declTmp = declTmp.nextDecl; callTmp = callTmp.nextExpr; } } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: el.genCode(curFunc); el.length = 0; FuncDecl f = declRef; Code.genInstr("", "call", f.assemblerName, "Call "+f.name); if(f.funcParams.dataSize()>0){ Code.genInstr("", "addl", "$"+f.funcParams.dataSize()+",%esp", "Remove parameters"); } } static FunctionCall parse() { // -- Must be changed in part 1: Log.enterParser("<function call>"); FunctionCall fc = new FunctionCall(); fc.funcName = Scanner.curName; Scanner.skip(nameToken); Scanner.skip(leftParToken); fc.el = ExprList.parse(); Log.leaveParser("</function call>"); return fc; } @Override void printTree() { // -- Must be changed in part 1: Log.wTree(funcName); Log.wTree("("); el.printTree(); Log.wTree(")"); } // -- Must be changed in part 1+2: } /* * A <number>. */ class Number extends Operand { int numVal; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: type = Types.intType; } @Override void genCode(FuncDecl curFunc) { Code.genInstr("", "movl", "$" + numVal + ",%eax","" + numVal); } static Number parse() { // -- Must be changed in part 1: Log.enterParser("<number>"); Number n = new Number(); n.numVal = Scanner.curNum; Scanner.skip(numberToken); Log.leaveParser("</number>"); return n; } @Override void printTree() { Log.wTree("" + numVal); } } /* * A <variable>. */ class Variable extends Operand { String varName; VarDecl declRef = null; Expression index = null; @Override void check(DeclList curDecls) { Declaration d = curDecls.findDecl(varName, this); Log.noteBinding(varName, lineNum, d.lineNum); d.checkWhetherVariable(this); declRef = (VarDecl) d; if (index == null) { type = d.type; } else { index.check(curDecls); Log.noteTypeCheck("a[e]", d.type, "a", index.type, "e", lineNum); if (index.type == Types.intType) { // OK } else { error("Only integers may be used as index."); } if (d.type.mayBeIndexed()) { // OK } else { error("Only arrays and pointers may be indexed."); } type = d.type.getElemType(); } } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: if (index == null) { System.out.println(varName + " " + declRef.name + " " + declRef.assemblerName); Code.genInstr("", "movl", declRef.assemblerName + ",%eax", varName); } else { index.genCode(curFunc); if (declRef.type instanceof ArrayType) { Code.genInstr("", "leal", declRef.assemblerName + ",%edx", varName + "[...]"); } else { Code.genInstr("", "movl", declRef.assemblerName + ",%edx", varName + "[...]"); } Code.genInstr("", "movl", "(%edx, %eax, 4), %eax", ""); } } void genAddressCode(FuncDecl curFunc) { // Generate code to load the _address_ of the variable // rather than its value. if (index == null) { Code.genInstr("", "leal", declRef.assemblerName + ",%eax", varName); } else { index.genCode(curFunc); if (declRef.type instanceof ArrayType) { Code.genInstr("", "leal", declRef.assemblerName + ",%edx", varName + "[...]"); } else { Code.genInstr("", "movl", declRef.assemblerName + ",%edx", varName + "[...]"); } Code.genInstr("", "leal", "(%edx,%eax,4),%eax", ""); } } static Variable parse() { Log.enterParser("<variable>"); // -- Must be changed in part 1: Variable v = new Variable(); v.varName = Scanner.curName; Scanner.skip(nameToken); if(Scanner.curToken == leftBracketToken){ Scanner.skip(leftBracketToken); v.index = Expression.parse(); Scanner.skip(rightBracketToken); } Log.leaveParser("</variable>"); return v; } @Override void printTree() { // -- Must be changed in part 1: Log.wTree(varName); if(index != null){ Log.wTree("["); index.printTree(); Log.wTree("]"); } } } /* * An <address>. */ class Address extends Operand { Variable var; @Override void check(DeclList curDecls) { var.check(curDecls); type = new PointerType(var.type); } @Override void genCode(FuncDecl curFunc) { var.genAddressCode(curFunc); } static Address parse() { Log.enterParser("<address>"); Address a = new Address(); Scanner.skip(ampToken); a.var = Variable.parse(); Log.leaveParser("</address>"); return a; } @Override void printTree() { Log.wTree("&"); var.printTree(); } } /* * An <inner expr>. */ class InnerExpr extends Operand { Expression expr; @Override void check(DeclList curDecls) { expr.check(curDecls); type = expr.type; } @Override void genCode(FuncDecl curFunc) { expr.genCode(curFunc); } static InnerExpr parse() { Log.enterParser("<inner expr>"); InnerExpr ie = new InnerExpr(); Scanner.skip(leftParToken); ie.expr = Expression.parse(); Scanner.skip(rightParToken); Log.leaveParser("</inner expr>"); return ie; } @Override void printTree() { Log.wTree("("); expr.printTree(); Log.wTree(")"); } }
alboc/no/uio/ifi/alboc/syntax/Syntax.java
package no.uio.ifi.alboc.syntax; /* * module Syntax */ import no.uio.ifi.alboc.alboc.AlboC; import no.uio.ifi.alboc.code.Code; import no.uio.ifi.alboc.error.Error; import no.uio.ifi.alboc.log.Log; import no.uio.ifi.alboc.scanner.Scanner; import no.uio.ifi.alboc.scanner.Token; import static no.uio.ifi.alboc.scanner.Token.*; import no.uio.ifi.alboc.types.*; /* * Creates a syntax tree by parsing an AlboC program; * prints the parse tree (if requested); * checks it; * generates executable code. */ public class Syntax { static DeclList library; static Program program; public static void init() { // -- Must be changed in part 1+2: library = new GlobalDeclList(); library.addDecl(new FuncDecl("exit", Types.intType, "status")); library.addDecl(new FuncDecl("getchar", Types.intType, null)); library.addDecl(new FuncDecl("getint", Types.intType, null)); library.addDecl(new FuncDecl("putchar", Types.intType, "c")); library.addDecl(new FuncDecl("putint", Types.intType, "c")); Scanner.readNext(); Scanner.readNext(); } public static void finish() { // -- Must be changed in part 1+2: } public static void checkProgram() { program.check(library); } public static void genCode() { program.genCode(null); } public static void parseProgram() { program = Program.parse(); } public static void printProgram() { program.printTree(); } } /* * Super class for all syntactic units. (This class is not mentioned in the * syntax diagrams.) */ abstract class SyntaxUnit { int lineNum; SyntaxUnit() { lineNum = Scanner.curLine; } abstract void check(DeclList curDecls); abstract void genCode(FuncDecl curFunc); abstract void printTree(); void error(String message) { Error.error(lineNum, message); } } /* * A <program> */ class Program extends SyntaxUnit { DeclList progDecls; @Override void check(DeclList curDecls) { progDecls.check(curDecls); if (!AlboC.noLink) { // Check that 'main' has been declared properly: // -- Must be changed in part 2: FuncDecl main; Declaration d = progDecls.findDecl("main", null); Log.noteBinding("main", 0, d.lineNum); main = (FuncDecl) d; if(main.type != Types.intType) error("'main' should return type 'int'"); } } @Override void genCode(FuncDecl curFunc) { progDecls.genCode(null); } static Program parse() { Log.enterParser("<program>"); Program p = new Program(); p.progDecls = GlobalDeclList.parse(); if (Scanner.curToken != eofToken) { Error.expected("A declaration"); } //System.out.println(Log.ut + " what " + Log.inn); Log.leaveParser("</program>"); return p; } @Override void printTree() { progDecls.printTree(); } } /* * A declaration list. (This class is not mentioned in the syntax diagrams.) */ abstract class DeclList extends SyntaxUnit { Declaration firstDecl = null; DeclList outerScope; DeclList() { // -- Must be changed in part 1: } @Override void check(DeclList curDecls) { outerScope = curDecls; Declaration dx = firstDecl; while (dx != null) { dx.check(this); dx = dx.nextDecl; } } @Override void printTree() { // -- Must be changed in part 1: Declaration currDecl = firstDecl; while(currDecl != null){ currDecl.printTree(); currDecl = currDecl.nextDecl; } } // Lager FIFO liste void addDecl(Declaration d) { // -- Must be changed in part 1: if(firstDecl == null){ firstDecl = d; } else{ Declaration prevDecl = firstDecl; while(prevDecl.nextDecl != null){ if(prevDecl.name.equals(d.name)) d.error("name " + d.name + " already declared"); prevDecl = prevDecl.nextDecl; } if(prevDecl.name.equals(d.name)) d.error("name " + d.name + " already declared"); prevDecl.nextDecl = d; } } int dataSize() { Declaration dx = firstDecl; int res = 0; while (dx != null) { res += dx.declSize(); dx = dx.nextDecl; } return res; } Declaration findDecl(String name, SyntaxUnit use) { // -- Must be changed in part 2: Declaration dx = firstDecl; while(dx != null){ if(dx.name.equals(name)){ return dx; } dx = dx.nextDecl; } if(outerScope != null){ return outerScope.findDecl(name, use); } Error.error("name " + name + " is unknown"); return null; } } /* * A list of global declarations. (This class is not mentioned in the syntax * diagrams.) */ class GlobalDeclList extends DeclList { @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: Declaration gdl = firstDecl; while(gdl != null){ gdl.genCode(curFunc); gdl = gdl.nextDecl; } } static GlobalDeclList parse() { GlobalDeclList gdl = new GlobalDeclList(); while (Scanner.curToken == intToken) { DeclType ts = DeclType.parse(); gdl.addDecl(Declaration.parse(ts)); } return gdl; } } /* * A list of local declarations. (This class is not mentioned in the syntax * diagrams.) */ class LocalDeclList extends DeclList { @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: if(firstDecl != null) { // Declaration ldl = firstDecl; // while(ldl != null){ // ldl.genCode(curFunc); // ldl = ldl.nextDecl; // } Declaration ldl = firstDecl; if(ldl.nextDecl != null) { ldl.nextDecl.genCode(curFunc); } ldl.genCode(curFunc); } } static LocalDeclList parse() { // -- Must be changed in part 1: LocalDeclList ldl = new LocalDeclList(); while(Scanner.curToken == intToken){ DeclType ts = DeclType.parse(); ldl.addDecl(LocalVarDecl.parse(ts)); } return ldl; } } /* * A list of parameter declarations. (This class is not mentioned in the syntax * diagrams.) */ class ParamDeclList extends DeclList { static int length = 0; @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2:' if(firstDecl != null) { Declaration pdl = firstDecl; if(pdl.nextDecl != null) { pdl.nextDecl.genCode(curFunc); } pdl.genCode(curFunc); } // Declaration pdl = firstDecl; // while(pdl != null){ // pdl.genCode(curFunc); // pdl = pdl.nextDecl; // } } static ParamDeclList parse() { // -- Must be changed in part 1: ParamDeclList pdl = new ParamDeclList(); while(Scanner.curToken == intToken){ DeclType ts = DeclType.parse(); pdl.addDecl(ParamDecl.parse(ts)); length++; } return pdl; } @Override void printTree() { Declaration px = firstDecl; while (px != null) { px.printTree(); px = px.nextDecl; if (px != null) Log.wTree(", "); } } } /* * A <type> */ class DeclType extends SyntaxUnit { int numStars = 0; Type type; @Override void check(DeclList curDecls) { type = Types.intType; for (int i = 1; i <= numStars; ++i) type = new PointerType(type); } @Override void genCode(FuncDecl curFunc) { } static DeclType parse() { Log.enterParser("<type>"); DeclType dt = new DeclType(); Scanner.skip(intToken); while (Scanner.curToken == starToken) { ++dt.numStars; Scanner.readNext(); } Log.leaveParser("</type>"); return dt; } @Override void printTree() { Log.wTree("int"); for (int i = 1; i <= numStars; ++i) Log.wTree("*"); } } /* * Any kind of declaration. */ abstract class Declaration extends SyntaxUnit { String name, assemblerName; DeclType typeSpec; Type type; boolean visible = false; Declaration nextDecl = null; int offset = 0; Declaration(String n) { name = n; } abstract int declSize(); static Declaration parse(DeclType dt) { Declaration d = null; if (Scanner.curToken == nameToken && Scanner.nextToken == leftParToken) { d = FuncDecl.parse(dt); } else if (Scanner.curToken == nameToken) { d = GlobalVarDecl.parse(dt); } else { Error.expected("A declaration name"); } d.typeSpec = dt; return d; } /** * checkWhetherVariable: Utility method to check whether this Declaration is * really a variable. The compiler must check that a name is used properly; * for instance, using a variable name a in "a()" is illegal. This is * handled in the following way: * <ul> * <li>When a name a is found in a setting which implies that should be a * variable, the parser will first search for a's declaration d. * <li>The parser will call d.checkWhetherVariable(this). * <li>Every sub-class of Declaration will implement a checkWhetherVariable. * If the declaration is indeed a variable, checkWhetherVariable will do * nothing, but if it is not, the method will give an error message. * </ul> * Examples * <dl> * <dt>GlobalVarDecl.checkWhetherVariable(...)</dt> * <dd>will do nothing, as everything is all right.</dd> * <dt>FuncDecl.checkWhetherVariable(...)</dt> * <dd>will give an error message.</dd> * </dl> */ abstract void checkWhetherVariable(SyntaxUnit use); /** * checkWhetherFunction: Utility method to check whether this Declaration is * really a function. * * @param nParamsUsed * Number of parameters used in the actual call. (The method will * give an error message if the function was used with too many * or too few parameters.) * @param use * From where is the check performed? * @see //checkWhetherVariable */ abstract void checkWhetherFunction(int nParamsUsed, SyntaxUnit use); } /* * A <var decl> */ abstract class VarDecl extends Declaration { boolean isArray = false; int numElems = 0; VarDecl(String n) { super(n); } @Override void check(DeclList curDecls) { // -- Must be changed in part 2: visible = true; typeSpec.check(curDecls); if(isArray){ type = new ArrayType(typeSpec.type, numElems); }else { type = typeSpec.type; } } @Override void printTree() { typeSpec.printTree(); Log.wTree(" " + name); Log.wTreeLn(";"); } @Override int declSize() { return type.size(); } @Override void checkWhetherFunction(int nParamsUsed, SyntaxUnit use) { use.error(name + " is a variable and no function!"); } @Override void checkWhetherVariable(SyntaxUnit use) { // OK } } /* * A global <var decl>. */ class GlobalVarDecl extends VarDecl { GlobalVarDecl(String n) { super(n); assemblerName = (AlboC.underscoredGlobals() ? "_" : "") + n; } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: // set offset if(isArray){ Code.genVar(assemblerName, true, numElems, type.size()/numElems, type + " " + name); } else{ Code.genVar(assemblerName, true, 1, type.size(), type + " " + name); } } static GlobalVarDecl parse(DeclType dt) { Log.enterParser("<var decl>"); // -- Must be changed in part 1: GlobalVarDecl gv = new GlobalVarDecl(Scanner.curName); gv.typeSpec = dt; Scanner.skip(nameToken); if(Scanner.curToken == leftBracketToken) { // we found an array. gv.isArray = true; Scanner.skip(leftBracketToken); // skip this leftbracket gv.numElems = Scanner.curNum; Scanner.skip(numberToken); // skip the array size Scanner.skip(rightBracketToken); // skip the next right bracket token } Scanner.skip(semicolonToken); Log.leaveParser("</var decl>"); return gv; } } /* * A local variable declaration */ class LocalVarDecl extends VarDecl { LocalVarDecl(String n) { super(n); } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: assemblerName = "-"+curFunc.localOffset+"(%ebp)"; curFunc.localOffset -= 4; } static LocalVarDecl parse(DeclType dt) { Log.enterParser("<var decl>"); LocalVarDecl vv = new LocalVarDecl(Scanner.curName); vv.typeSpec = dt; Scanner.skip(nameToken); if(Scanner.curToken == leftBracketToken){ vv.isArray = true; Scanner.skip(leftBracketToken); vv.numElems = Scanner.curNum; Scanner.skip(numberToken); // skip the array size Scanner.skip(rightBracketToken); // skip the next right bracket token } Scanner.skip(semicolonToken); Log.leaveParser("</var decl>"); // -- Must be changed in part 1: return vv; } } /* * A <param decl> */ class ParamDecl extends VarDecl { ParamDecl(String n) { super(n); } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: curFunc.paramOffset -= 4; assemblerName = curFunc.paramOffset+"(%ebp)"; } static ParamDecl parse(DeclType dt) { Log.enterParser("<param decl>"); // -- Must be changed in part 1: ParamDecl pd = new ParamDecl(Scanner.curName); pd.typeSpec = dt; Scanner.skip(nameToken); if(Scanner.curToken == commaToken){ Scanner.skip(commaToken); } Log.leaveParser("</param decl>"); return pd; } @Override void printTree() { typeSpec.printTree(); Log.wTree(" " + name); } } /* * A <func decl> */ class FuncDecl extends Declaration { ParamDeclList funcParams; LocalDeclList funcVars; StatmList funcBody; String exitLabel; int paramOffset = 8; int localOffset = 0; FuncDecl(String n) { // Used for user functions: super(n); assemblerName = (AlboC.underscoredGlobals() ? "_" : "") + n; // -- Must be changed in part 1: } FuncDecl(String n, Type rt, String t){ super(n); assemblerName = (AlboC.underscoredGlobals() ? "_" : "") + n; this.type = rt; funcParams = new ParamDeclList(); if(t != null){ ParamDecl p = new ParamDecl(t); funcParams.addDecl(p); funcParams.firstDecl.type = Types.intType; } } @Override int declSize() { return 0; } @Override void check(DeclList curDecls) { // -- Must be changed in part 2: visible = true; typeSpec.check(curDecls); type = typeSpec.type; if(funcParams != null) { funcParams.check(curDecls); funcVars.check(funcParams); } else{ funcVars.check(curDecls); } funcBody.check(funcVars); } @Override void checkWhetherFunction(int nParamsUsed, SyntaxUnit use) { // -- Must be changed in part 2: if(funcParams != null && funcParams.length != nParamsUsed){ Error.error("FUCK THIS"); } } @Override void checkWhetherVariable(SyntaxUnit use) { // -- Must be changed in part 2: use.error(name + " is a function and no variable!"); } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: Code.genInstr("", ".globl", assemblerName, ""); Code.genInstr(assemblerName, "enter", "$"+funcVars.dataSize()+",$0", "Start function " + name); if(funcParams != null){ paramOffset += funcParams.dataSize(); funcParams.genCode(this); } localOffset += funcVars.dataSize(); funcVars.genCode(this); funcBody.genCode(this); Code.genInstr(".exit$"+name,"","",""); Code.genInstr("","leave","",""); Code.genInstr("","ret","","End function " + name); } static FuncDecl parse(DeclType ts) { // -- Must be changed in part 1: /* What to do: first parse ParamDecList and save to funcParams. next we need to parse a local declaration list then we need some sort of function body, which would be a statmList i guess. then we return the object. */ Log.enterParser("<func decl>"); FuncDecl fd = new FuncDecl(Scanner.curName); // start with creating a new object fd.typeSpec = ts; Scanner.skip(nameToken); Scanner.skip(leftParToken); fd.funcParams = ParamDeclList.parse(); Scanner.skip(rightParToken); Log.enterParser("<func body>"); Scanner.skip(leftCurlToken); fd.funcVars = LocalDeclList.parse(); fd.funcBody = StatmList.parse(); Log.leaveParser("</func body>"); Log.leaveParser("</func delc>"); return fd; } @Override void printTree() { // -- Must be changed in part 1: typeSpec.printTree(); Log.wTree(" " +name); Log.wTree("("); funcParams.printTree(); Log.wTree(")"); Log.wTreeLn("{"); Log.indentTree(); funcVars.printTree(); funcBody.printTree(); Log.wTreeLn(); Log.outdentTree(); Log.wTreeLn("}"); } } /* * A <statm list>. */ class StatmList extends SyntaxUnit { // -- Must be changed in part 1: Statement first = null; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: if(first != null){ Statement s = first; s.check(curDecls); while(s.nextStatm != null){ // sjekker alle statements i lista s = s.nextStatm; s.check(curDecls); } } } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: if(first != null){ Statement s = first; s.genCode(curFunc); while(s.nextStatm != null){ s = s.nextStatm; s.genCode(curFunc); } } } static StatmList parse() { Log.enterParser("<statm list>"); StatmList sl = new StatmList(); while (Scanner.curToken != rightCurlToken) { // -- Must be changed in part 1: if(sl.first == null){ sl.first = Statement.parse(); } else{ Statement lastStatm = null; lastStatm = sl.first; while(lastStatm.nextStatm != null){ lastStatm = lastStatm.nextStatm; } lastStatm.nextStatm = Statement.parse(); } } Scanner.skip(rightCurlToken); Log.leaveParser("</statm list>"); return sl; } @Override void printTree() { // -- Must be changed in part 1: Statement currStatm = first; while(currStatm != null){ currStatm.printTree(); currStatm = currStatm.nextStatm; } } } /* * A <statement>. */ abstract class Statement extends SyntaxUnit { Statement nextStatm = null; static Statement parse() { Log.enterParser("<statement>"); Statement s = null; if (Scanner.curToken == nameToken && Scanner.nextToken == leftParToken) { // -- Must be changed in part 1: s = CallStatm.parse(); } else if (Scanner.curToken == nameToken || Scanner.curToken == starToken) { // -- Must be changed in part 1: s = AssignStatm.parse(); } else if (Scanner.curToken == forToken) { // -- Must be changed in part 1: s = ForStatm.parse(); } else if (Scanner.curToken == ifToken) { s = IfStatm.parse(); } else if (Scanner.curToken == returnToken) { // -- Must be changed in part 1: s = ReturnStatm.parse(); } else if (Scanner.curToken == whileToken) { s = WhileStatm.parse(); } else if (Scanner.curToken == semicolonToken) { s = EmptyStatm.parse(); } else { Error.expected("A statement"); } Log.leaveParser("</statement>"); return s; } } /* * An <call-statm>. */ class CallStatm extends Statement { // -- Must be changed in part 1+2: FunctionCall fc; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: fc.check(curDecls); } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: fc.genCode(curFunc); } static CallStatm parse() { // -- Must be changed in part 1: Log.enterParser("<call-statm>"); CallStatm cs = new CallStatm(); cs.fc = FunctionCall.parse(); Scanner.skip(semicolonToken); Log.leaveParser("</call-statm>"); return cs; } @Override void printTree() { // -- Must be changed in part 1: fc.printTree(); Log.wTreeLn(";"); } } /* * An <empty statm>. */ class EmptyStatm extends Statement { // -- Must be changed in part 1+2: @Override void check(DeclList curDecls) { // -- Must be changed in part 2: } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: } static EmptyStatm parse() { // -- Must be changed in part 1: EmptyStatm es = new EmptyStatm(); Log.enterParser("<empty-statm>"); Scanner.skip(semicolonToken); Log.leaveParser("</empty-statm>"); return es; } @Override void printTree() { // -- Must be changed in part 1: Log.wTreeLn(";"); } } /* * A <for-statm>. */ class ForStatm extends Statement { // -- Must be changed in part 1+2: ForControl control; StatmList statmlist; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: control.check(curDecls); statmlist.check(curDecls); } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: // Sender med statm list til forControl // Saa slipper man control.first.gencode(), naar // man kan heller bare skrive first.gencode :P control.statmlist = statmlist; control.genCode(curFunc); } static ForStatm parse() { // -- Must be changed in part 1: Log.enterParser("<for-statm>"); ForStatm fs = new ForStatm(); Scanner.skip(forToken); Scanner.skip(leftParToken); fs.control = ForControl.parse(); Scanner.skip(rightParToken); Scanner.skip(leftCurlToken); fs.statmlist = StatmList.parse(); //Scanner.skip(rightCurlToken); Log.leaveParser("</for-statm>"); return fs; } @Override void printTree() { // -- Must be changed in part 1: Log.wTree("for ("); control.printTree(); Log.wTreeLn(") {"); Log.indentTree(); statmlist.printTree(); Log.outdentTree(); Log.wTreeLn("}"); } } /* * a <for-control> */ class ForControl extends Statement { // -- Must be changed in part 1+2: Expression e; Assignment first, second; StatmList statmlist = null; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: first.check(curDecls); second.check(curDecls); e.check(curDecls); } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: String testLabel = Code.getLocalLabel(), endLabel = Code .getLocalLabel(); Code.genInstr("", "", "", "Start for-statement"); first.genCode(curFunc); Code.genInstr(testLabel, "", "", ""); e.genCode(curFunc); Code.genInstr("", "cmpl", "$0,%eax", ""); Code.genInstr("", "je", endLabel, ""); statmlist.genCode(curFunc); second.genCode(curFunc); Code.genInstr("", "jmp", testLabel, ""); Code.genInstr(endLabel, "", "", "End for-statement"); } static ForControl parse() { // -- Must be changed in part 1: ForControl fc = new ForControl(); // Usikker om dette trengs? Greit aa dobbeltsjekke kanskje? if(Scanner.curToken == nameToken || Scanner.curToken == starToken){ fc.first = Assignment.parse(); } Scanner.skip(semicolonToken); fc.e = Expression.parse(); Scanner.skip(semicolonToken); if(Scanner.curToken == nameToken || Scanner.curToken == starToken){ fc.second = Assignment.parse(); } return fc; } @Override void printTree() { // -- Must be changed in part 1: first.printTree(); Log.wTree(";"); e.printTree(); Log.wTree("}"); second.printTree(); } } /* * An <if-statm>. */ class IfStatm extends Statement { // -- Must be changed in part 1+2: Expression e; StatmList ifList; StatmList elseList; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: e.check(curDecls); ifList.check(curDecls); if(elseList != null){elseList.check(curDecls);} } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: String endLabel = Code.getLocalLabel(), elseLabel = ""; if(elseList != null){elseLabel = Code.getLocalLabel();} Code.genInstr("", "","", "Start if-statement"); e.genCode(curFunc); Code.genInstr("", "cmpl", "$0,%eax", ""); Code.genInstr("", "je", (elseList != null) ? elseLabel : endLabel, ""); ifList.genCode(curFunc); if(elseList != null){ Code.genInstr("", "jmp", endLabel, ""); Code.genInstr(elseLabel, "", "", " else-part"); elseList.genCode(curFunc); } Code.genInstr(endLabel, "", "", "End if-statement"); } static IfStatm parse() { // -- Must be changed in part 1: Log.enterParser("<if-statm>"); IfStatm is = new IfStatm(); Scanner.skip(ifToken); Scanner.skip(leftParToken); is.e = Expression.parse(); Scanner.skip(rightParToken); Scanner.skip(leftCurlToken); is.ifList = StatmList.parse(); //Scanner.skip(rightCurlToken); if(Scanner.curToken == Token.elseToken){ Log.enterParser("<else-part>"); Scanner.skip(elseToken); Scanner.skip(leftCurlToken); is.elseList = StatmList.parse(); //Scanner.skip(rightCurlToken); Log.leaveParser("</else-part>"); } Log.leaveParser("</if-statm>"); return is; } @Override void printTree() { // -- Must be changed in part 1: Log.wTree("if ("); e.printTree(); Log.wTreeLn(") {"); Log.indentTree(); ifList.printTree(); Log.wTreeLn("}"); Log.outdentTree(); if(elseList != null) { Log.wTreeLn("else {"); Log.indentTree(); elseList.printTree(); Log.wTreeLn(); Log.wTreeLn("}"); Log.outdentTree(); } } } /* * A <return-statm>. */ class ReturnStatm extends Statement{ // -- mUST BE CHANGED IN PART 1+2 Expression e; @Override void check(DeclList curDecls) { e.check(curDecls); // -- Must be changed in part 2: } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: System.out.println(""+curFunc.assemblerName); e.genCode(curFunc); Code.genInstr("", "jmp", ".exit$"+curFunc.name, "Return-statement"); } static ReturnStatm parse() { // -- Must be changed in part 1: Log.enterParser("<return-statm>"); ReturnStatm rs = new ReturnStatm(); Scanner.skip(returnToken); rs.e = Expression.parse(); Scanner.skip(semicolonToken); Log.leaveParser("</return-statm>"); return rs; } @Override void printTree() { // -- Must be changed in part 1: Log.wTree("return "); e.printTree(); Log.wTree(";"); } } /* * A <while-statm>. */ class WhileStatm extends Statement { Expression test; StatmList body; @Override void check(DeclList curDecls) { test.check(curDecls); body.check(curDecls); Log.noteTypeCheck("while (t) ...", test.type, "t", lineNum); if (test.type instanceof ValueType) { // OK } else { error("While-test must be a value."); } } @Override void genCode(FuncDecl curFunc) { String testLabel = Code.getLocalLabel(), endLabel = Code .getLocalLabel(); Code.genInstr(testLabel, "", "", "Start while-statement"); test.genCode(curFunc); Code.genInstr("", "cmpl", "$0,%eax", ""); Code.genInstr("", "je", endLabel, ""); body.genCode(curFunc); Code.genInstr("", "jmp", testLabel, ""); Code.genInstr(endLabel, "", "", "End while-statement"); } static WhileStatm parse() { Log.enterParser("<while-statm>"); WhileStatm ws = new WhileStatm(); Scanner.skip(whileToken); Scanner.skip(leftParToken); ws.test = Expression.parse(); Scanner.skip(rightParToken); Scanner.skip(leftCurlToken); ws.body = StatmList.parse(); //Scanner.skip(rightCurlToken); Log.leaveParser("</while-statm>"); return ws; } @Override void printTree() { Log.wTree("while ("); test.printTree(); Log.wTreeLn(") {"); Log.indentTree(); body.printTree(); Log.outdentTree(); Log.wTreeLn("}"); } } /* * An <Lhs-variable> */ class LhsVariable extends SyntaxUnit { int numStars = 0; Variable var; Type type; @Override void check(DeclList curDecls) { var.check(curDecls); type = var.type; for (int i = 1; i <= numStars; ++i) { Type e = type.getElemType(); if (e == null) error("Type error in left-hand side variable!"); type = e; } } @Override void genCode(FuncDecl curFunc) { var.genAddressCode(curFunc); for (int i = 1; i <= numStars; ++i) Code.genInstr("", "movl", "(%eax),%eax", " *"); } static LhsVariable parse() { Log.enterParser("<lhs-variable>"); LhsVariable lhs = new LhsVariable(); while (Scanner.curToken == starToken) { ++lhs.numStars; Scanner.skip(starToken); } Scanner.check(nameToken); lhs.var = Variable.parse(); Log.leaveParser("</lhs-variable>"); return lhs; } @Override void printTree() { for (int i = 1; i <= numStars; ++i) Log.wTree("*"); var.printTree(); } } /* * An <assign-statm> */ class AssignStatm extends Statement{ // -- mUST BE CHANGED IN PART 1+2 Assignment a; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: a.check(curDecls); } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: a.genCode(curFunc); } static AssignStatm parse() { // -- Must be changed in part 1: Log.enterParser("<assign-statm>"); AssignStatm as = new AssignStatm(); as.a = Assignment.parse(); Scanner.skip(semicolonToken); Log.leaveParser("</assign-statm>"); return as; } @Override void printTree() { // -- Must be changed in part 1: a.printTree(); Log.wTreeLn(";"); } } /* * An <assignment> */ class Assignment extends Statement{ // -- mUST BE CHANGED IN PART 1+2 Expression e; LhsVariable lhs; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: lhs.check(curDecls); e.check(curDecls); } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: lhs.genCode(curFunc); Code.genInstr("", "pushl", "%eax", ""); e.genCode(curFunc); Code.genInstr("", "popl", "%edx", ""); Code.genInstr("", "movl", "%eax,(%edx)", " ="); } static Assignment parse() { // -- Must be changed in part 1: Log.enterParser("<assignment>"); Assignment ass = new Assignment(); ass.lhs = LhsVariable.parse(); Scanner.skip(assignToken); ass.e = Expression.parse(); Log.leaveParser("</assignment>"); return ass; } @Override void printTree() { // -- Must be changed in part 1: lhs.printTree(); Log.wTree("="); e.printTree(); } } /* * An <expression list>. */ class ExprList extends SyntaxUnit { Expression firstExpr = null; static int length = 0; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: Expression e = firstExpr; while(e != null){ // sjekker alle exprs i exprlisten e.check(curDecls); e = e.nextExpr; } } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: // Expression curr = firstExpr; // while(curr != null){ // curr.genCode(curFunc); // Code.genInstr("", "pushl", "%eax", "Push parameter #"+(++length)); // curr = curr.nextExpr; // } if(firstExpr != null) { Expression curr = firstExpr; if(curr.nextExpr != null) { curr.nextExpr.genCode(curFunc); Code.genInstr("", "pushl", "%eax", "Push parameter #"+(++length)); curr = curr.nextExpr; } curr.genCode(curFunc); Code.genInstr("", "pushl", "%eax", "Push parameter #"+(++length)); } } static ExprList parse() { Expression lastExpr = null; Log.enterParser("<expr list>"); // -- Must be changed in part 1: ExprList el = new ExprList(); length = 1; if(Scanner.curToken != rightParToken) { // makes sure the firstExpr is null if there's no expressions while (Scanner.curToken != rightParToken) { if (el.firstExpr == null) { el.firstExpr = Expression.parse(); } else { Expression prevExpr = el.firstExpr; while (prevExpr.nextExpr != null) { prevExpr = prevExpr.nextExpr; } length++; prevExpr.nextExpr = Expression.parse(); } if (Scanner.curToken != rightParToken) { Scanner.skip(commaToken); } } } else { el.firstExpr = null; } Scanner.skip(rightParToken); Log.leaveParser("</expr list>"); return el; } @Override void printTree() { // -- Must be changed in part 1: Expression currExpr = firstExpr; while(currExpr != null){ currExpr.printTree(); if(currExpr.nextExpr != null){ Log.wTree(", "); } currExpr = currExpr.nextExpr; } } // -- Must be changed in part 1: } /* * An <expression> */ class Expression extends SyntaxUnit { Expression nextExpr = null; Term firstTerm, secondTerm = null; Operator relOpr = null; Type type = null; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: firstTerm.check(curDecls); if(secondTerm == null) { type = firstTerm.type; } else{ secondTerm.check(curDecls); if(relOpr.oprToken == equalToken || relOpr.oprToken == notEqualToken){ if(firstTerm.type instanceof ValueType && secondTerm.type instanceof ValueType && (firstTerm.type.isSameType(secondTerm.type) || firstTerm.type == Types.intType || secondTerm.type == Types.intType)){ type = Types.intType; }else{ Error.error("Type of x was " + firstTerm.type + " and type for y was " + secondTerm.type + ". Both should have been intType"); } }else if(Token.isRelOperator(relOpr.oprToken)){ if(firstTerm.type == Types.intType && secondTerm.type == Types.intType){ type = Types.intType; }else{ Error.error("Expected both to be intTypes, x was " + firstTerm.type + " and y was " + secondTerm.type); } }else{ Error.error("Not a valid expression"); } } } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: // Assignment already redcued away pointer values, so we're left with the actual value firstTerm.genCode(curFunc); if(secondTerm != null){ Code.genInstr("", "pushl", "%eax", ""); // mellomlagrer first term paa stacken secondTerm.genCode(curFunc); // execute second term relOpr.genCode(curFunc); // naar denne kjores ligger term2 i eax og term1 paa toppen av stack } } static Expression parse() { Log.enterParser("<expression>"); Expression e = new Expression(); e.firstTerm = Term.parse(); if (Token.isRelOperator(Scanner.curToken)) { e.relOpr = RelOpr.parse(); e.secondTerm = Term.parse(); } Log.leaveParser("</expression>"); return e; } @Override void printTree() { // -- Must be changed in part 1: firstTerm.printTree(); if(relOpr != null){ relOpr.printTree(); } if(secondTerm != null){ secondTerm.printTree(); } } } /* * A <term> */ class Term extends SyntaxUnit { // -- Must be changed in part 1+2: Factor first; Term second; TermOpr termOpr; Type type; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: first.check(curDecls); if(second == null){ type = first.type; }else{ second.check(curDecls); if(first.type == Types.intType && second.type == Types.intType){ type = first.type; } else{ Error.error("Not declared as intType, was declared as " + first.type); } } } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: // if (first != null){ first.genCode(curFunc); // } //second.genCode(curFunc); if(second != null) { Code.genInstr("", "pushl", "%eax", ""); // mellomlagrer paa stacken second.genCode(curFunc); termOpr.genCode(curFunc); } } static Term parse() { // -- Must be changed in part 1: Log.enterParser("<term>"); Term t = new Term(); t.first = Factor.parse(); if(Token.isTermOperator(Scanner.curToken)) { t.termOpr = TermOpr.parse(); t.second = Term.parse(); } Log.leaveParser("</term>"); return t; } @Override void printTree() { // -- Must be changed in part 1: first.printTree(); if(termOpr != null){ termOpr.printTree(); } if(second != null){ second.printTree(); } } } /* * A <factor> */ class Factor extends SyntaxUnit { // -- Must be changed in part 1+2: FactorOpr factorOpr; Primary first; Factor second; Type type; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: first.check(curDecls); if(second == null){ type = first.type; }else{ second.check(curDecls); if(first.type == Types.intType && second.type == Types.intType){ type = Types.intType; }else{ Error.error("Not declared as intType, was declared as " + first.type); } } } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: first.genCode(curFunc); if(second != null) { Code.genInstr("", "pushl", "%eax", ""); // mellomlagrer first paa stacken second.genCode(curFunc); factorOpr.genCode(curFunc); } } static Factor parse() { // -- Must be changed in part 1: Log.enterParser("<factor>"); Factor f = new Factor(); f.first = Primary.parse(); if(Token.isFactorOperator(Scanner.curToken)){ f.factorOpr = FactorOpr.parse(); f.second = Factor.parse(); } Log.leaveParser("</factor>"); return f; } @Override void printTree() { // -- Must be changed in part 1: first.printTree(); if(factorOpr != null){ factorOpr.printTree(); } if(second != null){ second.printTree(); } } } /* * A <primary> */ class Primary extends SyntaxUnit { // -- Must be changed in part 1+2: Operand first; PrefixOpr prefix; Type type; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: first.check(curDecls); if(prefix == null){ // System.out.println("hei1"); type = first.type; } else if(prefix.oprToken == starToken){ if(first.type instanceof PointerType) type = first.type.getElemType(); else{ Error.error("Expected pointerType, got " + first.type); } }else if(prefix.oprToken == subtractToken){ if(first.type == Types.intType){ type = Types.intType; }else{ Error.error("Expected intType, got " + first.type); } } } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: first.genCode(curFunc); if(prefix != null) { Code.genInstr("", "pushl", "%eax", ""); prefix.genCode(curFunc); } } static Primary parse() { // -- Must be changed in part 1: Log.enterParser("<primary>"); Primary p = new Primary(); // System.out.println(Scanner.curToken); if(Token.isPrefixOperator(Scanner.curToken)){ p.prefix = PrefixOpr.parse(); } p.first = Operand.parse(); // System.out.println(p.first.lineNum +""); Log.leaveParser("</primary>"); return p; } @Override void printTree() { // -- Must be changed in part 1: if(prefix != null){ prefix.printTree(); } first.printTree(); } } /* * An <operator> */ abstract class Operator extends SyntaxUnit { Operator nextOpr = null; Token oprToken; @Override void check(DeclList curDecls) { } // Never needed. } /* * A <term opr> (+ or -) */ class TermOpr extends Operator{ @Override void genCode(FuncDecl curFunc){ // PART 2 Code.genInstr("", "movl", "%eax,%ecx", ""); Code.genInstr("", "popl", "%eax", ""); if(oprToken == addToken) {Code.genInstr("", "addl", "%ecx,%eax", " + ");} else if(oprToken == subtractToken){Code.genInstr("", "subl", "%ecx,%eax", "Compute -");} } static TermOpr parse(){ // PART 1 Log.enterParser("<term opr>"); TermOpr to = new TermOpr(); to.oprToken = Scanner.curToken; Scanner.readNext(); Log.leaveParser("</term opr>"); return to; } @Override void printTree(){ // MUST BE CHANGED IN PART 1 if(oprToken == addToken){Log.wTree(" + ");} else if(oprToken == subtractToken){Log.wTree(" - ");} } } /* * A <factor opr> (* or /) */ class FactorOpr extends Operator{ @Override void genCode(FuncDecl curFunc){ // PART 2 Code.genInstr("", "movl", "%eax, %ecx", ""); Code.genInstr("", "popl", "%eax", ""); if(oprToken == divideToken){ Code.genInstr("", "cdq", "", ""); Code.genInstr("", "idivl", "%ecx", " / "); } else if(oprToken == starToken){Code.genInstr("", "imull", "%ecx, %eax", " * ");} } static FactorOpr parse(){ // PART 1 Log.enterParser("<factor opr>"); FactorOpr fo = new FactorOpr(); fo.oprToken = Scanner.curToken; Scanner.readNext(); Log.leaveParser("</factor opr>"); return fo; } @Override void printTree(){ // MUST BE CHANGED IN PART 1 if(oprToken == starToken){Log.wTree(" * ");} else if(oprToken == divideToken){Log.wTree(" / ");} } } /* * A <prefix opr> (- or *) */ class PrefixOpr extends Operator{ @Override void genCode(FuncDecl curFunc){ // PART 2 if(oprToken == subtractToken){Code.genInstr("", "negl", "%eax", " negative nr");} else if(oprToken == starToken){Code.genInstr("", "movl", "(%eax), %eax", "peker");} } static PrefixOpr parse(){ // PART 1 Log.enterParser("<prefix opr>"); PrefixOpr po = new PrefixOpr(); po.oprToken = Scanner.curToken; Scanner.readNext(); Log.leaveParser("</prefix opr>"); return po; } @Override void printTree(){ // MUST BE CHANGED IN PART 1 if(oprToken == subtractToken){Log.wTree("-");} else if(oprToken == starToken){Log.wTree("*");} } } /* * A <rel opr> (==, !=, <, <=, > or >=). */ class RelOpr extends Operator { @Override void genCode(FuncDecl curFunc) { Code.genInstr("", "popl", "%ecx", ""); Code.genInstr("", "cmpl", "%eax,%ecx", ""); Code.genInstr("", "movl", "$0,%eax", ""); switch (oprToken) { case equalToken: Code.genInstr("", "sete", "%al", "Test =="); break; case notEqualToken: Code.genInstr("", "setne", "%al", "Test !="); break; case lessToken: Code.genInstr("", "setl", "%al", "Test <"); break; case lessEqualToken: Code.genInstr("", "setle", "%al", "Test <="); break; case greaterToken: Code.genInstr("", "setg", "%al", "Test >"); break; case greaterEqualToken: Code.genInstr("", "setge", "%al", "Test >="); break; } } static RelOpr parse() { Log.enterParser("<rel opr>"); RelOpr ro = new RelOpr(); ro.oprToken = Scanner.curToken; Scanner.readNext(); Log.leaveParser("</rel opr>"); return ro; } @Override void printTree() { String op = "?"; switch (oprToken) { case equalToken: op = "=="; break; case notEqualToken: op = "!="; break; case lessToken: op = "<"; break; case lessEqualToken: op = "<="; break; case greaterToken: op = ">"; break; case greaterEqualToken: op = ">="; break; } Log.wTree(" " + op + " "); } } /* * An <operand> */ abstract class Operand extends SyntaxUnit { Operand nextOperand = null; Type type; static Operand parse() { Log.enterParser("<operand>"); Operand o = null; if (Scanner.curToken == numberToken) { o = Number.parse(); } else if (Scanner.curToken == nameToken && Scanner.nextToken == leftParToken) { o = FunctionCall.parse(); } else if (Scanner.curToken == nameToken) { o = Variable.parse(); } else if (Scanner.curToken == ampToken) { o = Address.parse(); } else if (Scanner.curToken == leftParToken) { o = InnerExpr.parse(); } else { Error.expected("An operand"); } Log.leaveParser("</operand>"); return o; } } /* * A <function call>. */ class FunctionCall extends Operand { // -- Must be changed in part 1+2: String funcName; ExprList el; FuncDecl declRef = null; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: if(el == null){ Error.error("ExprList is null"); } Declaration d = curDecls.findDecl(funcName, this); Log.noteBinding(funcName, lineNum, d.lineNum); //d.checkWhetherFunction(el.length, this); type = d.type; declRef = (FuncDecl) d; //Check params el.check(curDecls); // check func Declaration declTmp = declRef.funcParams.firstDecl; Expression callTmp = el.firstExpr; while(declTmp != null && callTmp != null){ if(declTmp == null || callTmp == null){ Error.error("FunctionDecl and callDecl parameterlist are not equal length"); } //if(!declTmp.type.isSameType(callTmp.type) || !callTmp.type.isSameType(Types.intType)) { // Error.error("Function call parameter type not equal to function declaration type or int is " + callTmp.type + " " +callTmp.lineNum); //} declTmp = declTmp.nextDecl; callTmp = callTmp.nextExpr; } } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: el.genCode(curFunc); el.length = 0; FuncDecl f = declRef; Code.genInstr("", "call", f.assemblerName, "Call "+f.name); if(f.funcParams.dataSize()>0){ Code.genInstr("", "addl", "$"+f.funcParams.dataSize()+",%esp", "Remove parameters"); } } static FunctionCall parse() { // -- Must be changed in part 1: Log.enterParser("<function call>"); FunctionCall fc = new FunctionCall(); fc.funcName = Scanner.curName; Scanner.skip(nameToken); Scanner.skip(leftParToken); fc.el = ExprList.parse(); Log.leaveParser("</function call>"); return fc; } @Override void printTree() { // -- Must be changed in part 1: Log.wTree(funcName); Log.wTree("("); el.printTree(); Log.wTree(")"); } // -- Must be changed in part 1+2: } /* * A <number>. */ class Number extends Operand { int numVal; @Override void check(DeclList curDecls) { // -- Must be changed in part 2: type = Types.intType; } @Override void genCode(FuncDecl curFunc) { Code.genInstr("", "movl", "$" + numVal + ",%eax", "" + numVal); } static Number parse() { // -- Must be changed in part 1: Log.enterParser("<number>"); Number n = new Number(); n.numVal = Scanner.curNum; Scanner.skip(numberToken); Log.leaveParser("</number>"); return n; } @Override void printTree() { Log.wTree("" + numVal); } } /* * A <variable>. */ class Variable extends Operand { String varName; VarDecl declRef = null; Expression index = null; @Override void check(DeclList curDecls) { Declaration d = curDecls.findDecl(varName, this); Log.noteBinding(varName, lineNum, d.lineNum); d.checkWhetherVariable(this); declRef = (VarDecl) d; if (index == null) { type = d.type; } else { index.check(curDecls); Log.noteTypeCheck("a[e]", d.type, "a", index.type, "e", lineNum); if (index.type == Types.intType) { // OK } else { error("Only integers may be used as index."); } if (d.type.mayBeIndexed()) { // OK } else { error("Only arrays and pointers may be indexed."); } type = d.type.getElemType(); } } @Override void genCode(FuncDecl curFunc) { // -- Must be changed in part 2: if (index == null) { Code.genInstr("", "movl", declRef.assemblerName + ",%eax", varName); } else { index.genCode(curFunc); if (declRef.type instanceof ArrayType) { Code.genInstr("", "leal", declRef.assemblerName + ",%edx", varName + "[...]"); } else { Code.genInstr("", "movl", declRef.assemblerName + ",%edx", varName + "[...]"); } Code.genInstr("", "movl", "(%edx, %eax, 4), %eax", ""); } } void genAddressCode(FuncDecl curFunc) { // Generate code to load the _address_ of the variable // rather than its value. if (index == null) { Code.genInstr("", "leal", declRef.assemblerName + ",%eax", varName); } else { index.genCode(curFunc); if (declRef.type instanceof ArrayType) { Code.genInstr("", "leal", declRef.assemblerName + ",%edx", varName + "[...]"); } else { Code.genInstr("", "movl", declRef.assemblerName + ",%edx", varName + "[...]"); } Code.genInstr("", "leal", "(%edx,%eax,4),%eax", ""); } } static Variable parse() { Log.enterParser("<variable>"); // -- Must be changed in part 1: Variable v = new Variable(); v.varName = Scanner.curName; Scanner.skip(nameToken); if(Scanner.curToken == leftBracketToken){ Scanner.skip(leftBracketToken); v.index = Expression.parse(); Scanner.skip(rightBracketToken); } Log.leaveParser("</variable>"); return v; } @Override void printTree() { // -- Must be changed in part 1: Log.wTree(varName); if(index != null){ Log.wTree("["); index.printTree(); Log.wTree("]"); } } } /* * An <address>. */ class Address extends Operand { Variable var; @Override void check(DeclList curDecls) { var.check(curDecls); type = new PointerType(var.type); } @Override void genCode(FuncDecl curFunc) { var.genAddressCode(curFunc); } static Address parse() { Log.enterParser("<address>"); Address a = new Address(); Scanner.skip(ampToken); a.var = Variable.parse(); Log.leaveParser("</address>"); return a; } @Override void printTree() { Log.wTree("&"); var.printTree(); } } /* * An <inner expr>. */ class InnerExpr extends Operand { Expression expr; @Override void check(DeclList curDecls) { expr.check(curDecls); type = expr.type; } @Override void genCode(FuncDecl curFunc) { expr.genCode(curFunc); } static InnerExpr parse() { Log.enterParser("<inner expr>"); InnerExpr ie = new InnerExpr(); Scanner.skip(leftParToken); ie.expr = Expression.parse(); Scanner.skip(rightParToken); Log.leaveParser("</inner expr>"); return ie; } @Override void printTree() { Log.wTree("("); expr.printTree(); Log.wTree(")"); } }
debugging
alboc/no/uio/ifi/alboc/syntax/Syntax.java
debugging
Java
apache-2.0
58ca8489d1bf44a0f7a0cc9e7f5911c633c79695
0
HanSolo/Medusa
/* * Copyright (c) 2015 by Gerrit Grunwald * * 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 eu.hansolo.medusa; import javafx.beans.property.DoubleProperty; import javafx.beans.property.DoublePropertyBase; import javafx.beans.property.ObjectProperty; import javafx.beans.property.ObjectPropertyBase; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.StringProperty; import javafx.beans.property.StringPropertyBase; import javafx.event.Event; import javafx.event.EventHandler; import javafx.event.EventTarget; import javafx.event.EventType; import javafx.scene.image.Image; import javafx.scene.paint.Color; /** * Created by hansolo on 11.12.15. */ public class Section implements Comparable<Section> { public final SectionEvent ENTERED_EVENT = new SectionEvent(this, null, SectionEvent.SECTION_ENTERED); public final SectionEvent LEFT_EVENT = new SectionEvent(this, null, SectionEvent.SECTION_LEFT); public final SectionEvent UPDATE_EVENT = new SectionEvent(this, null, SectionEvent.SECTION_UPDATE); private double _start; private DoubleProperty start; private double _stop; private DoubleProperty stop; private String _text; private StringProperty text; private Image _icon; private ObjectProperty<Image> icon; private Color _color; private ObjectProperty<Color> color; private Color _highlightColor; private ObjectProperty<Color> highlightColor; private Color _textColor; private ObjectProperty<Color> textColor; private double checkedValue; private String styleClass; // ******************** Constructors ************************************** /** * Represents an area of a given range, defined by a start and stop value. * This class is used for regions and areas in many gauges. It is possible * to check a value against the defined range and fire events in case the * value enters or leaves the defined region. */ public Section() { this(-1, -1, "", null, Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT, ""); } public Section(final double START, final double STOP) { this(START, STOP, "", null, Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT, ""); } public Section(final double START, final double STOP, final Color COLOR) { this(START, STOP, "", null, COLOR, COLOR, Color.TRANSPARENT, ""); } public Section(final double START, final double STOP, final Color COLOR, final Color HIGHLIGHT_COLOR) { this(START, STOP, "", null, COLOR, HIGHLIGHT_COLOR, Color.TRANSPARENT, ""); } public Section(final double START, final double STOP, final Image ICON, final Color COLOR) { this(START, STOP, "", ICON, COLOR, COLOR, Color.WHITE, ""); } public Section(final double START, final double STOP, final String TEXT, final Color COLOR) { this(START, STOP, TEXT, null, COLOR, COLOR, Color.WHITE, ""); } public Section(final double START, final double STOP, final String TEXT, final Color COLOR, final Color TEXT_COLOR) { this(START, STOP, TEXT, null, COLOR, COLOR, TEXT_COLOR, ""); } public Section(final double START, final double STOP, final String TEXT, final Image ICON, final Color COLOR, final Color TEXT_COLOR) { this(START, STOP, TEXT, ICON, COLOR, COLOR, TEXT_COLOR, ""); } public Section(final double START, final double STOP, final String TEXT, final Image ICON, final Color COLOR, final Color HIGHLIGHT_COLOR, final Color TEXT_COLOR) { this(START, STOP, TEXT, ICON, COLOR, HIGHLIGHT_COLOR, TEXT_COLOR, ""); } public Section(final double START, final double STOP, final String TEXT, final Image ICON, final Color COLOR, final Color HIGHLIGHT_COLOR, final Color TEXT_COLOR, final String STYLE_CLASS) { _start = START; _stop = STOP; _text = TEXT; _icon = ICON; _color = COLOR; _highlightColor = HIGHLIGHT_COLOR; _textColor = TEXT_COLOR; checkedValue = -Double.MAX_VALUE; styleClass = STYLE_CLASS; } // ******************** Methods ******************************************* /** * Returns the value where the section begins. * @return the value where the section begins */ public double getStart() { return null == start ? _start : start.get(); } /** * Defines the value where the section begins. * @param START */ public void setStart(final double START) { if (null == start) { _start = START; fireSectionEvent(UPDATE_EVENT); } else { start.set(START); } } public DoubleProperty startProperty() { if (null == start) { start = new DoublePropertyBase(_start) { @Override protected void invalidated() { fireSectionEvent(UPDATE_EVENT); } @Override public Object getBean() { return Section.this; } @Override public String getName() { return "start"; } }; } return start; } /** * Returns the value where the section ends. * @return the value where the section ends */ public double getStop() { return null == stop ? _stop : stop.get(); } /** * Defines the value where the section ends. * @param STOP */ public void setStop(final double STOP) { if (null == stop) { _stop = STOP; fireSectionEvent(UPDATE_EVENT); } else { stop.set(STOP); } } public DoubleProperty stopProperty() { if (null == stop) { stop = new DoublePropertyBase(_stop) { @Override protected void invalidated() { fireSectionEvent(UPDATE_EVENT); } @Override public Object getBean() { return Section.this; } @Override public String getName() { return "stop"; } }; } return stop; } /** * Returns the text that was set for the section. * @return the text that was set for the section */ public String getText() { return null == text ? _text : text.get(); } /** * Defines a text for the section. * @param TEXT */ public void setText(final String TEXT) { if (null == text) { _text = TEXT; fireSectionEvent(UPDATE_EVENT); } else { text.set(TEXT); } } public StringProperty textProperty() { if (null == text) { text = new StringPropertyBase(_text) { @Override protected void invalidated() { fireSectionEvent(UPDATE_EVENT); } @Override public Object getBean() { return Section.this; } @Override public String getName() { return "text"; } }; } return text; } /** * Returns the image that was defined for the section. * In some skins the image will be drawn (e.g. SimpleSkin). * @return the image that was defined for the section */ public Image getImage() { return null == icon ? _icon : icon.get(); } /** * Defines an image for the section. * In some skins the image will be drawn (e.g. SimpleSkin) * @param IMAGE */ public void setIcon(final Image IMAGE) { if (null == icon) { _icon = IMAGE; fireSectionEvent(UPDATE_EVENT); } else { icon.set(IMAGE); } } public ObjectProperty<Image> iconProperty() { if (null == icon) { icon = new ObjectPropertyBase<Image>(_icon) { @Override protected void invalidated() { fireSectionEvent(UPDATE_EVENT); } @Override public Object getBean() { return Section.this; } @Override public String getName() { return "icon"; } }; } return icon; } /** * Returns the color that will be used to colorize the section in * a gauge. * @return the color that will be used to colorize the section */ public Color getColor() { return null == color ? _color : color.get(); } /** * Defines the color that will be used to colorize the section in * a gauge. * @param COLOR */ public void setColor(final Color COLOR) { if (null == color) { _color = COLOR; fireSectionEvent(UPDATE_EVENT); } else { color.set(COLOR); } } public ObjectProperty<Color> colorProperty() { if (null == color) { color = new ObjectPropertyBase<Color>(_color) { @Override protected void invalidated() { fireSectionEvent(UPDATE_EVENT); } @Override public Object getBean() { return Section.this; } @Override public String getName() { return "color"; } }; } return color; } /** * Returns the color that will be used to colorize the section in * a gauge when it is highlighted. * @return the color that will be used to colorize a highlighted section */ public Color getHighlightColor() { return null == highlightColor ? _highlightColor : highlightColor.get(); } /** * Defines the color that will be used to colorize a highlighted section * @param COLOR */ public void setHighlightColor(final Color COLOR) { if (null == highlightColor) { _highlightColor = COLOR; fireSectionEvent(UPDATE_EVENT); } else { highlightColor.set(COLOR); } } public ObjectProperty<Color> highlightColorProperty() { if (null == highlightColor) { highlightColor = new ObjectPropertyBase<Color>(_highlightColor) { @Override protected void invalidated() { fireSectionEvent(UPDATE_EVENT); } @Override public Object getBean() { return Section.this; } @Override public String getName() { return "highlightColor"; } }; } return highlightColor; } /** * Returns the color that will be used to colorize the section text. * @return the color that will be used to colorize the section text */ public Color getTextColor() { return null == textColor ? _textColor : textColor.get(); } /** * Defines the color that will be used to colorize the section text. * @param COLOR */ public void setTextColor(final Color COLOR) { if (null == textColor) { _textColor = COLOR; fireSectionEvent(UPDATE_EVENT); } else { textColor.set(COLOR); } } public ObjectProperty<Color> textColorProperty() { if (null == textColor) { textColor = new ObjectPropertyBase<Color>(_textColor) { @Override protected void invalidated() { fireSectionEvent(UPDATE_EVENT); } @Override public Object getBean() { return Section.this; } @Override public String getName() { return "textColor"; } }; } return textColor; } /** * Returns the style class that can be used to colorize the section. * This is not implemented in the current available skins. * @return the style class that can be used to colorize the section */ public String getStyleClass() { return styleClass; } /** * Defines the style class that can be used to colorize the section. * This is not implemented in the current available skins. * @param STYLE_CLASS */ public void setStyleClass(final String STYLE_CLASS) { styleClass = STYLE_CLASS; } /** * Returns true if the given value is within the range between * section.getStart() and section.getStop() * @param VALUE * @return true if the given value is within the range of the section */ public boolean contains(final double VALUE) { return (Double.compare(VALUE, getStart()) >= 0 && Double.compare(VALUE, getStop()) <= 0); } /** * Checks if the section contains the given value and fires an event * in case the value "entered" or "left" the section. With this one * can react if a value enters/leaves a specific region in a gauge. * @param VALUE */ public void checkForValue(final double VALUE) { boolean wasInSection = contains(checkedValue); boolean isInSection = contains(VALUE); if (!wasInSection && isInSection) { fireSectionEvent(ENTERED_EVENT); } else if (wasInSection && !isInSection) { fireSectionEvent(LEFT_EVENT); } checkedValue = VALUE; } public boolean equals(final Section SECTION) { return (Double.compare(SECTION.getStart(), getStart()) == 0 && Double.compare(SECTION.getStop(), getStop()) == 0 && SECTION.getText().equals(getText())); } @Override public int compareTo(final Section SECTION) { if (Double.compare(getStart(), SECTION.getStart()) < 0) return -1; if (Double.compare(getStart(), SECTION.getStart()) > 0) return 1; return 0; } @Override public String toString() { return new StringBuilder() .append("{\n") .append("\"text\":\"").append(getText()).append("\",\n") .append("\"startValue\":").append(getStart()).append(",\n") .append("\"stopValue\":").append(getStop()).append(",\n") .append("\"color\":\"").append(getColor().toString().substring(0,8).replace("0x", "#")).append("\",\n") .append("\"highlightColor\":\"").append(getHighlightColor().toString().substring(0,8).replace("0x", "#")).append("\",\n") .append("\"textColor\":\"").append(getTextColor().toString().substring(0,8).replace("0x", "#")).append("\"\n") .append("}") .toString(); } // ******************** Event handling ************************************ public final ObjectProperty<EventHandler<SectionEvent>> onSectionEnteredProperty() { return onSectionEntered; } public final void setOnSectionEntered(EventHandler<SectionEvent> value) { onSectionEnteredProperty().set(value); } public final EventHandler<SectionEvent> getOnSectionEntered() { return onSectionEnteredProperty().get(); } private ObjectProperty<EventHandler<SectionEvent>> onSectionEntered = new SimpleObjectProperty<>(this, "onSectionEntered"); public final ObjectProperty<EventHandler<SectionEvent>> onSectionLeftProperty() { return onSectionLeft; } public final void setOnSectionLeft(EventHandler<SectionEvent> value) { onSectionLeftProperty().set(value); } public final EventHandler<SectionEvent> getOnSectionLeft() { return onSectionLeftProperty().get(); } private ObjectProperty<EventHandler<SectionEvent>> onSectionLeft = new SimpleObjectProperty<>(this, "onSectionLeft"); public final ObjectProperty<EventHandler<SectionEvent>> onSectionUpdateProperty() { return onSectionUpdate; } public final void setOnSectionUpdate(EventHandler<SectionEvent> value) { onSectionUpdateProperty().set(value); } public final EventHandler<SectionEvent> getOnSectionUpdate() { return onSectionUpdateProperty().get(); } private ObjectProperty<EventHandler<SectionEvent>> onSectionUpdate = new SimpleObjectProperty<>(this, "onSectionUpdate"); public void fireSectionEvent(final SectionEvent EVENT) { final EventHandler<SectionEvent> HANDLER; final EventType TYPE = EVENT.getEventType(); if (SectionEvent.SECTION_ENTERED == TYPE) { HANDLER = getOnSectionEntered(); } else if (SectionEvent.SECTION_LEFT == TYPE) { HANDLER = getOnSectionLeft(); } else if (SectionEvent.SECTION_UPDATE == TYPE) { HANDLER = getOnSectionUpdate(); } else { HANDLER = null; } if (null == HANDLER) return; HANDLER.handle(EVENT); } // ******************** Inner Classes ************************************* public static class SectionEvent extends Event { public static final EventType<SectionEvent> SECTION_ENTERED = new EventType(ANY, "SECTION_ENTERED"); public static final EventType<SectionEvent> SECTION_LEFT = new EventType(ANY, "SECTION_LEFT"); public static final EventType<SectionEvent> SECTION_UPDATE = new EventType(ANY, "SECTION_UPDATE"); // ******************** Constructors ************************************** public SectionEvent(final Object SOURCE, final EventTarget TARGET, EventType<SectionEvent> TYPE) { super(SOURCE, TARGET, TYPE); } } }
src/main/java/eu/hansolo/medusa/Section.java
/* * Copyright (c) 2015 by Gerrit Grunwald * * 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 eu.hansolo.medusa; import javafx.beans.property.DoubleProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.event.Event; import javafx.event.EventHandler; import javafx.event.EventTarget; import javafx.event.EventType; import javafx.scene.image.Image; import javafx.scene.paint.Color; /** * Created by hansolo on 11.12.15. */ public class Section implements Comparable<Section> { public final SectionEvent ENTERED_EVENT = new SectionEvent(this, null, SectionEvent.SECTION_ENTERED); public final SectionEvent LEFT_EVENT = new SectionEvent(this, null, SectionEvent.SECTION_LEFT); private double _start; private DoubleProperty start; private double _stop; private DoubleProperty stop; private String _text; private StringProperty text; private Image _icon; private ObjectProperty<Image> icon; private Color _color; private ObjectProperty<Color> color; private Color _highlightColor; private ObjectProperty<Color> highlightColor; private Color _textColor; private ObjectProperty<Color> textColor; private double checkedValue; private String styleClass; // ******************** Constructors ************************************** /** * Represents an area of a given range, defined by a start and stop value. * This class is used for regions and areas in many gauges. It is possible * to check a value against the defined range and fire events in case the * value enters or leaves the defined region. */ public Section() { this(-1, -1, "", null, Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT, ""); } public Section(final double START, final double STOP) { this(START, STOP, "", null, Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT, ""); } public Section(final double START, final double STOP, final Color COLOR) { this(START, STOP, "", null, COLOR, COLOR, Color.TRANSPARENT, ""); } public Section(final double START, final double STOP, final Color COLOR, final Color HIGHLIGHT_COLOR) { this(START, STOP, "", null, COLOR, HIGHLIGHT_COLOR, Color.TRANSPARENT, ""); } public Section(final double START, final double STOP, final Image ICON, final Color COLOR) { this(START, STOP, "", ICON, COLOR, COLOR, Color.WHITE, ""); } public Section(final double START, final double STOP, final String TEXT, final Color COLOR) { this(START, STOP, TEXT, null, COLOR, COLOR, Color.WHITE, ""); } public Section(final double START, final double STOP, final String TEXT, final Color COLOR, final Color TEXT_COLOR) { this(START, STOP, TEXT, null, COLOR, COLOR, TEXT_COLOR, ""); } public Section(final double START, final double STOP, final String TEXT, final Image ICON, final Color COLOR, final Color TEXT_COLOR) { this(START, STOP, TEXT, ICON, COLOR, COLOR, TEXT_COLOR, ""); } public Section(final double START, final double STOP, final String TEXT, final Image ICON, final Color COLOR, final Color HIGHLIGHT_COLOR, final Color TEXT_COLOR) { this(START, STOP, TEXT, ICON, COLOR, HIGHLIGHT_COLOR, TEXT_COLOR, ""); } public Section(final double START, final double STOP, final String TEXT, final Image ICON, final Color COLOR, final Color HIGHLIGHT_COLOR, final Color TEXT_COLOR, final String STYLE_CLASS) { _start = START; _stop = STOP; _text = TEXT; _icon = ICON; _color = COLOR; _highlightColor = HIGHLIGHT_COLOR; _textColor = TEXT_COLOR; checkedValue = -Double.MAX_VALUE; styleClass = STYLE_CLASS; } // ******************** Methods ******************************************* /** * Returns the value where the section begins. * @return the value where the section begins */ public double getStart() { return null == start ? _start : start.get(); } /** * Defines the value where the section begins. * @param START */ public void setStart(final double START) { if (null == start) { _start = START; } else { start.set(START); } } public DoubleProperty startProperty() { if (null == start) { start = new SimpleDoubleProperty(Section.this, "start", _start); } return start; } /** * Returns the value where the section ends. * @return the value where the section ends */ public double getStop() { return null == stop ? _stop : stop.get(); } /** * Defines the value where the section ends. * @param STOP */ public void setStop(final double STOP) { if (null == stop) { _stop = STOP; } else { stop.set(STOP); } } public DoubleProperty stopProperty() { if (null == stop) { stop = new SimpleDoubleProperty(Section.this, "stop", _stop); } return stop; } /** * Returns the text that was set for the section. * @return the text that was set for the section */ public String getText() { return null == text ? _text : text.get(); } /** * Defines a text for the section. * @param TEXT */ public void setText(final String TEXT) { if (null == text) { _text = TEXT; } else { text.set(TEXT); } } public StringProperty textProperty() { if (null == text) { text = new SimpleStringProperty(Section.this, "text", _text); } return text; } /** * Returns the image that was defined for the section. * In some skins the image will be drawn (e.g. SimpleSkin). * @return the image that was defined for the section */ public Image getImage() { return null == icon ? _icon : icon.get(); } /** * Defines an image for the section. * In some skins the image will be drawn (e.g. SimpleSkin) * @param IMAGE */ public void setIcon(final Image IMAGE) { if (null == icon) { _icon = IMAGE; } else { icon.set(IMAGE); } } public ObjectProperty<Image> iconProperty() { if (null == icon) { icon = new SimpleObjectProperty<>(this, "icon", _icon); } return icon; } /** * Returns the color that will be used to colorize the section in * a gauge. * @return the color that will be used to colorize the section */ public Color getColor() { return null == color ? _color : color.get(); } /** * Defines the color that will be used to colorize the section in * a gauge. * @param COLOR */ public void setColor(final Color COLOR) { if (null == color) { _color = COLOR; } else { color.set(COLOR); } } public ObjectProperty<Color> colorProperty() { if (null == color) { color = new SimpleObjectProperty<>(Section.this, "color", _color); } return color; } /** * Returns the color that will be used to colorize the section in * a gauge when it is highlighted. * @return the color that will be used to colorize a highlighted section */ public Color getHighlightColor() { return null == highlightColor ? _highlightColor : highlightColor.get(); } /** * Defines the color that will be used to colorize a highlighted section * @param COLOR */ public void setHighlightColor(final Color COLOR) { if (null == highlightColor) { _highlightColor = COLOR; } else { highlightColor.set(COLOR); } } public ObjectProperty<Color> highlightColorProperty() { if (null == highlightColor) { highlightColor = new SimpleObjectProperty<>(Section.this, "highlightColor", _highlightColor); } return highlightColor; } /** * Returns the color that will be used to colorize the section text. * @return the color that will be used to colorize the section text */ public Color getTextColor() { return null == textColor ? _textColor : textColor.get(); } /** * Defines the color that will be used to colorize the section text. * @param COLOR */ public void setTextColor(final Color COLOR) { if (null == textColor) { _textColor = COLOR; } else { textColor.set(COLOR); } } public ObjectProperty<Color> textColorProperty() { if (null == textColor) { textColor = new SimpleObjectProperty<>(Section.this, "textColor", _textColor); } return textColor; } /** * Returns the style class that can be used to colorize the section. * This is not implemented in the current available skins. * @return the style class that can be used to colorize the section */ public String getStyleClass() { return styleClass; } /** * Defines the style class that can be used to colorize the section. * This is not implemented in the current available skins. * @param STYLE_CLASS */ public void setStyleClass(final String STYLE_CLASS) { styleClass = STYLE_CLASS; } /** * Returns true if the given value is within the range between * section.getStart() and section.getStop() * @param VALUE * @return true if the given value is within the range of the section */ public boolean contains(final double VALUE) { return (Double.compare(VALUE, getStart()) >= 0 && Double.compare(VALUE, getStop()) <= 0); } /** * Checks if the section contains the given value and fires an event * in case the value "entered" or "left" the section. With this one * can react if a value enters/leaves a specific region in a gauge. * @param VALUE */ public void checkForValue(final double VALUE) { boolean wasInSection = contains(checkedValue); boolean isInSection = contains(VALUE); if (!wasInSection && isInSection) { fireSectionEvent(ENTERED_EVENT); } else if (wasInSection && !isInSection) { fireSectionEvent(LEFT_EVENT); } checkedValue = VALUE; } public boolean equals(final Section SECTION) { return (Double.compare(SECTION.getStart(), getStart()) == 0 && Double.compare(SECTION.getStop(), getStop()) == 0 && SECTION.getText().equals(getText())); } @Override public int compareTo(final Section SECTION) { if (Double.compare(getStart(), SECTION.getStart()) < 0) return -1; if (Double.compare(getStart(), SECTION.getStart()) > 0) return 1; return 0; } @Override public String toString() { return new StringBuilder() .append("{\n") .append("\"text\":\"").append(getText()).append("\",\n") .append("\"startValue\":").append(getStart()).append(",\n") .append("\"stopValue\":").append(getStop()).append(",\n") .append("\"color\":\"").append(getColor().toString().substring(0,8).replace("0x", "#")).append("\",\n") .append("\"highlightColor\":\"").append(getHighlightColor().toString().substring(0,8).replace("0x", "#")).append("\",\n") .append("\"textColor\":\"").append(getTextColor().toString().substring(0,8).replace("0x", "#")).append("\"\n") .append("}") .toString(); } // ******************** Event handling ************************************ public final ObjectProperty<EventHandler<SectionEvent>> onSectionEnteredProperty() { return onSectionEntered; } public final void setOnSectionEntered(EventHandler<SectionEvent> value) { onSectionEnteredProperty().set(value); } public final EventHandler<SectionEvent> getOnSectionEntered() { return onSectionEnteredProperty().get(); } private ObjectProperty<EventHandler<SectionEvent>> onSectionEntered = new SimpleObjectProperty<>(this, "onSectionEntered"); public final ObjectProperty<EventHandler<SectionEvent>> onSectionLeftProperty() { return onSectionLeft; } public final void setOnSectionLeft(EventHandler<SectionEvent> value) { onSectionLeftProperty().set(value); } public final EventHandler<SectionEvent> getOnSectionLeft() { return onSectionLeftProperty().get(); } private ObjectProperty<EventHandler<SectionEvent>> onSectionLeft = new SimpleObjectProperty<>(this, "onSectionLeft"); public void fireSectionEvent(final SectionEvent EVENT) { final EventHandler<SectionEvent> HANDLER; final EventType TYPE = EVENT.getEventType(); if (SectionEvent.SECTION_ENTERED == TYPE) { HANDLER = getOnSectionEntered(); } else if (SectionEvent.SECTION_LEFT == TYPE) { HANDLER = getOnSectionLeft(); } else { HANDLER = null; } if (null == HANDLER) return; HANDLER.handle(EVENT); } // ******************** Inner Classes ************************************* public static class SectionEvent extends Event { public static final EventType<SectionEvent> SECTION_ENTERED = new EventType(ANY, "SECTION_ENTERED"); public static final EventType<SectionEvent> SECTION_LEFT = new EventType(ANY, "SECTION_LEFT"); // ******************** Constructors ************************************** public SectionEvent(final Object SOURCE, final EventTarget TARGET, EventType<SectionEvent> TYPE) { super(SOURCE, TARGET, TYPE); } } }
Sections will now fire an event of type SectionEvent.SECTION_UPDATE whenever a property changed With this you can listen to Section updates when the application is running. To trigger a redraw of the gauge in case a property of a Section changed you can use the following line of code: gauge.getSections().forEach(section -> section.setOnSectionUpdate(sectionEvent -> gauge.fireUpdateEvent(new UpdateEvent(YOUR_APP_CLASS.this, EventType.REDRAW))));
src/main/java/eu/hansolo/medusa/Section.java
Sections will now fire an event of type SectionEvent.SECTION_UPDATE whenever a property changed
Java
apache-2.0
b0514bc92144523c7add28f8ba97ae6f2aa17ed7
0
google/j2objc,life-beam/j2objc,life-beam/j2objc,groschovskiy/j2objc,lukhnos/j2objc,google/j2objc,groschovskiy/j2objc,lukhnos/j2objc,bandcampdotcom/j2objc,mirego/j2objc,lukhnos/j2objc,mirego/j2objc,doppllib/j2objc,life-beam/j2objc,life-beam/j2objc,google/j2objc,lukhnos/j2objc,mirego/j2objc,mirego/j2objc,life-beam/j2objc,groschovskiy/j2objc,doppllib/j2objc,doppllib/j2objc,mirego/j2objc,doppllib/j2objc,lukhnos/j2objc,life-beam/j2objc,google/j2objc,groschovskiy/j2objc,mirego/j2objc,groschovskiy/j2objc,bandcampdotcom/j2objc,bandcampdotcom/j2objc,doppllib/j2objc,bandcampdotcom/j2objc,google/j2objc,google/j2objc,lukhnos/j2objc,doppllib/j2objc,bandcampdotcom/j2objc,groschovskiy/j2objc,bandcampdotcom/j2objc
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.j2objc.javac; import com.google.devtools.j2objc.ast.AbstractTypeDeclaration; import com.google.devtools.j2objc.ast.Annotation; import com.google.devtools.j2objc.ast.AnnotationTypeDeclaration; import com.google.devtools.j2objc.ast.AnnotationTypeMemberDeclaration; import com.google.devtools.j2objc.ast.AnonymousClassDeclaration; import com.google.devtools.j2objc.ast.ArrayAccess; import com.google.devtools.j2objc.ast.ArrayCreation; import com.google.devtools.j2objc.ast.ArrayInitializer; import com.google.devtools.j2objc.ast.ArrayType; import com.google.devtools.j2objc.ast.AssertStatement; import com.google.devtools.j2objc.ast.Assignment; import com.google.devtools.j2objc.ast.Block; import com.google.devtools.j2objc.ast.BlockComment; import com.google.devtools.j2objc.ast.BodyDeclaration; import com.google.devtools.j2objc.ast.BooleanLiteral; import com.google.devtools.j2objc.ast.BreakStatement; import com.google.devtools.j2objc.ast.CastExpression; import com.google.devtools.j2objc.ast.CatchClause; import com.google.devtools.j2objc.ast.CharacterLiteral; import com.google.devtools.j2objc.ast.ClassInstanceCreation; import com.google.devtools.j2objc.ast.Comment; import com.google.devtools.j2objc.ast.CompilationUnit; import com.google.devtools.j2objc.ast.ConditionalExpression; import com.google.devtools.j2objc.ast.ConstructorInvocation; import com.google.devtools.j2objc.ast.ContinueStatement; import com.google.devtools.j2objc.ast.CreationReference; import com.google.devtools.j2objc.ast.DoStatement; import com.google.devtools.j2objc.ast.EmptyStatement; import com.google.devtools.j2objc.ast.EnhancedForStatement; import com.google.devtools.j2objc.ast.EnumConstantDeclaration; import com.google.devtools.j2objc.ast.EnumDeclaration; import com.google.devtools.j2objc.ast.Expression; import com.google.devtools.j2objc.ast.ExpressionMethodReference; import com.google.devtools.j2objc.ast.ExpressionStatement; import com.google.devtools.j2objc.ast.FieldAccess; import com.google.devtools.j2objc.ast.FieldDeclaration; import com.google.devtools.j2objc.ast.ForStatement; import com.google.devtools.j2objc.ast.FunctionalExpression; import com.google.devtools.j2objc.ast.IfStatement; import com.google.devtools.j2objc.ast.InfixExpression; import com.google.devtools.j2objc.ast.InstanceofExpression; import com.google.devtools.j2objc.ast.Javadoc; import com.google.devtools.j2objc.ast.LabeledStatement; import com.google.devtools.j2objc.ast.LambdaExpression; import com.google.devtools.j2objc.ast.LineComment; import com.google.devtools.j2objc.ast.MarkerAnnotation; import com.google.devtools.j2objc.ast.MemberValuePair; import com.google.devtools.j2objc.ast.MethodDeclaration; import com.google.devtools.j2objc.ast.MethodInvocation; import com.google.devtools.j2objc.ast.MethodReference; import com.google.devtools.j2objc.ast.Name; import com.google.devtools.j2objc.ast.NormalAnnotation; import com.google.devtools.j2objc.ast.NullLiteral; import com.google.devtools.j2objc.ast.NumberLiteral; import com.google.devtools.j2objc.ast.PackageDeclaration; import com.google.devtools.j2objc.ast.ParameterizedType; import com.google.devtools.j2objc.ast.ParenthesizedExpression; import com.google.devtools.j2objc.ast.PostfixExpression; import com.google.devtools.j2objc.ast.PrefixExpression; import com.google.devtools.j2objc.ast.PrimitiveType; import com.google.devtools.j2objc.ast.PropertyAnnotation; import com.google.devtools.j2objc.ast.QualifiedName; import com.google.devtools.j2objc.ast.ReturnStatement; import com.google.devtools.j2objc.ast.SimpleName; import com.google.devtools.j2objc.ast.SimpleType; import com.google.devtools.j2objc.ast.SingleMemberAnnotation; import com.google.devtools.j2objc.ast.SingleVariableDeclaration; import com.google.devtools.j2objc.ast.SourcePosition; import com.google.devtools.j2objc.ast.Statement; import com.google.devtools.j2objc.ast.StringLiteral; import com.google.devtools.j2objc.ast.SuperConstructorInvocation; import com.google.devtools.j2objc.ast.SuperFieldAccess; import com.google.devtools.j2objc.ast.SuperMethodReference; import com.google.devtools.j2objc.ast.SwitchCase; import com.google.devtools.j2objc.ast.SwitchStatement; import com.google.devtools.j2objc.ast.SynchronizedStatement; import com.google.devtools.j2objc.ast.ThisExpression; import com.google.devtools.j2objc.ast.ThrowStatement; import com.google.devtools.j2objc.ast.TreeNode; import com.google.devtools.j2objc.ast.TreeUtil; import com.google.devtools.j2objc.ast.TryStatement; import com.google.devtools.j2objc.ast.Type; import com.google.devtools.j2objc.ast.TypeDeclaration; import com.google.devtools.j2objc.ast.TypeDeclarationStatement; import com.google.devtools.j2objc.ast.TypeLiteral; import com.google.devtools.j2objc.ast.TypeMethodReference; import com.google.devtools.j2objc.ast.VariableDeclaration; import com.google.devtools.j2objc.ast.VariableDeclarationExpression; import com.google.devtools.j2objc.ast.VariableDeclarationFragment; import com.google.devtools.j2objc.ast.VariableDeclarationStatement; import com.google.devtools.j2objc.ast.WhileStatement; import com.google.devtools.j2objc.types.ExecutablePair; import com.google.devtools.j2objc.util.ElementUtil; import com.google.devtools.j2objc.util.ErrorUtil; import com.google.devtools.j2objc.util.FileUtil; import com.google.devtools.j2objc.util.TranslationEnvironment; import com.google.j2objc.annotations.Property; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.StatementTree; import com.sun.source.tree.Tree.Kind; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.PackageSymbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import com.sun.tools.javac.tree.DocCommentTable; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.tree.JCTree.Tag; import com.sun.tools.javac.tree.TreeInfo; import com.sun.tools.javac.util.Position; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.PackageElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.ExecutableType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.tools.JavaFileObject; /** * Converts a Java AST from the JDT data structure to our J2ObjC data structure. */ public class TreeConverter { private JCTree.JCCompilationUnit unit; public static CompilationUnit convertCompilationUnit( JavacEnvironment env, JCTree.JCCompilationUnit javacUnit) { String sourceFilePath = getPath(javacUnit.getSourceFile()); try { TreeConverter converter = new TreeConverter(javacUnit); JavaFileObject sourceFile = javacUnit.getSourceFile(); String source = sourceFile.getCharContent(false).toString(); String mainTypeName = FileUtil.getMainTypeName(sourceFile); CompilationUnit unit = new CompilationUnit(new TranslationEnvironment(env), sourceFilePath, mainTypeName, source); PackageElement pkg = javacUnit.packge != null ? javacUnit.packge : env.defaultPackage(); unit.setPackage(converter.convertPackage(pkg)); for (JCTree type : javacUnit.getTypeDecls()) { unit.addType((AbstractTypeDeclaration) converter.convert(type)); } addOcniComments(unit); return unit; } catch (IOException e) { ErrorUtil.fatalError(e, sourceFilePath); return null; } } private TreeConverter(JCTree.JCCompilationUnit javacUnit) { unit = javacUnit; } private TreeNode convert(Object obj) { if (obj == null) { return null; } JCTree node = (JCTree) obj; TreeNode newNode = convertInner(node) .setPosition(getPosition(node)); newNode.validate(); return newNode; } private SourcePosition getPosition(JCTree node) { int startPosition = TreeInfo.getStartPos(node); int endPosition = TreeInfo.getEndPos(node, unit.endPositions); int length = startPosition == Position.NOPOS || endPosition == Position.NOPOS ? 0 : endPosition - startPosition; if (unit.getLineMap() != null) { int line = unit.getLineMap().getLineNumber(startPosition); return new SourcePosition(startPosition, length, line); } else { return new SourcePosition(startPosition, length); } } @SuppressWarnings("fallthrough") private TreeNode convertInner(JCTree javacNode) { switch (javacNode.getKind()) { default: throw new AssertionError("Unknown node type: " + javacNode.getKind()); case ANNOTATION: return convertAnnotation((JCTree.JCAnnotation) javacNode); case ANNOTATION_TYPE: return convertAnnotationTypeDeclaration((JCTree.JCClassDecl) javacNode); case ARRAY_ACCESS: return convertArrayAccess((JCTree.JCArrayAccess) javacNode); case ARRAY_TYPE: return convertArrayType((JCTree.JCArrayTypeTree) javacNode); case ASSERT: return convertAssert((JCTree.JCAssert) javacNode); case ASSIGNMENT: return convertAssignment((JCTree.JCAssign) javacNode); case BLOCK: return convertBlock((JCTree.JCBlock) javacNode); case BREAK: return convertBreakStatement((JCTree.JCBreak) javacNode); case CASE: return convertCase((JCTree.JCCase) javacNode); case CATCH: return convertCatch((JCTree.JCCatch) javacNode); case CLASS: return convertClassDeclaration((JCTree.JCClassDecl) javacNode); case COMPILATION_UNIT: throw new AssertionError( "CompilationUnit must be converted using convertCompilationUnit()"); case CONDITIONAL_EXPRESSION: return convertConditionalExpression((JCTree.JCConditional) javacNode); case CONTINUE: return convertContinueStatement((JCTree.JCContinue) javacNode); case DO_WHILE_LOOP: return convertDoStatement((JCTree.JCDoWhileLoop) javacNode); case EMPTY_STATEMENT: return new EmptyStatement(); case ENHANCED_FOR_LOOP: return convertEnhancedForStatement((JCTree.JCEnhancedForLoop) javacNode); case ENUM: return convertEnum((JCTree.JCClassDecl) javacNode); case EXPRESSION_STATEMENT: return convertExpressionStatement((JCTree.JCExpressionStatement) javacNode); case FOR_LOOP: return convertForLoop((JCTree.JCForLoop) javacNode); case IDENTIFIER: return convertIdent((JCTree.JCIdent) javacNode); case INSTANCE_OF: return convertInstanceOf((JCTree.JCInstanceOf) javacNode); case INTERFACE: return convertClassDeclaration((JCTree.JCClassDecl) javacNode); case IF: return convertIf((JCTree.JCIf) javacNode); case LABELED_STATEMENT: return convertLabeledStatement((JCTree.JCLabeledStatement) javacNode); case LAMBDA_EXPRESSION: return convertLambda((JCTree.JCLambda) javacNode); case MEMBER_REFERENCE: return convertMemberReference((JCTree.JCMemberReference) javacNode); case MEMBER_SELECT: return convertFieldAccess((JCTree.JCFieldAccess) javacNode); case METHOD: return convertMethodDeclaration((JCTree.JCMethodDecl) javacNode); case METHOD_INVOCATION: return convertMethodInvocation((JCTree.JCMethodInvocation) javacNode); case NEW_ARRAY: return convertNewArray((JCTree.JCNewArray) javacNode); case NEW_CLASS: return convertNewClass((JCTree.JCNewClass) javacNode); case PARAMETERIZED_TYPE: return convertTypeApply((JCTree.JCTypeApply) javacNode); case PARENTHESIZED: return convertParens((JCTree.JCParens) javacNode); case PRIMITIVE_TYPE: return convertPrimitiveType((JCTree.JCPrimitiveTypeTree) javacNode); case RETURN: return convertReturn((JCTree.JCReturn) javacNode); case SWITCH: return convertSwitch((JCTree.JCSwitch) javacNode); case THROW: return convertThrow((JCTree.JCThrow) javacNode); case TRY: return convertTry((JCTree.JCTry) javacNode); case TYPE_CAST: return convertTypeCast((JCTree.JCTypeCast) javacNode); case VARIABLE: return convertVariableDeclaration((JCTree.JCVariableDecl) javacNode); case WHILE_LOOP: return convertWhileLoop((JCTree.JCWhileLoop) javacNode); case BOOLEAN_LITERAL: return convertBooleanLiteral((JCTree.JCLiteral) javacNode); case CHAR_LITERAL: return convertCharLiteral((JCTree.JCLiteral) javacNode); case DOUBLE_LITERAL: case FLOAT_LITERAL: case INT_LITERAL: case LONG_LITERAL: return convertNumberLiteral((JCTree.JCLiteral) javacNode); case STRING_LITERAL: return convertStringLiteral((JCTree.JCLiteral) javacNode); case SYNCHRONIZED: return convertSynchronized((JCTree.JCSynchronized) javacNode); case NULL_LITERAL: return new NullLiteral(((JCTree.JCLiteral) javacNode).type); case AND: case CONDITIONAL_AND: case CONDITIONAL_OR: case DIVIDE: case EQUAL_TO: case GREATER_THAN: case GREATER_THAN_EQUAL: case LEFT_SHIFT: case LESS_THAN: case LESS_THAN_EQUAL: case MINUS: case MULTIPLY: case NOT_EQUAL_TO: case OR: case PLUS: case REMAINDER: case RIGHT_SHIFT: case UNSIGNED_RIGHT_SHIFT: case XOR: return convertBinary((JCTree.JCBinary) javacNode); case BITWISE_COMPLEMENT: case LOGICAL_COMPLEMENT: case PREFIX_DECREMENT: case PREFIX_INCREMENT: case UNARY_MINUS: case UNARY_PLUS: return convertPrefixExpr((JCTree.JCUnary) javacNode); case POSTFIX_DECREMENT: case POSTFIX_INCREMENT: return convertPostExpr((JCTree.JCUnary) javacNode); case AND_ASSIGNMENT: case DIVIDE_ASSIGNMENT: case LEFT_SHIFT_ASSIGNMENT: case MINUS_ASSIGNMENT: case MULTIPLY_ASSIGNMENT: case OR_ASSIGNMENT: case PLUS_ASSIGNMENT: case REMAINDER_ASSIGNMENT: case RIGHT_SHIFT_ASSIGNMENT: case UNSIGNED_RIGHT_SHIFT_ASSIGNMENT: case XOR_ASSIGNMENT: return convertAssignOp((JCTree.JCAssignOp) javacNode); case OTHER: { if (javacNode.hasTag(Tag.NULLCHK)) { // Skip javac's nullchk operators, since j2objc provides its own. // TODO(tball): convert to nil_chk() functions in this class, to // always check references that javac flagged? return convert(((JCTree.JCUnary) javacNode).arg); } throw new AssertionError("Unknown OTHER node, tag: " + javacNode.getTag()); } } } private TreeNode convertAbstractTypeDeclaration( JCTree.JCClassDecl node, AbstractTypeDeclaration newNode) { convertBodyDeclaration(node, newNode); List<BodyDeclaration> bodyDeclarations = new ArrayList<>(); for (JCTree bodyDecl : node.getMembers()) { // Skip synthetic methods. Synthetic default constructors are not marked // synthetic for backwards-compatibility reasons, so they are detected // by a source position that's the same as their declaring class. // TODO(tball): keep synthetic default constructors after front-end switch, // and get rid of DefaultConstructorAdder translator. if (bodyDecl.getKind() == Kind.METHOD && (ElementUtil.isSynthetic(((JCTree.JCMethodDecl) bodyDecl).sym) || bodyDecl.pos == node.pos)) { continue; } Object member = convert(bodyDecl); if (member instanceof BodyDeclaration) { // Not true for enum constants. bodyDeclarations.add((BodyDeclaration) member); } } return newNode .setName(convertSimpleName(node.sym)) .setTypeElement(node.sym) .setBodyDeclarations(bodyDeclarations); } private TreeNode convertAnnotation(JCTree.JCAnnotation node) { List<JCTree.JCExpression> args = node.getArguments(); Annotation newNode; if (args.isEmpty()) { newNode = new MarkerAnnotation() .setAnnotationMirror(node.attribute); } else if (args.size() == 1) { String annotationName = node.getAnnotationType().toString(); if (annotationName.equals(Property.class.getSimpleName()) || annotationName.equals(Property.class.getName())) { newNode = new PropertyAnnotation(); //TODO(tball): parse property attribute string. throw new AssertionError("not implemented"); } else { newNode = new SingleMemberAnnotation() .setValue((Expression) convert(args.get(0))); } } else { NormalAnnotation normalAnn = new NormalAnnotation(); for (JCTree.JCExpression obj : node.getArguments()) { JCTree.JCAssign assign = (JCTree.JCAssign) obj; MemberValuePair memberPair = new MemberValuePair() .setName(convertSimpleName(((JCTree.JCIdent) assign.lhs).sym)) .setValue((Expression) convert(assign.rhs)); normalAnn.addValue(memberPair); } newNode = normalAnn; } return newNode .setAnnotationMirror(node.attribute) .setTypeName((Name) convert(node.getAnnotationType())); } private TreeNode convertAnnotationTypeDeclaration(JCTree.JCClassDecl node) { AnnotationTypeDeclaration newNode = new AnnotationTypeDeclaration(); convertBodyDeclaration(node, newNode); for (JCTree bodyDecl : node.getMembers()) { if (bodyDecl.getKind() == Kind.METHOD) { JCTree.JCMethodDecl methodDecl = (JCTree.JCMethodDecl) bodyDecl; AnnotationTypeMemberDeclaration newMember = new AnnotationTypeMemberDeclaration() .setName(convertSimpleName(methodDecl.sym)) .setDefault((Expression) convert(methodDecl.defaultValue)) .setExecutableElement(methodDecl.sym) .setType(Type.newType(methodDecl.sym.getReturnType())); List<Annotation> annotations = new ArrayList<>(); for (AnnotationTree annotation : methodDecl.mods.annotations) { annotations.add((Annotation) convert(annotation)); } newMember .setModifiers((int) methodDecl.getModifiers().flags) .setAnnotations(annotations) .setJavadoc((Javadoc) getAssociatedJavaDoc(methodDecl)); newNode.addBodyDeclaration(newMember); } else { newNode.addBodyDeclaration((BodyDeclaration) convert(bodyDecl)); } } return newNode .setName(convertSimpleName(node.sym)) .setTypeElement(node.sym); } private TreeNode convertArrayAccess(JCTree.JCArrayAccess node) { return new ArrayAccess() .setArray((Expression) convert(node.getExpression())) .setIndex((Expression) convert(node.getIndex())); } private TreeNode convertArrayType(JCTree.JCArrayTypeTree node) { ArrayType newNode = new ArrayType(); convertType(node, newNode); Type componentType = (Type) Type.newType(node.getType().type); return newNode.setComponentType(componentType); } private TreeNode convertAssert(JCTree.JCAssert node) { return new AssertStatement() .setExpression((Expression) convert(node.getCondition())) .setMessage((Expression) convert(node.getDetail())); } private TreeNode convertAssignment(JCTree.JCAssign node) { Assignment newNode = new Assignment(); convertExpression(node, newNode); return newNode .setOperator(Assignment.Operator.ASSIGN) .setLeftHandSide((Expression) convert(node.getVariable())) .setRightHandSide((Expression) convert(node.getExpression())); } private TreeNode convertAssignOp(JCTree.JCAssignOp node) { Assignment newNode = new Assignment(); convertExpression(node, newNode); String operatorName = node.getOperator().getSimpleName().toString() + "="; return newNode .setOperator(Assignment.Operator.fromJdtOperatorName(operatorName)) .setLeftHandSide((Expression) convert(node.getVariable())) .setRightHandSide((Expression) convert(node.getExpression())); } private TreeNode convertBinary(JCTree.JCBinary node) { return new InfixExpression() .setTypeMirror(node.type) .setOperator(InfixExpression.Operator.parse(node.operator.name.toString())) .addOperand((Expression) convert(node.getLeftOperand())) .addOperand((Expression) convert(node.getRightOperand())); } private TreeNode convertBlock(JCTree.JCBlock node) { Block newNode = new Block(); for (StatementTree stmt : node.getStatements()) { TreeNode tree = convert(stmt); if (tree instanceof AbstractTypeDeclaration) { tree = new TypeDeclarationStatement().setDeclaration((AbstractTypeDeclaration) tree); } newNode.addStatement((Statement) tree); } return newNode; } private TreeNode convertBodyDeclaration(JCTree.JCClassDecl node, BodyDeclaration newNode) { List<Annotation> annotations = new ArrayList<>(); for (AnnotationTree annotation : node.getModifiers().getAnnotations()) { annotations.add((Annotation) convert(annotation)); } return newNode .setModifiers((int) node.getModifiers().flags) .setAnnotations(annotations) .setJavadoc((Javadoc) getAssociatedJavaDoc(node)); } private TreeNode convertBooleanLiteral(JCTree.JCLiteral node) { return new BooleanLiteral((Boolean) node.getValue(), node.type); } private TreeNode convertBreakStatement(JCTree.JCBreak node) { BreakStatement newNode = new BreakStatement(); newNode.setLabel((SimpleName) convert(node.getLabel())); return newNode; } private TreeNode convertCase(JCTree.JCCase node) { // Case statements are converted in convertSwitch(). return new SwitchCase() .setExpression((Expression) convert(node.getExpression())); } private TreeNode convertCatch(JCTree.JCCatch node) { return new CatchClause() .setException((SingleVariableDeclaration) convert(node.getParameter())) .setBody((Block) convert(node.getBlock())); } private TreeNode convertCharLiteral(JCTree.JCLiteral node) { return new CharacterLiteral((Character) node.getValue(), node.type); } private TreeNode convertClassDeclaration(JCTree.JCClassDecl node) { // javac defines all type declarations with JCClassDecl, so differentiate here // to support our different declaration nodes. if (node.sym.isAnonymous()) { AnonymousClassDeclaration newNode = new AnonymousClassDeclaration(); for (JCTree bodyDecl : node.getMembers()) { Object member = convert(bodyDecl); if (member instanceof BodyDeclaration) { // Not true for enum constants. newNode.addBodyDeclaration((BodyDeclaration) member); } } return newNode.setTypeElement(node.sym); } if (node.sym.getKind() == ElementKind.ANNOTATION_TYPE) { throw new AssertionError("Annotation type declaration tree conversion not implemented"); } TypeDeclaration newNode = (TypeDeclaration) convertAbstractTypeDeclaration(node, new TypeDeclaration()); JCTree.JCExpression extendsClause = node.getExtendsClause(); if (extendsClause != null) { newNode.setSuperclassType(Type.newType(nameType((node.getExtendsClause())))); } newNode.setInterface( node.getKind() == Kind.INTERFACE || node.getKind() == Kind.ANNOTATION_TYPE); for (JCTree superInterface : node.getImplementsClause()) { newNode.addSuperInterfaceType(Type.newType(nameType(superInterface))); } return newNode; } private TreeNode convertConditionalExpression(JCTree.JCConditional node) { return new ConditionalExpression() .setTypeMirror(node.type) .setExpression((Expression) convert(node.getCondition())) .setThenExpression((Expression) convert(node.getTrueExpression())) .setElseExpression((Expression) convert(node.getFalseExpression())); } private TreeNode convertContinueStatement(JCTree.JCContinue node) { return new ContinueStatement() .setLabel((SimpleName) convert(node.getLabel())); } private TreeNode convertDoStatement(JCTree.JCDoWhileLoop node) { return new DoStatement() .setExpression((Expression) convert(node.getCondition())) .setBody((Statement) convert(node.getStatement())); } private TreeNode convertEnhancedForStatement(JCTree.JCEnhancedForLoop node) { return new EnhancedForStatement() .setParameter((SingleVariableDeclaration) convertSingleVariable(node.getVariable())) .setExpression((Expression) convert(node.getExpression())) .setBody((Statement) convert(node.getStatement())); } private TreeNode convertEnum(JCTree.JCClassDecl node) { if (node.sym.isAnonymous()) { return (AnonymousClassDeclaration) convertClassDeclaration(node); } EnumDeclaration newNode = (EnumDeclaration) new EnumDeclaration() .setName(convertSimpleName(node.sym)) .setTypeElement(node.sym); for (JCTree superInterface : node.getImplementsClause()) { newNode.addSuperInterfaceType(Type.newType(nameType(superInterface))); } for (JCTree bodyDecl : node.getMembers()) { if (bodyDecl.getKind() == Kind.VARIABLE) { TreeNode var = convertVariableDeclaration((JCTree.JCVariableDecl) bodyDecl); if (var.getKind() == TreeNode.Kind.ENUM_CONSTANT_DECLARATION) { newNode.addEnumConstant((EnumConstantDeclaration) var); } else { newNode.addBodyDeclaration((BodyDeclaration) var); } } else if (bodyDecl.getKind() == Kind.METHOD) { MethodDeclaration method = (MethodDeclaration) convertMethodDeclaration((JCTree.JCMethodDecl) bodyDecl); if (ElementUtil.isConstructor(method.getExecutableElement()) && !method.getBody().getStatements().isEmpty()){ // Remove bogus "super()" call from constructors, so InitializationNormalizer // adds the correct super call that includes the ordinal and name arguments. Statement stmt = method.getBody().getStatements().get(0); if (stmt.getKind() == TreeNode.Kind.SUPER_CONSTRUCTOR_INVOCATION) { SuperConstructorInvocation call = (SuperConstructorInvocation) stmt; if (call.getArguments().isEmpty()) { method.getBody().getStatements().remove(0); } } } newNode.addBodyDeclaration(method); } else { newNode.addBodyDeclaration((BodyDeclaration) convert(bodyDecl)); } } return newNode; } private TreeNode convertExpression( JCTree.JCExpression node, Expression newNode) { return newNode .setConstantValue(node.type.constValue()); } private TreeNode convertExpressionStatement(JCTree.JCExpressionStatement node) { TreeNode expr = convert(node.getExpression()); if (expr instanceof Statement) { return expr; } return new ExpressionStatement().setExpression((Expression) expr); } private TreeNode convertFieldAccess(JCTree.JCFieldAccess node) { String fieldName = node.name.toString(); JCTree.JCExpression selected = node.getExpression(); if (fieldName.equals("this")) { return new ThisExpression() .setQualifier((Name) convert(selected)) .setTypeMirror(node.sym.asType()); } if (selected.toString().equals("super")) { return new SuperFieldAccess() .setVariableElement((VariableElement) node.sym) .setName(new SimpleName(node.sym, node.type)); } if (node.getIdentifier().toString().equals("class")) { // For Foo.class the type is Class<Foo>, so use the type argument as the // TypeLiteral type. com.sun.tools.javac.code.Type type = node.sym.asType(); return new TypeLiteral(type) .setType(Type.newType(type.getTypeArguments().get(0))); } if (selected.getKind() == Kind.IDENTIFIER) { return new QualifiedName() .setName(new SimpleName(node.sym, node.type)) .setQualifier(new SimpleName(((JCTree.JCIdent) selected).sym)) .setElement(node.sym); } if (selected.getKind() == Kind.MEMBER_SELECT) { return new QualifiedName() .setName(new SimpleName(node.sym, node.type)) .setQualifier(convertName(((JCTree.JCFieldAccess) selected).sym)) .setElement(node.sym); } return new FieldAccess() .setVariableElement((VariableElement) node.sym) .setExpression((Expression) convert(selected)) .setName(new SimpleName(node.sym, node.type)); } private TreeNode convertForLoop(JCTree.JCForLoop node) { ForStatement newNode = new ForStatement() .setExpression((Expression) convert(node.getCondition())) .setBody((Statement) convert(node.getStatement())); for (JCTree.JCStatement initializer : node.getInitializer()) { if (initializer.getKind() == Kind.VARIABLE) { JCTree.JCVariableDecl var = (JCTree.JCVariableDecl) initializer; newNode.addInitializer((Expression) convertVariableExpression(var)); } else { assert initializer.getKind() == Kind.EXPRESSION_STATEMENT; newNode.addInitializer((Expression) convert(((JCTree.JCExpressionStatement) initializer).getExpression())); } } for (JCTree.JCExpressionStatement updater : node.getUpdate()) { newNode.addUpdater((Expression) convert(updater.getExpression())); } return newNode; } private TreeNode convertFunctionalExpression(JCTree.JCFunctionalExpression node, FunctionalExpression newNode) { convertExpression(node, newNode); for (TypeMirror type : node.targets) { newNode.addTargetType(type); } return newNode.setTypeMirror(node.type); } private TreeNode convertIdent(JCTree.JCIdent node) { return new SimpleName(node.sym, node.type); } private TreeNode convertIf(JCTree.JCIf node) { Expression condition = (Expression) convert(node.getCondition()); if (condition.getKind() == TreeNode.Kind.PARENTHESIZED_EXPRESSION) { condition = TreeUtil.remove(((ParenthesizedExpression) condition).getExpression()); } return new IfStatement() .setExpression(condition) .setThenStatement((Statement) convert(node.getThenStatement())) .setElseStatement((Statement) convert(node.getElseStatement())); } private TreeNode convertInstanceOf(JCTree.JCInstanceOf node) { TypeMirror clazz = nameType(node.getType()); return new InstanceofExpression() .setLeftOperand((Expression) convert(node.getExpression())) .setRightOperand(Type.newType(clazz)); } private TreeNode convertLabeledStatement(JCTree.JCLabeledStatement node) { return new LabeledStatement() .setLabel(new SimpleName(node.label.toString())); } private TreeNode convertLambda(JCTree.JCLambda node) { LambdaExpression newNode = new LambdaExpression(); convertFunctionalExpression(node, newNode); for (JCVariableDecl param : node.params) { newNode.addParameter((VariableDeclaration) convert(param)); } return newNode.setBody(convert(node.getBody())); } private TreeNode convertMethodReference(JCTree.JCMemberReference node, MethodReference newNode) { convertFunctionalExpression(node, newNode); if (node.getTypeArguments() != null) { for (Object typeArg : node.getTypeArguments()) { newNode.addTypeArgument((Type) convert(typeArg)); } } return newNode // TODO(tball): Add the appropriate ExecutableType. .setExecutablePair(new ExecutablePair((ExecutableElement) node.sym, null)); } private TreeNode convertMemberReference(JCTree.JCMemberReference node) { Element element = node.sym; if (ElementUtil.isConstructor(element)) { CreationReference newNode = new CreationReference(); convertMethodReference(node, newNode); return newNode .setType(Type.newType(nameType(node.expr))); } if (node.hasKind(JCTree.JCMemberReference.ReferenceKind.SUPER)) { SuperMethodReference newNode = new SuperMethodReference(); convertMethodReference(node, newNode); // Qualifier expression is <name>."super", so it's always a JCFieldAccess. JCTree.JCFieldAccess expr = (JCTree.JCFieldAccess) node.getQualifierExpression(); return newNode .setName(convertSimpleName(node.sym)) .setQualifier(convertSimpleName(nameSymbol(expr.selected))); } if (node.hasKind(JCTree.JCMemberReference.ReferenceKind.UNBOUND) || node.hasKind(JCTree.JCMemberReference.ReferenceKind.STATIC)) { TypeMethodReference newNode = new TypeMethodReference(); convertMethodReference(node, newNode); return newNode .setName(convertSimpleName(node.sym)) .setType(convertType(node.type, false)); } ExpressionMethodReference newNode = new ExpressionMethodReference(); convertMethodReference(node, newNode); return newNode .setName(convertSimpleName(node.sym)) .setExpression((Expression) convert(node.getQualifierExpression())); } private TreeNode convertMethodDeclaration(JCTree.JCMethodDecl node) { MethodDeclaration newNode = new MethodDeclaration(); List<Annotation> annotations = new ArrayList<>(); for (AnnotationTree annotation : node.getModifiers().getAnnotations()) { annotations.add((Annotation) convert(annotation)); } for (JCTree.JCVariableDecl param : node.getParameters()) { newNode.addParameter((SingleVariableDeclaration) convert(param)); } if (ElementUtil.isConstructor(node.sym)) { newNode .setName(convertSimpleName(ElementUtil.getDeclaringClass(node.sym))) .setIsConstructor(true); } else { newNode .setName(convertSimpleName(node.sym)) .setReturnType(Type.newType(node.type.asMethodType().getReturnType())); } return newNode .setExecutableElement(node.sym) .setBody((Block) convert(node.getBody())) .setModifiers((int) node.getModifiers().flags) .setAnnotations(annotations) .setJavadoc((Javadoc) getAssociatedJavaDoc(node)); } private TreeNode convertMethodInvocation(JCTree.JCMethodInvocation node) { JCTree.JCExpression method = node.getMethodSelect(); if (method.getKind() == Kind.IDENTIFIER) { ExecutableElement element = (ExecutableElement) ((JCTree.JCIdent) method).sym; if (method.toString().equals("this")) { ConstructorInvocation newNode = new ConstructorInvocation() .setExecutablePair(new ExecutablePair(element, (ExecutableType) element.asType())); for (JCTree.JCExpression arg : node.getArguments()) { newNode.addArgument((Expression) convert(arg)); } return newNode; } if (method.toString().equals("super")) { SuperConstructorInvocation newNode = new SuperConstructorInvocation() .setExecutablePair(new ExecutablePair(element, (ExecutableType) element.asType())); for (JCTree.JCExpression arg : node.getArguments()) { newNode.addArgument((Expression) convert(arg)); } // If there's no expression node, javac sets it to be "<init>" which we don't want. Expression expr = ((Expression) convert(method)); if (!expr.toString().equals("<init>")) { newNode.setExpression(expr); } return newNode; } } if (method.getKind() == Kind.MEMBER_SELECT && ((JCTree.JCFieldAccess) method).name.toString().equals("super")) { ExecutableElement sym = (ExecutableElement) ((JCTree.JCFieldAccess) method).sym; SuperConstructorInvocation newNode = new SuperConstructorInvocation() .setExecutablePair(new ExecutablePair(sym, (ExecutableType) sym.asType())) .setExpression((Expression) convert(method)); for (JCTree.JCExpression arg : node.getArguments()) { newNode.addArgument((Expression) convert(arg)); } return newNode; } MethodInvocation newNode = new MethodInvocation(); ExecutableElement sym; if (method.getKind() == Kind.IDENTIFIER) { sym = (ExecutableElement) ((JCTree.JCIdent) method).sym; newNode .setName((SimpleName) convert(method)) .setExecutablePair(new ExecutablePair(sym, (ExecutableType) sym.asType())); } else { JCTree.JCFieldAccess select = (JCTree.JCFieldAccess) method; sym = (ExecutableElement) select.sym; newNode .setName(convertSimpleName(select.sym)) .setExpression((Expression) convert(select.selected)); } for (JCTree.JCExpression arg : node.getArguments()) { newNode.addArgument((Expression) convert(arg)); } return newNode .setTypeMirror(node.type) .setExecutablePair(new ExecutablePair(sym, (ExecutableType) sym.asType())); } private SimpleName convertSimpleName(Element element) { return new SimpleName(element); } private Name convertName(Symbol symbol) { if (symbol.owner == null || symbol.owner.name.isEmpty()) { return new SimpleName(symbol); } return new QualifiedName(symbol, symbol.asType(), convertName(symbol.owner)); } private TreeNode convertNewArray(JCTree.JCNewArray node) { ArrayCreation newNode = new ArrayCreation(); convertExpression(node, newNode); List<Expression> dimensions = new ArrayList<>(); for (JCTree.JCExpression dimension : node.getDimensions()) { dimensions.add((Expression) convert(dimension)); } javax.lang.model.type.ArrayType type = (javax.lang.model.type.ArrayType) node.type; if (node.getInitializers() != null) { ArrayInitializer initializers = new ArrayInitializer(type); for (JCTree.JCExpression initializer : node.getInitializers()) { initializers.addExpression((Expression) convert(initializer)); } newNode.setInitializer(initializers); } return newNode .setType(new ArrayType(type)) .setDimensions(dimensions); } private TreeNode convertNewClass(JCTree.JCNewClass node) { ClassInstanceCreation newNode = new ClassInstanceCreation(); convertExpression(node, newNode); for (JCTree.JCExpression arg : node.getArguments()) { newNode.addArgument((Expression) convert(arg)); } return newNode .setExecutablePair(new ExecutablePair( (ExecutableElement) node.constructor, node.constructorType.asMethodType())) .setExpression((Expression) convert(node.getEnclosingExpression())) .setType(Type.newType(node.type)) .setAnonymousClassDeclaration((AnonymousClassDeclaration) convert(node.def)); } private TreeNode convertNumberLiteral(JCTree.JCLiteral node) { return new NumberLiteral((Number) node.getValue(), node.type) .setToken(getTreeSource(node)); } private PackageDeclaration convertPackage(PackageElement pkg) { PackageDeclaration newNode = new PackageDeclaration() .setPackageElement(pkg); return newNode.setName(convertName((PackageSymbol) pkg)); } private TreeNode convertPrefixExpr(JCTree.JCUnary node) { return new PrefixExpression() .setTypeMirror(node.type) .setOperator(PrefixExpression.Operator.parse(node.getOperator().name.toString())) .setOperand((Expression) convert(node.getExpression())); } private TreeNode convertParens(JCTree.JCParens node) { return new ParenthesizedExpression() .setExpression((Expression) convert(node.getExpression())); } private TreeNode convertPostExpr(JCTree.JCUnary node) { return new PostfixExpression() .setOperator(PostfixExpression.Operator.parse(node.getOperator().name.toString())) .setOperand((Expression) convert(node.getExpression())); } private TreeNode convertPrimitiveType(JCTree.JCPrimitiveTypeTree node) { return new PrimitiveType(node.type); } private TreeNode convertReturn(JCTree.JCReturn node) { return new ReturnStatement((Expression) convert(node.getExpression())); } private TreeNode convertStringLiteral(JCTree.JCLiteral node) { return new StringLiteral((String) node.getValue(), node.type); } private TreeNode convertSwitch(JCTree.JCSwitch node) { SwitchStatement newNode = new SwitchStatement() .setExpression((Expression) convert(node.getExpression())); for (JCTree.JCCase switchCase : node.getCases()) { newNode.addStatement((SwitchCase) convert(switchCase)); for (JCTree.JCStatement s : switchCase.getStatements()) { newNode.addStatement((Statement) convert(s)); } } return newNode; } private TreeNode convertSynchronized(JCTree.JCSynchronized node) { return new SynchronizedStatement() .setExpression((Expression) convert(node.getExpression())) .setBody((Block) convertBlock(node.getBlock())); } private TreeNode convertThrow(JCTree.JCThrow node) { return new ThrowStatement() .setExpression((Expression) convert(node.getExpression())); } private TreeNode convertTry(JCTree.JCTry node) { TryStatement newNode = new TryStatement(); for (Object obj : node.getResources()) { newNode.addResource(convertVariableExpression((JCTree.JCVariableDecl) obj)); } for (Object obj : node.getCatches()) { newNode.addCatchClause((CatchClause) convert(obj)); } return newNode .setBody((Block) convert(node.getBlock())) .setFinally((Block) convert(node.getFinallyBlock())); } private TreeNode convertType(JCTree.JCExpression node, Type newType) { return newType .setTypeMirror(node.type); } private TypeMirror nameType(JCTree node) { if (node.getKind() == Kind.PARAMETERIZED_TYPE) { return ((JCTree.JCTypeApply) node).clazz.type; } if (node.getKind() == Kind.ARRAY_TYPE) { return ((JCTree.JCArrayTypeTree) node).type; } return nameSymbol(node).asType(); } private Symbol nameSymbol(JCTree node) { return node.getKind() == Kind.MEMBER_SELECT ? ((JCTree.JCFieldAccess) node).sym : ((JCTree.JCIdent) node).sym; } private TreeNode convertTypeApply(JCTree.JCTypeApply node) { return new ParameterizedType() .setType(Type.newType(node.type)) .setTypeMirror(node.type); } private TreeNode convertTypeCast(JCTree.JCTypeCast node) { return new CastExpression(node.type, (Expression) convert(node.getExpression())); } private TreeNode convertVariableDeclaration(JCTree.JCVariableDecl node) { VarSymbol var = node.sym; if (var.getKind() == ElementKind.FIELD) { return new FieldDeclaration(var, (Expression) convert(node.getInitializer())); } if (var.getKind() == ElementKind.LOCAL_VARIABLE) { return new VariableDeclarationStatement(var, (Expression) convert(node.getInitializer())) .setType(convertType(var.asType(), false)); } if (var.getKind() == ElementKind.ENUM_CONSTANT) { EnumConstantDeclaration newNode = new EnumConstantDeclaration() .setName(convertSimpleName(var)) .setVariableElement(var); ClassInstanceCreation init = (ClassInstanceCreation) convert(node.getInitializer()); TreeUtil.copyList(init.getArguments(), newNode.getArguments()); if (init.getAnonymousClassDeclaration() != null) { newNode.setAnonymousClassDeclaration(TreeUtil.remove(init.getAnonymousClassDeclaration())); } return newNode .setExecutablePair(init.getExecutablePair()); } return convertSingleVariable(node); } private TreeNode convertSingleVariable(JCTree.JCVariableDecl node) { VarSymbol var = node.sym; boolean isVarargs = (node.sym.flags() & Flags.VARARGS) > 0; Type newType = convertType(var.asType(), isVarargs); return new SingleVariableDeclaration() .setType(newType) .setIsVarargs(isVarargs) .setName(convertSimpleName(var)) .setVariableElement(var) .setInitializer((Expression) convert(node.getInitializer())); } private Type convertType(TypeMirror varType, boolean isVarargs) { Type newType; if (isVarargs) { newType = Type.newType(((javax.lang.model.type.ArrayType) varType).getComponentType()); } else { if (varType.getKind() == TypeKind.DECLARED && !((DeclaredType) varType).getTypeArguments().isEmpty()) { newType = new ParameterizedType() .setType(new SimpleType(varType)) .setTypeMirror(varType); } else { newType = Type.newType(varType); } } return newType; } private VariableDeclarationExpression convertVariableExpression(JCTree.JCVariableDecl node) { VarSymbol var = node.sym; boolean isVarargs = (node.sym.flags() & Flags.VARARGS) > 0; Type newType = convertType(var.asType(), isVarargs); VariableDeclarationFragment fragment = new VariableDeclarationFragment(); fragment .setName(convertSimpleName(var)) .setVariableElement(var) .setInitializer((Expression) convert(node.getInitializer())); return new VariableDeclarationExpression() .setType(newType) .addFragment(fragment); } private TreeNode convertWhileLoop(JCTree.JCWhileLoop node) { return new WhileStatement() .setExpression((Expression) convert(node.getCondition())) .setBody((Statement) convert(node.getStatement())); } private TreeNode getAssociatedJavaDoc(JCTree node) { Comment comment = convertAssociatedComment(node); return comment != null && comment.isDocComment() ? comment : null; } private Comment convertAssociatedComment(JCTree node) { DocCommentTable docComments = unit.docComments; if (docComments == null || !docComments.hasComment(node)) { return null; } com.sun.tools.javac.parser.Tokens.Comment javacComment = docComments.getComment(node); Comment comment; switch (javacComment.getStyle()) { case BLOCK: comment = new BlockComment(); break; case JAVADOC: comment = new Javadoc(); break; case LINE: comment = new LineComment(); break; default: throw new AssertionError("unknown comment type"); } int startPos = javacComment.getSourcePos(0); int endPos = startPos + javacComment.getText().length(); comment.setSourceRange(startPos, endPos); return comment; } private static void addOcniComments(CompilationUnit unit) { // Can't use a regex because it will greedily include everything between // the first and last closing pattern, resulting in a single comment node. String source = unit.getSource(); int startPos = 0; int endPos = 0; while ((startPos = source.indexOf("/*-[", endPos)) > -1) { endPos = source.indexOf("]-*/", startPos); if (endPos > startPos) { endPos += 4; // Include closing delimiter. BlockComment ocniComment = new BlockComment(); ocniComment.setSourceRange(startPos, endPos); unit.getCommentList().add(ocniComment); } } } private static String getPath(JavaFileObject file) { String uri = file.toUri().toString(); if (uri.startsWith("mem:/")) { // MemoryFileObject needs a custom file system for URI to return the // correct path, so the URI string is split instead. return uri.substring(5); } return file.toUri().getPath(); } private String getTreeSource(JCTree node) { try { CharSequence source = unit.getSourceFile().getCharContent(true); return source.subSequence(node.getStartPosition(), node.getEndPosition(unit.endPositions)) .toString(); } catch (IOException e) { return node.toString(); } } }
translator/src/main/java/com/google/devtools/j2objc/javac/TreeConverter.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.j2objc.javac; import com.google.devtools.j2objc.ast.AbstractTypeDeclaration; import com.google.devtools.j2objc.ast.Annotation; import com.google.devtools.j2objc.ast.AnnotationTypeDeclaration; import com.google.devtools.j2objc.ast.AnnotationTypeMemberDeclaration; import com.google.devtools.j2objc.ast.AnonymousClassDeclaration; import com.google.devtools.j2objc.ast.ArrayAccess; import com.google.devtools.j2objc.ast.ArrayCreation; import com.google.devtools.j2objc.ast.ArrayInitializer; import com.google.devtools.j2objc.ast.ArrayType; import com.google.devtools.j2objc.ast.AssertStatement; import com.google.devtools.j2objc.ast.Assignment; import com.google.devtools.j2objc.ast.Block; import com.google.devtools.j2objc.ast.BlockComment; import com.google.devtools.j2objc.ast.BodyDeclaration; import com.google.devtools.j2objc.ast.BooleanLiteral; import com.google.devtools.j2objc.ast.BreakStatement; import com.google.devtools.j2objc.ast.CastExpression; import com.google.devtools.j2objc.ast.CatchClause; import com.google.devtools.j2objc.ast.CharacterLiteral; import com.google.devtools.j2objc.ast.ClassInstanceCreation; import com.google.devtools.j2objc.ast.Comment; import com.google.devtools.j2objc.ast.CompilationUnit; import com.google.devtools.j2objc.ast.ConditionalExpression; import com.google.devtools.j2objc.ast.ConstructorInvocation; import com.google.devtools.j2objc.ast.ContinueStatement; import com.google.devtools.j2objc.ast.CreationReference; import com.google.devtools.j2objc.ast.DoStatement; import com.google.devtools.j2objc.ast.EmptyStatement; import com.google.devtools.j2objc.ast.EnhancedForStatement; import com.google.devtools.j2objc.ast.EnumConstantDeclaration; import com.google.devtools.j2objc.ast.EnumDeclaration; import com.google.devtools.j2objc.ast.Expression; import com.google.devtools.j2objc.ast.ExpressionMethodReference; import com.google.devtools.j2objc.ast.ExpressionStatement; import com.google.devtools.j2objc.ast.FieldAccess; import com.google.devtools.j2objc.ast.FieldDeclaration; import com.google.devtools.j2objc.ast.ForStatement; import com.google.devtools.j2objc.ast.FunctionalExpression; import com.google.devtools.j2objc.ast.IfStatement; import com.google.devtools.j2objc.ast.InfixExpression; import com.google.devtools.j2objc.ast.InstanceofExpression; import com.google.devtools.j2objc.ast.Javadoc; import com.google.devtools.j2objc.ast.LabeledStatement; import com.google.devtools.j2objc.ast.LambdaExpression; import com.google.devtools.j2objc.ast.LineComment; import com.google.devtools.j2objc.ast.MarkerAnnotation; import com.google.devtools.j2objc.ast.MemberValuePair; import com.google.devtools.j2objc.ast.MethodDeclaration; import com.google.devtools.j2objc.ast.MethodInvocation; import com.google.devtools.j2objc.ast.MethodReference; import com.google.devtools.j2objc.ast.Name; import com.google.devtools.j2objc.ast.NormalAnnotation; import com.google.devtools.j2objc.ast.NullLiteral; import com.google.devtools.j2objc.ast.NumberLiteral; import com.google.devtools.j2objc.ast.PackageDeclaration; import com.google.devtools.j2objc.ast.ParameterizedType; import com.google.devtools.j2objc.ast.ParenthesizedExpression; import com.google.devtools.j2objc.ast.PostfixExpression; import com.google.devtools.j2objc.ast.PrefixExpression; import com.google.devtools.j2objc.ast.PrimitiveType; import com.google.devtools.j2objc.ast.PropertyAnnotation; import com.google.devtools.j2objc.ast.QualifiedName; import com.google.devtools.j2objc.ast.ReturnStatement; import com.google.devtools.j2objc.ast.SimpleName; import com.google.devtools.j2objc.ast.SimpleType; import com.google.devtools.j2objc.ast.SingleMemberAnnotation; import com.google.devtools.j2objc.ast.SingleVariableDeclaration; import com.google.devtools.j2objc.ast.SourcePosition; import com.google.devtools.j2objc.ast.Statement; import com.google.devtools.j2objc.ast.StringLiteral; import com.google.devtools.j2objc.ast.SuperConstructorInvocation; import com.google.devtools.j2objc.ast.SuperFieldAccess; import com.google.devtools.j2objc.ast.SuperMethodReference; import com.google.devtools.j2objc.ast.SwitchCase; import com.google.devtools.j2objc.ast.SwitchStatement; import com.google.devtools.j2objc.ast.SynchronizedStatement; import com.google.devtools.j2objc.ast.ThisExpression; import com.google.devtools.j2objc.ast.ThrowStatement; import com.google.devtools.j2objc.ast.TreeNode; import com.google.devtools.j2objc.ast.TreeUtil; import com.google.devtools.j2objc.ast.TryStatement; import com.google.devtools.j2objc.ast.Type; import com.google.devtools.j2objc.ast.TypeDeclaration; import com.google.devtools.j2objc.ast.TypeDeclarationStatement; import com.google.devtools.j2objc.ast.TypeLiteral; import com.google.devtools.j2objc.ast.TypeMethodReference; import com.google.devtools.j2objc.ast.VariableDeclaration; import com.google.devtools.j2objc.ast.VariableDeclarationExpression; import com.google.devtools.j2objc.ast.VariableDeclarationFragment; import com.google.devtools.j2objc.ast.VariableDeclarationStatement; import com.google.devtools.j2objc.ast.WhileStatement; import com.google.devtools.j2objc.types.ExecutablePair; import com.google.devtools.j2objc.util.ElementUtil; import com.google.devtools.j2objc.util.ErrorUtil; import com.google.devtools.j2objc.util.FileUtil; import com.google.devtools.j2objc.util.TranslationEnvironment; import com.google.j2objc.annotations.Property; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.StatementTree; import com.sun.source.tree.Tree.Kind; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.PackageSymbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import com.sun.tools.javac.tree.DocCommentTable; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.tree.JCTree.Tag; import com.sun.tools.javac.tree.TreeInfo; import com.sun.tools.javac.util.Position; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.PackageElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.ExecutableType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.tools.JavaFileObject; /** * Converts a Java AST from the JDT data structure to our J2ObjC data structure. */ public class TreeConverter { private JCTree.JCCompilationUnit unit; public static CompilationUnit convertCompilationUnit( JavacEnvironment env, JCTree.JCCompilationUnit javacUnit) { String sourceFilePath = getPath(javacUnit.getSourceFile()); try { TreeConverter converter = new TreeConverter(javacUnit); JavaFileObject sourceFile = javacUnit.getSourceFile(); String source = sourceFile.getCharContent(false).toString(); String mainTypeName = FileUtil.getMainTypeName(sourceFile); CompilationUnit unit = new CompilationUnit(new TranslationEnvironment(env), sourceFilePath, mainTypeName, source); PackageElement pkg = javacUnit.packge != null ? javacUnit.packge : env.defaultPackage(); unit.setPackage(converter.convertPackage(pkg)); for (JCTree type : javacUnit.getTypeDecls()) { unit.addType((AbstractTypeDeclaration) converter.convert(type)); } addOcniComments(unit); return unit; } catch (IOException e) { ErrorUtil.fatalError(e, sourceFilePath); return null; } } private TreeConverter(JCTree.JCCompilationUnit javacUnit) { unit = javacUnit; } private TreeNode convert(Object obj) { if (obj == null) { return null; } JCTree node = (JCTree) obj; TreeNode newNode = convertInner(node) .setPosition(getPosition(node)); newNode.validate(); return newNode; } private SourcePosition getPosition(JCTree node) { int startPosition = TreeInfo.getStartPos(node); int endPosition = TreeInfo.getEndPos(node, unit.endPositions); int length = startPosition == Position.NOPOS || endPosition == Position.NOPOS ? 0 : endPosition - startPosition; if (unit.getLineMap() != null) { int line = unit.getLineMap().getLineNumber(startPosition); return new SourcePosition(startPosition, length, line); } else { return new SourcePosition(startPosition, length); } } @SuppressWarnings("fallthrough") private TreeNode convertInner(JCTree javacNode) { switch (javacNode.getKind()) { default: throw new AssertionError("Unknown node type: " + javacNode.getKind()); case ANNOTATION: return convertAnnotation((JCTree.JCAnnotation) javacNode); case ANNOTATION_TYPE: return convertAnnotationTypeDeclaration((JCTree.JCClassDecl) javacNode); case ARRAY_ACCESS: return convertArrayAccess((JCTree.JCArrayAccess) javacNode); case ARRAY_TYPE: return convertArrayType((JCTree.JCArrayTypeTree) javacNode); case ASSERT: return convertAssert((JCTree.JCAssert) javacNode); case ASSIGNMENT: return convertAssignment((JCTree.JCAssign) javacNode); case BLOCK: return convertBlock((JCTree.JCBlock) javacNode); case BREAK: return convertBreakStatement((JCTree.JCBreak) javacNode); case CASE: return convertCase((JCTree.JCCase) javacNode); case CATCH: return convertCatch((JCTree.JCCatch) javacNode); case CLASS: return convertClassDeclaration((JCTree.JCClassDecl) javacNode); case COMPILATION_UNIT: throw new AssertionError( "CompilationUnit must be converted using convertCompilationUnit()"); case CONDITIONAL_EXPRESSION: return convertConditionalExpression((JCTree.JCConditional) javacNode); case CONTINUE: return convertContinueStatement((JCTree.JCContinue) javacNode); case DO_WHILE_LOOP: return convertDoStatement((JCTree.JCDoWhileLoop) javacNode); case EMPTY_STATEMENT: return new EmptyStatement(); case ENHANCED_FOR_LOOP: return convertEnhancedForStatement((JCTree.JCEnhancedForLoop) javacNode); case ENUM: return convertEnum((JCTree.JCClassDecl) javacNode); case EXPRESSION_STATEMENT: return convertExpressionStatement((JCTree.JCExpressionStatement) javacNode); case FOR_LOOP: return convertForLoop((JCTree.JCForLoop) javacNode); case IDENTIFIER: return convertIdent((JCTree.JCIdent) javacNode); case INSTANCE_OF: return convertInstanceOf((JCTree.JCInstanceOf) javacNode); case INTERFACE: return convertClassDeclaration((JCTree.JCClassDecl) javacNode); case IF: return convertIf((JCTree.JCIf) javacNode); case LABELED_STATEMENT: return convertLabeledStatement((JCTree.JCLabeledStatement) javacNode); case LAMBDA_EXPRESSION: return convertLambda((JCTree.JCLambda) javacNode); case MEMBER_REFERENCE: return convertMemberReference((JCTree.JCMemberReference) javacNode); case MEMBER_SELECT: return convertFieldAccess((JCTree.JCFieldAccess) javacNode); case METHOD: return convertMethodDeclaration((JCTree.JCMethodDecl) javacNode); case METHOD_INVOCATION: return convertMethodInvocation((JCTree.JCMethodInvocation) javacNode); case NEW_ARRAY: return convertNewArray((JCTree.JCNewArray) javacNode); case NEW_CLASS: return convertNewClass((JCTree.JCNewClass) javacNode); case PARAMETERIZED_TYPE: return convertTypeApply((JCTree.JCTypeApply) javacNode); case PARENTHESIZED: return convertParens((JCTree.JCParens) javacNode); case PRIMITIVE_TYPE: return convertPrimitiveType((JCTree.JCPrimitiveTypeTree) javacNode); case RETURN: return convertReturn((JCTree.JCReturn) javacNode); case SWITCH: return convertSwitch((JCTree.JCSwitch) javacNode); case THROW: return convertThrow((JCTree.JCThrow) javacNode); case TRY: return convertTry((JCTree.JCTry) javacNode); case TYPE_CAST: return convertTypeCast((JCTree.JCTypeCast) javacNode); case VARIABLE: return convertVariableDeclaration((JCTree.JCVariableDecl) javacNode); case WHILE_LOOP: return convertWhileLoop((JCTree.JCWhileLoop) javacNode); case BOOLEAN_LITERAL: return convertBooleanLiteral((JCTree.JCLiteral) javacNode); case CHAR_LITERAL: return convertCharLiteral((JCTree.JCLiteral) javacNode); case DOUBLE_LITERAL: case FLOAT_LITERAL: case INT_LITERAL: case LONG_LITERAL: return convertNumberLiteral((JCTree.JCLiteral) javacNode); case STRING_LITERAL: return convertStringLiteral((JCTree.JCLiteral) javacNode); case SYNCHRONIZED: return convertSynchronized((JCTree.JCSynchronized) javacNode); case NULL_LITERAL: return new NullLiteral(((JCTree.JCLiteral) javacNode).type); case AND: case CONDITIONAL_AND: case CONDITIONAL_OR: case DIVIDE: case EQUAL_TO: case GREATER_THAN: case GREATER_THAN_EQUAL: case LEFT_SHIFT: case LESS_THAN: case LESS_THAN_EQUAL: case MINUS: case MULTIPLY: case NOT_EQUAL_TO: case OR: case PLUS: case REMAINDER: case RIGHT_SHIFT: case UNSIGNED_RIGHT_SHIFT: case XOR: return convertBinary((JCTree.JCBinary) javacNode); case BITWISE_COMPLEMENT: case LOGICAL_COMPLEMENT: case PREFIX_DECREMENT: case PREFIX_INCREMENT: case UNARY_MINUS: case UNARY_PLUS: return convertPrefixExpr((JCTree.JCUnary) javacNode); case POSTFIX_DECREMENT: case POSTFIX_INCREMENT: return convertPostExpr((JCTree.JCUnary) javacNode); case AND_ASSIGNMENT: case DIVIDE_ASSIGNMENT: case LEFT_SHIFT_ASSIGNMENT: case MINUS_ASSIGNMENT: case MULTIPLY_ASSIGNMENT: case OR_ASSIGNMENT: case PLUS_ASSIGNMENT: case REMAINDER_ASSIGNMENT: case RIGHT_SHIFT_ASSIGNMENT: case UNSIGNED_RIGHT_SHIFT_ASSIGNMENT: case XOR_ASSIGNMENT: return convertAssignOp((JCTree.JCAssignOp) javacNode); case OTHER: { if (javacNode.hasTag(Tag.NULLCHK)) { // Skip javac's nullchk operators, since j2objc provides its own. // TODO(tball): convert to nil_chk() functions in this class, to // always check references that javac flagged? return convert(((JCTree.JCUnary) javacNode).arg); } throw new AssertionError("Unknown OTHER node, tag: " + javacNode.getTag()); } } } private TreeNode convertAbstractTypeDeclaration( JCTree.JCClassDecl node, AbstractTypeDeclaration newNode) { convertBodyDeclaration(node, newNode); List<BodyDeclaration> bodyDeclarations = new ArrayList<>(); for (JCTree bodyDecl : node.getMembers()) { // Skip synthetic methods. Synthetic default constructors are not marked // synthetic for backwards-compatibility reasons, so they are detected // by a source position that's the same as their declaring class. // TODO(tball): keep synthetic default constructors after front-end switch, // and get rid of DefaultConstructorAdder translator. if (bodyDecl.getKind() == Kind.METHOD && (ElementUtil.isSynthetic(((JCTree.JCMethodDecl) bodyDecl).sym) || bodyDecl.pos == node.pos)) { continue; } Object member = convert(bodyDecl); if (member instanceof BodyDeclaration) { // Not true for enum constants. bodyDeclarations.add((BodyDeclaration) member); } } return newNode .setName(convertSimpleName(node.sym)) .setTypeElement(node.sym) .setBodyDeclarations(bodyDeclarations); } private TreeNode convertAnnotation(JCTree.JCAnnotation node) { List<JCTree.JCExpression> args = node.getArguments(); Annotation newNode; if (args.isEmpty()) { newNode = new MarkerAnnotation() .setAnnotationMirror(node.attribute); } else if (args.size() == 1) { String annotationName = node.getAnnotationType().toString(); if (annotationName.equals(Property.class.getSimpleName()) || annotationName.equals(Property.class.getName())) { newNode = new PropertyAnnotation(); //TODO(tball): parse property attribute string. throw new AssertionError("not implemented"); } else { newNode = new SingleMemberAnnotation() .setValue((Expression) convert(args.get(0))); } } else { NormalAnnotation normalAnn = new NormalAnnotation(); for (JCTree.JCExpression obj : node.getArguments()) { JCTree.JCAssign assign = (JCTree.JCAssign) obj; MemberValuePair memberPair = new MemberValuePair() .setName(convertSimpleName(((JCTree.JCIdent) assign.lhs).sym)) .setValue((Expression) convert(assign.rhs)); normalAnn.addValue(memberPair); } newNode = normalAnn; } return newNode .setAnnotationMirror(node.attribute) .setTypeName((Name) convert(node.getAnnotationType())); } private TreeNode convertAnnotationTypeDeclaration(JCTree.JCClassDecl node) { AnnotationTypeDeclaration newNode = new AnnotationTypeDeclaration(); convertBodyDeclaration(node, newNode); for (JCTree bodyDecl : node.getMembers()) { if (bodyDecl.getKind() == Kind.METHOD) { JCTree.JCMethodDecl methodDecl = (JCTree.JCMethodDecl) bodyDecl; AnnotationTypeMemberDeclaration newMember = new AnnotationTypeMemberDeclaration() .setName(convertSimpleName(methodDecl.sym)) .setDefault((Expression) convert(methodDecl.defaultValue)) .setExecutableElement(methodDecl.sym) .setType(Type.newType(methodDecl.sym.getReturnType())); List<Annotation> annotations = new ArrayList<>(); for (AnnotationTree annotation : methodDecl.mods.annotations) { annotations.add((Annotation) convert(annotation)); } newMember .setModifiers((int) methodDecl.getModifiers().flags) .setAnnotations(annotations) .setJavadoc((Javadoc) getAssociatedJavaDoc(methodDecl)); newNode.addBodyDeclaration(newMember); } else { newNode.addBodyDeclaration((BodyDeclaration) convert(bodyDecl)); } } return newNode .setName(convertSimpleName(node.sym)) .setTypeElement(node.sym); } private TreeNode convertArrayAccess(JCTree.JCArrayAccess node) { return new ArrayAccess() .setArray((Expression) convert(node.getExpression())) .setIndex((Expression) convert(node.getIndex())); } private TreeNode convertArrayType(JCTree.JCArrayTypeTree node) { ArrayType newNode = new ArrayType(); convertType(node, newNode); Type componentType = (Type) Type.newType(node.getType().type); return newNode.setComponentType(componentType); } private TreeNode convertAssert(JCTree.JCAssert node) { return new AssertStatement() .setExpression((Expression) convert(node.getCondition())) .setMessage((Expression) convert(node.getDetail())); } private TreeNode convertAssignment(JCTree.JCAssign node) { Assignment newNode = new Assignment(); convertExpression(node, newNode); return newNode .setOperator(Assignment.Operator.ASSIGN) .setLeftHandSide((Expression) convert(node.getVariable())) .setRightHandSide((Expression) convert(node.getExpression())); } private TreeNode convertAssignOp(JCTree.JCAssignOp node) { Assignment newNode = new Assignment(); convertExpression(node, newNode); String operatorName = node.getOperator().getSimpleName().toString() + "="; return newNode .setOperator(Assignment.Operator.fromJdtOperatorName(operatorName)) .setLeftHandSide((Expression) convert(node.getVariable())) .setRightHandSide((Expression) convert(node.getExpression())); } private TreeNode convertBinary(JCTree.JCBinary node) { return new InfixExpression() .setTypeMirror(node.type) .setOperator(InfixExpression.Operator.parse(node.operator.name.toString())) .addOperand((Expression) convert(node.getLeftOperand())) .addOperand((Expression) convert(node.getRightOperand())); } private TreeNode convertBlock(JCTree.JCBlock node) { Block newNode = new Block(); for (StatementTree stmt : node.getStatements()) { TreeNode tree = convert(stmt); if (tree instanceof AbstractTypeDeclaration) { tree = new TypeDeclarationStatement().setDeclaration((AbstractTypeDeclaration) tree); } newNode.addStatement((Statement) tree); } return newNode; } private TreeNode convertBodyDeclaration(JCTree.JCClassDecl node, BodyDeclaration newNode) { List<Annotation> annotations = new ArrayList<>(); for (AnnotationTree annotation : node.getModifiers().getAnnotations()) { annotations.add((Annotation) convert(annotation)); } return newNode .setModifiers((int) node.getModifiers().flags) .setAnnotations(annotations) .setJavadoc((Javadoc) getAssociatedJavaDoc(node)); } private TreeNode convertBooleanLiteral(JCTree.JCLiteral node) { return new BooleanLiteral((Boolean) node.getValue(), node.type); } private TreeNode convertBreakStatement(JCTree.JCBreak node) { BreakStatement newNode = new BreakStatement(); newNode.setLabel((SimpleName) convert(node.getLabel())); return newNode; } private TreeNode convertCase(JCTree.JCCase node) { // Case statements are converted in convertSwitch(). return new SwitchCase() .setExpression((Expression) convert(node.getExpression())); } private TreeNode convertCatch(JCTree.JCCatch node) { return new CatchClause() .setException((SingleVariableDeclaration) convert(node.getParameter())) .setBody((Block) convert(node.getBlock())); } private TreeNode convertCharLiteral(JCTree.JCLiteral node) { return new CharacterLiteral((Character) node.getValue(), node.type); } private TreeNode convertClassDeclaration(JCTree.JCClassDecl node) { // javac defines all type declarations with JCClassDecl, so differentiate here // to support our different declaration nodes. if (node.sym.isAnonymous()) { AnonymousClassDeclaration newNode = new AnonymousClassDeclaration(); for (JCTree bodyDecl : node.getMembers()) { Object member = convert(bodyDecl); if (member instanceof BodyDeclaration) { // Not true for enum constants. newNode.addBodyDeclaration((BodyDeclaration) member); } } return newNode.setTypeElement(node.sym); } if (node.sym.getKind() == ElementKind.ANNOTATION_TYPE) { throw new AssertionError("Annotation type declaration tree conversion not implemented"); } TypeDeclaration newNode = (TypeDeclaration) convertAbstractTypeDeclaration(node, new TypeDeclaration()); JCTree.JCExpression extendsClause = node.getExtendsClause(); if (extendsClause != null) { newNode.setSuperclassType(Type.newType(nameType((node.getExtendsClause())))); } newNode.setInterface( node.getKind() == Kind.INTERFACE || node.getKind() == Kind.ANNOTATION_TYPE); for (JCTree superInterface : node.getImplementsClause()) { newNode.addSuperInterfaceType(Type.newType(nameType(superInterface))); } return newNode; } private TreeNode convertConditionalExpression(JCTree.JCConditional node) { return new ConditionalExpression() .setTypeMirror(node.type) .setExpression((Expression) convert(node.getCondition())) .setThenExpression((Expression) convert(node.getTrueExpression())) .setElseExpression((Expression) convert(node.getFalseExpression())); } private TreeNode convertContinueStatement(JCTree.JCContinue node) { return new ContinueStatement() .setLabel((SimpleName) convert(node.getLabel())); } private TreeNode convertDoStatement(JCTree.JCDoWhileLoop node) { return new DoStatement() .setExpression((Expression) convert(node.getCondition())) .setBody((Statement) convert(node.getStatement())); } private TreeNode convertEnhancedForStatement(JCTree.JCEnhancedForLoop node) { return new EnhancedForStatement() .setParameter((SingleVariableDeclaration) convertSingleVariable(node.getVariable())) .setExpression((Expression) convert(node.getExpression())) .setBody((Statement) convert(node.getStatement())); } private TreeNode convertEnum(JCTree.JCClassDecl node) { if (node.sym.isAnonymous()) { return (AnonymousClassDeclaration) convertClassDeclaration(node); } EnumDeclaration newNode = (EnumDeclaration) new EnumDeclaration() .setName(convertSimpleName(node.sym)) .setTypeElement(node.sym); for (JCTree superInterface : node.getImplementsClause()) { newNode.addSuperInterfaceType(Type.newType(nameType(superInterface))); } for (JCTree bodyDecl : node.getMembers()) { if (bodyDecl.getKind() == Kind.VARIABLE) { TreeNode var = convertVariableDeclaration((JCTree.JCVariableDecl) bodyDecl); if (var.getKind() == TreeNode.Kind.ENUM_CONSTANT_DECLARATION) { newNode.addEnumConstant((EnumConstantDeclaration) var); } else { newNode.addBodyDeclaration((BodyDeclaration) var); } } else if (bodyDecl.getKind() == Kind.METHOD) { MethodDeclaration method = (MethodDeclaration) convertMethodDeclaration((JCTree.JCMethodDecl) bodyDecl); if (ElementUtil.isConstructor(method.getExecutableElement()) && !method.getBody().getStatements().isEmpty()){ // Remove bogus "super()" call from constructors, so InitializationNormalizer // adds the correct super call that includes the ordinal and name arguments. Statement stmt = method.getBody().getStatements().get(0); if (stmt.getKind() == TreeNode.Kind.SUPER_CONSTRUCTOR_INVOCATION) { SuperConstructorInvocation call = (SuperConstructorInvocation) stmt; if (call.getArguments().isEmpty()) { method.getBody().getStatements().remove(0); } } } newNode.addBodyDeclaration(method); } else { newNode.addBodyDeclaration((BodyDeclaration) convert(bodyDecl)); } } return newNode; } private TreeNode convertExpression( JCTree.JCExpression node, Expression newNode) { return newNode .setConstantValue(node.type.constValue()); } private TreeNode convertExpressionStatement(JCTree.JCExpressionStatement node) { TreeNode expr = convert(node.getExpression()); if (expr instanceof Statement) { return expr; } return new ExpressionStatement().setExpression((Expression) expr); } private TreeNode convertFieldAccess(JCTree.JCFieldAccess node) { String fieldName = node.name.toString(); JCTree.JCExpression selected = node.getExpression(); if (fieldName.equals("this")) { return new ThisExpression() .setQualifier((Name) convert(selected)) .setTypeMirror(node.sym.asType()); } if (selected.toString().equals("super")) { return new SuperFieldAccess() .setVariableElement((VariableElement) node.sym) .setName(new SimpleName(node.sym, node.type)); } if (node.getIdentifier().toString().equals("class")) { // For Foo.class the type is Class<Foo>, so use the type argument as the // TypeLiteral type. com.sun.tools.javac.code.Type type = node.sym.asType(); return new TypeLiteral(type) .setType(Type.newType(type.getTypeArguments().get(0))); } if (selected.getKind() == Kind.IDENTIFIER) { return new QualifiedName() .setName(new SimpleName(node.sym, node.type)) .setQualifier(new SimpleName(((JCTree.JCIdent) selected).sym)) .setElement(node.sym); } if (selected.getKind() == Kind.MEMBER_SELECT) { return new QualifiedName() .setName(new SimpleName(node.sym, node.type)) .setQualifier(convertName(((JCTree.JCFieldAccess) selected).sym)) .setElement(node.sym); } return new FieldAccess() .setVariableElement((VariableElement) node.sym) .setExpression((Expression) convert(selected)) .setName(new SimpleName(node.sym, node.type)); } private TreeNode convertForLoop(JCTree.JCForLoop node) { ForStatement newNode = new ForStatement() .setExpression((Expression) convert(node.getCondition())) .setBody((Statement) convert(node.getStatement())); for (JCTree.JCStatement initializer : node.getInitializer()) { if (initializer.getKind() == Kind.VARIABLE) { JCTree.JCVariableDecl var = (JCTree.JCVariableDecl) initializer; newNode.addInitializer((Expression) convertVariableExpression(var)); } else { assert initializer.getKind() == Kind.EXPRESSION_STATEMENT; newNode.addInitializer((Expression) convert(((JCTree.JCExpressionStatement) initializer).getExpression())); } } for (JCTree.JCExpressionStatement updater : node.getUpdate()) { newNode.addUpdater((Expression) convert(updater.getExpression())); } return newNode; } private TreeNode convertFunctionalExpression(JCTree.JCFunctionalExpression node, FunctionalExpression newNode) { convertExpression(node, newNode); for (TypeMirror type : node.targets) { newNode.addTargetType(type); } return newNode.setTypeMirror(node.type); } private TreeNode convertIdent(JCTree.JCIdent node) { return new SimpleName(node.sym, node.type); } private TreeNode convertIf(JCTree.JCIf node) { Expression condition = (Expression) convert(node.getCondition()); if (condition.getKind() == TreeNode.Kind.PARENTHESIZED_EXPRESSION) { condition = TreeUtil.remove(((ParenthesizedExpression) condition).getExpression()); } return new IfStatement() .setExpression(condition) .setThenStatement((Statement) convert(node.getThenStatement())) .setElseStatement((Statement) convert(node.getElseStatement())); } private TreeNode convertInstanceOf(JCTree.JCInstanceOf node) { TypeMirror clazz = nameType(node.getType()); return new InstanceofExpression() .setLeftOperand((Expression) convert(node.getExpression())) .setRightOperand(Type.newType(clazz)); } private TreeNode convertLabeledStatement(JCTree.JCLabeledStatement node) { return new LabeledStatement() .setLabel(new SimpleName(node.label.toString())); } private TreeNode convertLambda(JCTree.JCLambda node) { LambdaExpression newNode = new LambdaExpression(); convertFunctionalExpression(node, newNode); for (JCVariableDecl param : node.params) { newNode.addParameter((VariableDeclaration) convert(param)); } return newNode.setBody(convert(node.getBody())); } private TreeNode convertMethodReference(JCTree.JCMemberReference node, MethodReference newNode) { convertFunctionalExpression(node, newNode); if (node.getTypeArguments() != null) { for (Object typeArg : node.getTypeArguments()) { newNode.addTypeArgument((Type) convert(typeArg)); } } return newNode // TODO(tball): Add the appropriate ExecutableType. .setExecutablePair(new ExecutablePair((ExecutableElement) node.sym, null)); } private TreeNode convertMemberReference(JCTree.JCMemberReference node) { Element element = node.sym; if (ElementUtil.isConstructor(element)) { CreationReference newNode = new CreationReference(); convertMethodReference(node, newNode); return newNode .setType(Type.newType(nameType(node.expr))); } if (node.hasKind(JCTree.JCMemberReference.ReferenceKind.SUPER)) { SuperMethodReference newNode = new SuperMethodReference(); convertMethodReference(node, newNode); // Qualifier expression is <name>."super", so it's always a JCFieldAccess. JCTree.JCFieldAccess expr = (JCTree.JCFieldAccess) node.getQualifierExpression(); return newNode .setName(convertSimpleName(node.sym)) .setQualifier(convertSimpleName(nameSymbol(expr.selected))); } if (node.hasKind(JCTree.JCMemberReference.ReferenceKind.UNBOUND) || node.hasKind(JCTree.JCMemberReference.ReferenceKind.STATIC)) { TypeMethodReference newNode = new TypeMethodReference(); convertMethodReference(node, newNode); return newNode .setName(convertSimpleName(node.sym)) .setType(convertType(node.type, false)); } ExpressionMethodReference newNode = new ExpressionMethodReference(); convertMethodReference(node, newNode); return newNode .setName(convertSimpleName(node.sym)) .setExpression((Expression) convert(node.getQualifierExpression())); } private TreeNode convertMethodDeclaration(JCTree.JCMethodDecl node) { MethodDeclaration newNode = new MethodDeclaration(); List<Annotation> annotations = new ArrayList<>(); for (AnnotationTree annotation : node.getModifiers().getAnnotations()) { annotations.add((Annotation) convert(annotation)); } for (JCTree.JCVariableDecl param : node.getParameters()) { newNode.addParameter((SingleVariableDeclaration) convert(param)); } if (ElementUtil.isConstructor(node.sym)) { newNode .setName(convertSimpleName(ElementUtil.getDeclaringClass(node.sym))) .setIsConstructor(true); } else { newNode .setName(convertSimpleName(node.sym)) .setReturnType(Type.newType(node.type.asMethodType().getReturnType())); } return newNode .setExecutableElement(node.sym) .setBody((Block) convert(node.getBody())) .setModifiers((int) node.getModifiers().flags) .setAnnotations(annotations) .setJavadoc((Javadoc) getAssociatedJavaDoc(node)); } private TreeNode convertMethodInvocation(JCTree.JCMethodInvocation node) { JCTree.JCExpression method = node.getMethodSelect(); if (method.getKind() == Kind.IDENTIFIER) { ExecutableElement element = (ExecutableElement) ((JCTree.JCIdent) method).sym; if (method.toString().equals("this")) { ConstructorInvocation newNode = new ConstructorInvocation() .setExecutablePair(new ExecutablePair(element, (ExecutableType) element.asType())); for (JCTree.JCExpression arg : node.getArguments()) { newNode.addArgument((Expression) convert(arg)); } return newNode; } if (method.toString().equals("super")) { SuperConstructorInvocation newNode = new SuperConstructorInvocation() .setExecutablePair(new ExecutablePair(element, (ExecutableType) element.asType())); for (JCTree.JCExpression arg : node.getArguments()) { newNode.addArgument((Expression) convert(arg)); } // If there's no expression node, javac sets it to be "<init>" which we don't want. Expression expr = ((Expression) convert(method)); if (!expr.toString().equals("<init>")) { newNode.setExpression(expr); } return newNode; } } if (method.getKind() == Kind.MEMBER_SELECT && ((JCTree.JCFieldAccess) method).name.toString().equals("super")) { ExecutableElement sym = (ExecutableElement) ((JCTree.JCFieldAccess) method).sym; SuperConstructorInvocation newNode = new SuperConstructorInvocation() .setExecutablePair(new ExecutablePair(sym, (ExecutableType) sym.asType())) .setExpression((Expression) convert(method)); for (JCTree.JCExpression arg : node.getArguments()) { newNode.addArgument((Expression) convert(arg)); } return newNode; } MethodInvocation newNode = new MethodInvocation(); ExecutableElement sym; if (method.getKind() == Kind.IDENTIFIER) { sym = (ExecutableElement) ((JCTree.JCIdent) method).sym; newNode .setName((SimpleName) convert(method)) .setExecutablePair(new ExecutablePair(sym, (ExecutableType) sym.asType())); } else { JCTree.JCFieldAccess select = (JCTree.JCFieldAccess) method; sym = (ExecutableElement) select.sym; newNode .setName(convertSimpleName(select.sym)) .setExpression((Expression) convert(select.selected)); } for (JCTree.JCExpression arg : node.getArguments()) { newNode.addArgument((Expression) convert(arg)); } return newNode .setTypeMirror(node.type) .setExecutablePair(new ExecutablePair(sym, (ExecutableType) sym.asType())); } private SimpleName convertSimpleName(Element element) { return new SimpleName(element); } private Name convertName(Symbol symbol) { if (symbol.owner == null || symbol.owner.name.isEmpty()) { return new SimpleName(symbol); } return new QualifiedName(symbol, symbol.asType(), convertName(symbol.owner)); } private TreeNode convertNewArray(JCTree.JCNewArray node) { ArrayCreation newNode = new ArrayCreation(); convertExpression(node, newNode); List<Expression> dimensions = new ArrayList<>(); for (JCTree.JCExpression dimension : node.getDimensions()) { dimensions.add((Expression) convert(dimension)); } javax.lang.model.type.ArrayType type = (javax.lang.model.type.ArrayType) node.type; ArrayInitializer initializers = new ArrayInitializer(type); if (node.getInitializers() != null) { for (JCTree.JCExpression initializer : node.getInitializers()) { initializers.addExpression((Expression) convert(initializer)); } } return newNode .setType(new ArrayType(type)) .setDimensions(dimensions) .setInitializer(initializers); } private TreeNode convertNewClass(JCTree.JCNewClass node) { ClassInstanceCreation newNode = new ClassInstanceCreation(); convertExpression(node, newNode); for (JCTree.JCExpression arg : node.getArguments()) { newNode.addArgument((Expression) convert(arg)); } return newNode .setExecutablePair(new ExecutablePair( (ExecutableElement) node.constructor, node.constructorType.asMethodType())) .setExpression((Expression) convert(node.getEnclosingExpression())) .setType(Type.newType(node.type)) .setAnonymousClassDeclaration((AnonymousClassDeclaration) convert(node.def)); } private TreeNode convertNumberLiteral(JCTree.JCLiteral node) { return new NumberLiteral((Number) node.getValue(), node.type) .setToken(getTreeSource(node)); } private PackageDeclaration convertPackage(PackageElement pkg) { PackageDeclaration newNode = new PackageDeclaration() .setPackageElement(pkg); return newNode.setName(convertName((PackageSymbol) pkg)); } private TreeNode convertPrefixExpr(JCTree.JCUnary node) { return new PrefixExpression() .setTypeMirror(node.type) .setOperator(PrefixExpression.Operator.parse(node.getOperator().name.toString())) .setOperand((Expression) convert(node.getExpression())); } private TreeNode convertParens(JCTree.JCParens node) { return new ParenthesizedExpression() .setExpression((Expression) convert(node.getExpression())); } private TreeNode convertPostExpr(JCTree.JCUnary node) { return new PostfixExpression() .setOperator(PostfixExpression.Operator.parse(node.getOperator().name.toString())) .setOperand((Expression) convert(node.getExpression())); } private TreeNode convertPrimitiveType(JCTree.JCPrimitiveTypeTree node) { return new PrimitiveType(node.type); } private TreeNode convertReturn(JCTree.JCReturn node) { return new ReturnStatement((Expression) convert(node.getExpression())); } private TreeNode convertStringLiteral(JCTree.JCLiteral node) { return new StringLiteral((String) node.getValue(), node.type); } private TreeNode convertSwitch(JCTree.JCSwitch node) { SwitchStatement newNode = new SwitchStatement() .setExpression((Expression) convert(node.getExpression())); for (JCTree.JCCase switchCase : node.getCases()) { newNode.addStatement((SwitchCase) convert(switchCase)); for (JCTree.JCStatement s : switchCase.getStatements()) { newNode.addStatement((Statement) convert(s)); } } return newNode; } private TreeNode convertSynchronized(JCTree.JCSynchronized node) { return new SynchronizedStatement() .setExpression((Expression) convert(node.getExpression())) .setBody((Block) convertBlock(node.getBlock())); } private TreeNode convertThrow(JCTree.JCThrow node) { return new ThrowStatement() .setExpression((Expression) convert(node.getExpression())); } private TreeNode convertTry(JCTree.JCTry node) { TryStatement newNode = new TryStatement(); for (Object obj : node.getResources()) { newNode.addResource(convertVariableExpression((JCTree.JCVariableDecl) obj)); } for (Object obj : node.getCatches()) { newNode.addCatchClause((CatchClause) convert(obj)); } return newNode .setBody((Block) convert(node.getBlock())) .setFinally((Block) convert(node.getFinallyBlock())); } private TreeNode convertType(JCTree.JCExpression node, Type newType) { return newType .setTypeMirror(node.type); } private TypeMirror nameType(JCTree node) { if (node.getKind() == Kind.PARAMETERIZED_TYPE) { return ((JCTree.JCTypeApply) node).clazz.type; } if (node.getKind() == Kind.ARRAY_TYPE) { return ((JCTree.JCArrayTypeTree) node).type; } return nameSymbol(node).asType(); } private Symbol nameSymbol(JCTree node) { return node.getKind() == Kind.MEMBER_SELECT ? ((JCTree.JCFieldAccess) node).sym : ((JCTree.JCIdent) node).sym; } private TreeNode convertTypeApply(JCTree.JCTypeApply node) { return new ParameterizedType() .setType(Type.newType(node.type)) .setTypeMirror(node.type); } private TreeNode convertTypeCast(JCTree.JCTypeCast node) { return new CastExpression(node.type, (Expression) convert(node.getExpression())); } private TreeNode convertVariableDeclaration(JCTree.JCVariableDecl node) { VarSymbol var = node.sym; if (var.getKind() == ElementKind.FIELD) { return new FieldDeclaration(var, (Expression) convert(node.getInitializer())); } if (var.getKind() == ElementKind.LOCAL_VARIABLE) { return new VariableDeclarationStatement(var, (Expression) convert(node.getInitializer())) .setType(convertType(var.asType(), false)); } if (var.getKind() == ElementKind.ENUM_CONSTANT) { EnumConstantDeclaration newNode = new EnumConstantDeclaration() .setName(convertSimpleName(var)) .setVariableElement(var); ClassInstanceCreation init = (ClassInstanceCreation) convert(node.getInitializer()); TreeUtil.copyList(init.getArguments(), newNode.getArguments()); if (init.getAnonymousClassDeclaration() != null) { newNode.setAnonymousClassDeclaration(TreeUtil.remove(init.getAnonymousClassDeclaration())); } return newNode .setExecutablePair(init.getExecutablePair()); } return convertSingleVariable(node); } private TreeNode convertSingleVariable(JCTree.JCVariableDecl node) { VarSymbol var = node.sym; boolean isVarargs = (node.sym.flags() & Flags.VARARGS) > 0; Type newType = convertType(var.asType(), isVarargs); return new SingleVariableDeclaration() .setType(newType) .setIsVarargs(isVarargs) .setName(convertSimpleName(var)) .setVariableElement(var) .setInitializer((Expression) convert(node.getInitializer())); } private Type convertType(TypeMirror varType, boolean isVarargs) { Type newType; if (isVarargs) { newType = Type.newType(((javax.lang.model.type.ArrayType) varType).getComponentType()); } else { if (varType.getKind() == TypeKind.DECLARED && !((DeclaredType) varType).getTypeArguments().isEmpty()) { newType = new ParameterizedType() .setType(new SimpleType(varType)) .setTypeMirror(varType); } else { newType = Type.newType(varType); } } return newType; } private VariableDeclarationExpression convertVariableExpression(JCTree.JCVariableDecl node) { VarSymbol var = node.sym; boolean isVarargs = (node.sym.flags() & Flags.VARARGS) > 0; Type newType = convertType(var.asType(), isVarargs); VariableDeclarationFragment fragment = new VariableDeclarationFragment(); fragment .setName(convertSimpleName(var)) .setVariableElement(var) .setInitializer((Expression) convert(node.getInitializer())); return new VariableDeclarationExpression() .setType(newType) .addFragment(fragment); } private TreeNode convertWhileLoop(JCTree.JCWhileLoop node) { return new WhileStatement() .setExpression((Expression) convert(node.getCondition())) .setBody((Statement) convert(node.getStatement())); } private TreeNode getAssociatedJavaDoc(JCTree node) { Comment comment = convertAssociatedComment(node); return comment != null && comment.isDocComment() ? comment : null; } private Comment convertAssociatedComment(JCTree node) { DocCommentTable docComments = unit.docComments; if (docComments == null || !docComments.hasComment(node)) { return null; } com.sun.tools.javac.parser.Tokens.Comment javacComment = docComments.getComment(node); Comment comment; switch (javacComment.getStyle()) { case BLOCK: comment = new BlockComment(); break; case JAVADOC: comment = new Javadoc(); break; case LINE: comment = new LineComment(); break; default: throw new AssertionError("unknown comment type"); } int startPos = javacComment.getSourcePos(0); int endPos = startPos + javacComment.getText().length(); comment.setSourceRange(startPos, endPos); return comment; } private static void addOcniComments(CompilationUnit unit) { // Can't use a regex because it will greedily include everything between // the first and last closing pattern, resulting in a single comment node. String source = unit.getSource(); int startPos = 0; int endPos = 0; while ((startPos = source.indexOf("/*-[", endPos)) > -1) { endPos = source.indexOf("]-*/", startPos); if (endPos > startPos) { endPos += 4; // Include closing delimiter. BlockComment ocniComment = new BlockComment(); ocniComment.setSourceRange(startPos, endPos); unit.getCommentList().add(ocniComment); } } } private static String getPath(JavaFileObject file) { String uri = file.toUri().toString(); if (uri.startsWith("mem:/")) { // MemoryFileObject needs a custom file system for URI to return the // correct path, so the URI string is split instead. return uri.substring(5); } return file.toUri().getPath(); } private String getTreeSource(JCTree node) { try { CharSequence source = unit.getSourceFile().getCharContent(true); return source.subSequence(node.getStartPosition(), node.getEndPosition(unit.endPositions)) .toString(); } catch (IOException e) { return node.toString(); } } }
Fixed ArrayCreationTest failures. Change on 2016/12/05 by tball <[email protected]> ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=141062168
translator/src/main/java/com/google/devtools/j2objc/javac/TreeConverter.java
Fixed ArrayCreationTest failures.
Java
apache-2.0
05fc23acefea45cd8f4e181e454c5ed80c2d3cd1
0
relvaner/actor4j-core
/* * Copyright (c) 2015, David A. Bauer */ package actor4j.core; import static actor4j.core.ActorLogger.logger; import static actor4j.core.ActorProtocolTag.*; import static actor4j.core.ActorUtils.actorLabel; import static actor4j.core.supervisor.SupervisorStrategyDirective.*; import java.util.Iterator; import java.util.UUID; import actor4j.core.supervisor.OneForAllSupervisorStrategy; import actor4j.core.supervisor.OneForOneSupervisorStrategy; import actor4j.core.supervisor.SupervisorStrategy; import actor4j.core.supervisor.SupervisorStrategyDirective; public class ActorStrategyOnFailure { protected ActorSystem system; public ActorStrategyOnFailure(ActorSystem system) { this.system = system; } protected void oneForOne_directive_resume(Actor actor) { logger().info(String.format("System - actor (%s) resumed", actorLabel(actor))); } protected void oneForOne_directive_restart(Actor actor, Exception reason) { actor.preRestart(reason); } protected void oneForOne_directive_stop(Actor actor) { actor.stop(); } protected void oneForAll_directive_resume(Actor actor) { oneForOne_directive_resume(actor); } protected void oneForAll_directive_restart(Actor actor, Exception reason) { if (!actor.isRoot()) { Actor parent = system.actors.get(actor.getParent()); if (parent!=null) { Iterator<UUID> iterator = parent.getChildren().iterator(); while (iterator.hasNext()) { UUID dest = iterator.next(); if (!dest.equals(actor.getId())) system.sendAsDirective(new ActorMessage<>(reason, INTERNAL_RESTART, parent.getId(), dest)); } actor.preRestart(reason); } } else actor.preRestart(reason); } protected void oneForAll_directive_stop(Actor actor) { if (!actor.isRoot()) { Actor parent = system.actors.get(actor.getParent()); if (parent!=null) { Iterator<UUID> iterator = parent.getChildren().iterator(); while (iterator.hasNext()) { UUID dest = iterator.next(); if (!dest.equals(actor.getId())) system.sendAsDirective(new ActorMessage<>(null, INTERNAL_STOP, parent.getId(), dest)); } actor.stop(); } } else actor.stop(); } public void handle(Actor actor, Exception e) { Actor parent = system.actors.get(actor.parent); SupervisorStrategy supervisorStrategy = parent.supervisorStrategy(); SupervisorStrategyDirective directive = supervisorStrategy.apply(e); while (directive==ESCALATE && !parent.isRoot()) { parent = system.actors.get(parent.parent); directive = parent.supervisorStrategy().apply(e); } ; if (actor.supervisorStrategy() instanceof OneForOneSupervisorStrategy) { if (directive==RESUME) oneForOne_directive_resume(actor); else if (directive==RESTART) oneForOne_directive_restart(actor, e); else if (directive==STOP) oneForOne_directive_stop(actor); } else if (actor.supervisorStrategy() instanceof OneForAllSupervisorStrategy) { if (directive==RESUME) oneForAll_directive_resume(actor); else if (directive==RESTART) oneForAll_directive_restart(actor, e); else if (directive==STOP) oneForAll_directive_stop(actor); } } }
actor4j-m-core/src/main/java/actor4j/core/ActorStrategyOnFailure.java
/* * Copyright (c) 2015, David A. Bauer */ package actor4j.core; import static actor4j.core.ActorLogger.logger; import static actor4j.core.ActorProtocolTag.*; import static actor4j.core.ActorUtils.actorLabel; import java.util.Iterator; import java.util.UUID; import actor4j.core.supervisor.OneForAllSupervisorStrategy; import actor4j.core.supervisor.OneForOneSupervisorStrategy; import actor4j.core.supervisor.SupervisorStrategy; import actor4j.core.supervisor.SupervisorStrategyDirective; public class ActorStrategyOnFailure { protected ActorSystem system; public ActorStrategyOnFailure(ActorSystem system) { this.system = system; } protected void oneForOne_directive_resume(Actor actor) { logger().info(String.format("System - actor (%s) resumed", actorLabel(actor))); } protected void oneForOne_directive_restart(Actor actor, Exception reason) { actor.preRestart(reason); } protected void oneForOne_directive_stop(Actor actor) { actor.stop(); } protected void oneForAll_directive_resume(Actor actor) { oneForOne_directive_resume(actor); } protected void oneForAll_directive_restart(Actor actor, Exception reason) { if (!actor.isRoot()) { Actor parent = system.actors.get(actor.getParent()); if (parent!=null) { Iterator<UUID> iterator = parent.getChildren().iterator(); while (iterator.hasNext()) { UUID dest = iterator.next(); if (!dest.equals(actor.getId())) system.sendAsDirective(new ActorMessage<>(reason, INTERNAL_RESTART, parent.getId(), dest)); } actor.preRestart(reason); } } else actor.preRestart(reason); } protected void oneForAll_directive_stop(Actor actor) { if (!actor.isRoot()) { Actor parent = system.actors.get(actor.getParent()); if (parent!=null) { Iterator<UUID> iterator = parent.getChildren().iterator(); while (iterator.hasNext()) { UUID dest = iterator.next(); if (!dest.equals(actor.getId())) system.sendAsDirective(new ActorMessage<>(null, INTERNAL_STOP, parent.getId(), dest)); } actor.stop(); } } else actor.stop(); } public void handle(Actor actor, Exception e) { SupervisorStrategy supervisorStrategy = system.actors.get(actor.parent).supervisorStrategy(); SupervisorStrategyDirective directive = supervisorStrategy.apply(e); if (actor.supervisorStrategy() instanceof OneForOneSupervisorStrategy) { if (directive==SupervisorStrategyDirective.RESUME) oneForOne_directive_resume(actor); else if (directive==SupervisorStrategyDirective.RESTART) oneForOne_directive_restart(actor, e); else if (directive==SupervisorStrategyDirective.STOP) oneForOne_directive_stop(actor); else if (directive==SupervisorStrategyDirective.ESCALATE) ; } else if (actor.supervisorStrategy() instanceof OneForAllSupervisorStrategy) { if (directive==SupervisorStrategyDirective.RESUME) oneForAll_directive_resume(actor); else if (directive==SupervisorStrategyDirective.RESTART) oneForAll_directive_restart(actor, e); else if (directive==SupervisorStrategyDirective.STOP) oneForAll_directive_stop(actor); else if (directive==SupervisorStrategyDirective.ESCALATE) ; } } }
Added implementation for directive escalate
actor4j-m-core/src/main/java/actor4j/core/ActorStrategyOnFailure.java
Added implementation for directive escalate
Java
apache-2.0
d483108a1508e9a5f6324a5fe5547deb4c6a713f
0
apache/solr,apache/solr,apache/solr,apache/solr,apache/solr
/* * 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.solr.cloud; import java.lang.invoke.MethodHandles; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.apache.lucene.util.LuceneTestCase; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.embedded.JettySolrRunner; import org.apache.solr.client.solrj.impl.HttpSolrClient; import org.apache.solr.client.solrj.request.CollectionAdminRequest; import org.apache.solr.client.solrj.request.UpdateRequest; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.cloud.ClusterStateUtil; import org.apache.solr.common.cloud.DocCollection; import org.apache.solr.common.cloud.Replica; import org.apache.solr.common.cloud.Slice; import org.apache.solr.common.cloud.SolrZkClient; import org.apache.solr.common.cloud.ZkStateReader; import org.apache.solr.common.params.ModifiableSolrParams; import org.apache.solr.common.util.TimeSource; import org.apache.solr.common.util.Utils; import org.apache.solr.core.CoreContainer; import org.apache.solr.update.processor.DistributedUpdateProcessor; import org.apache.solr.update.processor.DistributingUpdateProcessorFactory; import org.apache.solr.util.TimeOut; import org.apache.zookeeper.KeeperException; import org.junit.AfterClass; import org.junit.BeforeClass; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @LuceneTestCase.Nightly @LuceneTestCase.Slow @Deprecated public class LIROnShardRestartTest extends SolrCloudTestCase { private static final Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); @BeforeClass public static void setupCluster() throws Exception { System.setProperty("solr.directoryFactory", "solr.StandardDirectoryFactory"); System.setProperty("solr.ulog.numRecordsToKeep", "1000"); configureCluster(3) .addConfig("conf", configset("cloud-minimal")) .configure(); } @AfterClass public static void tearDownCluster() throws Exception { System.clearProperty("solr.directoryFactory"); System.clearProperty("solr.ulog.numRecordsToKeep"); } public void testAllReplicasInLIR() throws Exception { String collection = "allReplicasInLIR"; CollectionAdminRequest.createCollection(collection, 1, 3) .process(cluster.getSolrClient()); cluster.getSolrClient().add(collection, new SolrInputDocument("id", "1")); cluster.getSolrClient().add(collection, new SolrInputDocument("id", "2")); cluster.getSolrClient().commit(collection); DocCollection docCollection = getCollectionState(collection); Slice shard1 = docCollection.getSlice("shard1"); Replica newLeader = shard1.getReplicas(rep -> !rep.getName().equals(shard1.getLeader().getName())).get(random().nextInt(2)); JettySolrRunner jettyOfNewLeader = cluster.getJettySolrRunners().stream() .filter(jetty -> jetty.getNodeName().equals(newLeader.getNodeName())) .findAny().get(); assertNotNull(jettyOfNewLeader); // randomly add too many docs to peer sync to one replica so that only one random replica is the valid leader // the versions don't matter, they just have to be higher than what the last 2 docs got try (HttpSolrClient client = getHttpSolrClient(jettyOfNewLeader.getBaseUrl().toString())) { ModifiableSolrParams params = new ModifiableSolrParams(); params.set(DistributingUpdateProcessorFactory.DISTRIB_UPDATE_PARAM, DistributedUpdateProcessor.DistribPhase.FROMLEADER.toString()); for (int i = 0; i < 101; i++) { UpdateRequest ureq = new UpdateRequest(); ureq.setParams(new ModifiableSolrParams(params)); ureq.add(sdoc("id", 3 + i, "_version_", Long.MAX_VALUE - 1 - i)); ureq.process(client, collection); } client.commit(collection); } ChaosMonkey.stop(cluster.getJettySolrRunners()); assertTrue("Timeout waiting for all not live", ClusterStateUtil.waitForAllReplicasNotLive(cluster.getSolrClient().getZkStateReader(), 45000)); try (ZkShardTerms zkShardTerms = new ZkShardTerms(collection, "shard1", cluster.getZkClient())) { for (Replica replica : docCollection.getReplicas()) { zkShardTerms.removeTerm(replica.getName()); } } Map<String,Object> stateObj = Utils.makeMap(); stateObj.put(ZkStateReader.STATE_PROP, "down"); stateObj.put("createdByNodeName", "test"); stateObj.put("createdByCoreNodeName", "test"); byte[] znodeData = Utils.toJSON(stateObj); for (Replica replica : docCollection.getReplicas()) { try { cluster.getZkClient().makePath("/collections/" + collection + "/leader_initiated_recovery/shard1/" + replica.getName(), znodeData, true); } catch (KeeperException.NodeExistsException e) { } } ChaosMonkey.start(cluster.getJettySolrRunners()); waitForState("Timeout waiting for active replicas", collection, clusterShape(1, 3)); assertEquals(103, cluster.getSolrClient().query(collection, new SolrQuery("*:*")).getResults().getNumFound()); // now expire each node for (Replica replica : docCollection.getReplicas()) { try { // todo remove the condition for skipping leader after SOLR-12166 is fixed if (newLeader.getName().equals(replica.getName())) continue; cluster.getZkClient().makePath("/collections/" + collection + "/leader_initiated_recovery/shard1/" + replica.getName(), znodeData, true); } catch (KeeperException.NodeExistsException e) { } } // only 2 replicas join the election and all of them are in LIR state, no one should win the election List<String> oldElectionNodes = getElectionNodes(collection, "shard1", cluster.getZkClient()); for (JettySolrRunner jetty : cluster.getJettySolrRunners()) { expire(jetty); } TimeOut timeOut = new TimeOut(60, TimeUnit.SECONDS, TimeSource.CURRENT_TIME); while (!timeOut.hasTimedOut()) { List<String> electionNodes = getElectionNodes(collection, "shard1", cluster.getZkClient()); electionNodes.retainAll(oldElectionNodes); if (electionNodes.isEmpty()) break; } assertFalse("Timeout waiting for replicas rejoin election", timeOut.hasTimedOut()); try { waitForState("Timeout waiting for active replicas", collection, clusterShape(1, 3)); } catch (Throwable th) { String electionPath = "/collections/allReplicasInLIR/leader_elect/shard1/election/"; List<String> children = zkClient().getChildren(electionPath, null, true); LOG.info("Election queue {}", children); throw th; } assertEquals(103, cluster.getSolrClient().query(collection, new SolrQuery("*:*")).getResults().getNumFound()); CollectionAdminRequest.deleteCollection(collection).process(cluster.getSolrClient()); } public void expire(JettySolrRunner jetty) { CoreContainer cores = jetty.getCoreContainer(); ChaosMonkey.causeConnectionLoss(jetty); long sessionId = cores.getZkController().getZkClient() .getSolrZooKeeper().getSessionId(); cluster.getZkServer().expire(sessionId); } public void testSeveralReplicasInLIR() throws Exception { String collection = "severalReplicasInLIR"; CollectionAdminRequest.createCollection(collection, 1, 3) .process(cluster.getSolrClient()); cluster.getSolrClient().add(collection, new SolrInputDocument("id", "1")); cluster.getSolrClient().add(collection, new SolrInputDocument("id", "2")); cluster.getSolrClient().commit(collection); DocCollection docCollection = getCollectionState(collection); Map<JettySolrRunner, String> nodeNameToJetty = cluster.getJettySolrRunners().stream() .collect(Collectors.toMap(jetty -> jetty, JettySolrRunner::getNodeName)); ChaosMonkey.stop(cluster.getJettySolrRunners()); assertTrue("Timeout waiting for all not live", ClusterStateUtil.waitForAllReplicasNotLive(cluster.getSolrClient().getZkStateReader(), 45000)); try (ZkShardTerms zkShardTerms = new ZkShardTerms(collection, "shard1", cluster.getZkClient())) { for (Replica replica : docCollection.getReplicas()) { zkShardTerms.removeTerm(replica.getName()); } } Map<String,Object> stateObj = Utils.makeMap(); stateObj.put(ZkStateReader.STATE_PROP, "down"); stateObj.put("createdByNodeName", "test"); stateObj.put("createdByCoreNodeName", "test"); byte[] znodeData = Utils.toJSON(stateObj); Replica replicaNotInLIR = docCollection.getReplicas().get(random().nextInt(3)); for (Replica replica : docCollection.getReplicas()) { if (replica.getName().equals(replicaNotInLIR.getName())) continue; try { cluster.getZkClient().makePath("/collections/" + collection + "/leader_initiated_recovery/shard1/" + replica.getName(), znodeData, true); } catch (KeeperException.NodeExistsException e) { } } for (JettySolrRunner jetty : cluster.getJettySolrRunners()) { if (nodeNameToJetty.get(jetty).equals(replicaNotInLIR.getNodeName())) continue; jetty.start(); } waitForState("Timeout waiting for no leader", collection, (liveNodes, collectionState) -> { Replica leader = collectionState.getSlice("shard1").getLeader(); return leader == null; }); // only 2 replicas join the election and all of them are in LIR state, no one should win the election List<String> oldElectionNodes = getElectionNodes(collection, "shard1", cluster.getZkClient()); TimeOut timeOut = new TimeOut(60, TimeUnit.SECONDS, TimeSource.CURRENT_TIME); while (!timeOut.hasTimedOut()) { List<String> electionNodes = getElectionNodes(collection, "shard1", cluster.getZkClient()); electionNodes.retainAll(oldElectionNodes); if (electionNodes.isEmpty()) break; } assertFalse("Timeout waiting for replicas rejoin election", timeOut.hasTimedOut()); for (JettySolrRunner jetty : cluster.getJettySolrRunners()) { if (nodeNameToJetty.get(jetty).equals(replicaNotInLIR.getNodeName())) { jetty.start(); } } waitForState("Timeout waiting for new leader", collection, (liveNodes, collectionState) -> { Replica leader = collectionState.getSlice("shard1").getLeader(); return leader != null; }); waitForState("Timeout waiting for new leader", collection, clusterShape(1, 3)); assertEquals(2L, cluster.getSolrClient().query(collection, new SolrQuery("*:*")).getResults().getNumFound()); CollectionAdminRequest.deleteCollection(collection).process(cluster.getSolrClient()); } private List<String> getElectionNodes(String collection, String shard, SolrZkClient client) throws KeeperException, InterruptedException { return client.getChildren("/collections/"+collection+"/leader_elect/"+shard+LeaderElector.ELECTION_NODE, null, true); } }
solr/core/src/test/org/apache/solr/cloud/LIROnShardRestartTest.java
/* * 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.solr.cloud; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.apache.lucene.util.LuceneTestCase; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.embedded.JettySolrRunner; import org.apache.solr.client.solrj.impl.HttpSolrClient; import org.apache.solr.client.solrj.request.CollectionAdminRequest; import org.apache.solr.client.solrj.request.UpdateRequest; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.cloud.ClusterStateUtil; import org.apache.solr.common.cloud.DocCollection; import org.apache.solr.common.cloud.Replica; import org.apache.solr.common.cloud.Slice; import org.apache.solr.common.cloud.SolrZkClient; import org.apache.solr.common.cloud.ZkStateReader; import org.apache.solr.common.params.ModifiableSolrParams; import org.apache.solr.common.util.TimeSource; import org.apache.solr.common.util.Utils; import org.apache.solr.core.CoreContainer; import org.apache.solr.update.processor.DistributedUpdateProcessor; import org.apache.solr.update.processor.DistributingUpdateProcessorFactory; import org.apache.solr.util.TimeOut; import org.apache.zookeeper.KeeperException; import org.junit.AfterClass; import org.junit.BeforeClass; @LuceneTestCase.Nightly @LuceneTestCase.Slow @Deprecated public class LIROnShardRestartTest extends SolrCloudTestCase { @BeforeClass public static void setupCluster() throws Exception { System.setProperty("solr.directoryFactory", "solr.StandardDirectoryFactory"); System.setProperty("solr.ulog.numRecordsToKeep", "1000"); configureCluster(3) .addConfig("conf", configset("cloud-minimal")) .configure(); } @AfterClass public static void tearDownCluster() throws Exception { System.clearProperty("solr.directoryFactory"); System.clearProperty("solr.ulog.numRecordsToKeep"); } public void testAllReplicasInLIR() throws Exception { String collection = "allReplicasInLIR"; CollectionAdminRequest.createCollection(collection, 1, 3) .process(cluster.getSolrClient()); cluster.getSolrClient().add(collection, new SolrInputDocument("id", "1")); cluster.getSolrClient().add(collection, new SolrInputDocument("id", "2")); cluster.getSolrClient().commit(collection); DocCollection docCollection = getCollectionState(collection); Slice shard1 = docCollection.getSlice("shard1"); Replica newLeader = shard1.getReplicas(rep -> !rep.getName().equals(shard1.getLeader().getName())).get(random().nextInt(2)); JettySolrRunner jettyOfNewLeader = cluster.getJettySolrRunners().stream() .filter(jetty -> jetty.getNodeName().equals(newLeader.getNodeName())) .findAny().get(); assertNotNull(jettyOfNewLeader); // randomly add too many docs to peer sync to one replica so that only one random replica is the valid leader // the versions don't matter, they just have to be higher than what the last 2 docs got try (HttpSolrClient client = getHttpSolrClient(jettyOfNewLeader.getBaseUrl().toString())) { ModifiableSolrParams params = new ModifiableSolrParams(); params.set(DistributingUpdateProcessorFactory.DISTRIB_UPDATE_PARAM, DistributedUpdateProcessor.DistribPhase.FROMLEADER.toString()); for (int i = 0; i < 101; i++) { UpdateRequest ureq = new UpdateRequest(); ureq.setParams(new ModifiableSolrParams(params)); ureq.add(sdoc("id", 3 + i, "_version_", Long.MAX_VALUE - 1 - i)); ureq.process(client, collection); } client.commit(collection); } ChaosMonkey.stop(cluster.getJettySolrRunners()); assertTrue("Timeout waiting for all not live", ClusterStateUtil.waitForAllReplicasNotLive(cluster.getSolrClient().getZkStateReader(), 45000)); try (ZkShardTerms zkShardTerms = new ZkShardTerms(collection, "shard1", cluster.getZkClient())) { for (Replica replica : docCollection.getReplicas()) { zkShardTerms.removeTerm(replica.getName()); } } Map<String,Object> stateObj = Utils.makeMap(); stateObj.put(ZkStateReader.STATE_PROP, "down"); stateObj.put("createdByNodeName", "test"); stateObj.put("createdByCoreNodeName", "test"); byte[] znodeData = Utils.toJSON(stateObj); for (Replica replica : docCollection.getReplicas()) { try { cluster.getZkClient().makePath("/collections/" + collection + "/leader_initiated_recovery/shard1/" + replica.getName(), znodeData, true); } catch (KeeperException.NodeExistsException e) { } } ChaosMonkey.start(cluster.getJettySolrRunners()); waitForState("Timeout waiting for active replicas", collection, clusterShape(1, 3)); assertEquals(103, cluster.getSolrClient().query(collection, new SolrQuery("*:*")).getResults().getNumFound()); // now expire each node for (Replica replica : docCollection.getReplicas()) { try { cluster.getZkClient().makePath("/collections/" + collection + "/leader_initiated_recovery/shard1/" + replica.getName(), znodeData, true); } catch (KeeperException.NodeExistsException e) { } } // only 2 replicas join the election and all of them are in LIR state, no one should win the election List<String> oldElectionNodes = getElectionNodes(collection, "shard1", cluster.getZkClient()); for (JettySolrRunner jetty : cluster.getJettySolrRunners()) { expire(jetty); } TimeOut timeOut = new TimeOut(60, TimeUnit.SECONDS, TimeSource.CURRENT_TIME); while (!timeOut.hasTimedOut()) { List<String> electionNodes = getElectionNodes(collection, "shard1", cluster.getZkClient()); electionNodes.retainAll(oldElectionNodes); if (electionNodes.isEmpty()) break; } assertFalse("Timeout waiting for replicas rejoin election", timeOut.hasTimedOut()); waitForState("Timeout waiting for active replicas", collection, clusterShape(1, 3)); assertEquals(103, cluster.getSolrClient().query(collection, new SolrQuery("*:*")).getResults().getNumFound()); CollectionAdminRequest.deleteCollection(collection).process(cluster.getSolrClient()); } public void expire(JettySolrRunner jetty) { CoreContainer cores = jetty.getCoreContainer(); ChaosMonkey.causeConnectionLoss(jetty); long sessionId = cores.getZkController().getZkClient() .getSolrZooKeeper().getSessionId(); cluster.getZkServer().expire(sessionId); } public void testSeveralReplicasInLIR() throws Exception { String collection = "severalReplicasInLIR"; CollectionAdminRequest.createCollection(collection, 1, 3) .process(cluster.getSolrClient()); cluster.getSolrClient().add(collection, new SolrInputDocument("id", "1")); cluster.getSolrClient().add(collection, new SolrInputDocument("id", "2")); cluster.getSolrClient().commit(collection); DocCollection docCollection = getCollectionState(collection); Map<JettySolrRunner, String> nodeNameToJetty = cluster.getJettySolrRunners().stream() .collect(Collectors.toMap(jetty -> jetty, JettySolrRunner::getNodeName)); ChaosMonkey.stop(cluster.getJettySolrRunners()); assertTrue("Timeout waiting for all not live", ClusterStateUtil.waitForAllReplicasNotLive(cluster.getSolrClient().getZkStateReader(), 45000)); try (ZkShardTerms zkShardTerms = new ZkShardTerms(collection, "shard1", cluster.getZkClient())) { for (Replica replica : docCollection.getReplicas()) { zkShardTerms.removeTerm(replica.getName()); } } Map<String,Object> stateObj = Utils.makeMap(); stateObj.put(ZkStateReader.STATE_PROP, "down"); stateObj.put("createdByNodeName", "test"); stateObj.put("createdByCoreNodeName", "test"); byte[] znodeData = Utils.toJSON(stateObj); Replica replicaNotInLIR = docCollection.getReplicas().get(random().nextInt(3)); for (Replica replica : docCollection.getReplicas()) { if (replica.getName().equals(replicaNotInLIR.getName())) continue; try { cluster.getZkClient().makePath("/collections/" + collection + "/leader_initiated_recovery/shard1/" + replica.getName(), znodeData, true); } catch (KeeperException.NodeExistsException e) { } } for (JettySolrRunner jetty : cluster.getJettySolrRunners()) { if (nodeNameToJetty.get(jetty).equals(replicaNotInLIR.getNodeName())) continue; jetty.start(); } waitForState("Timeout waiting for no leader", collection, (liveNodes, collectionState) -> { Replica leader = collectionState.getSlice("shard1").getLeader(); return leader == null; }); // only 2 replicas join the election and all of them are in LIR state, no one should win the election List<String> oldElectionNodes = getElectionNodes(collection, "shard1", cluster.getZkClient()); TimeOut timeOut = new TimeOut(60, TimeUnit.SECONDS, TimeSource.CURRENT_TIME); while (!timeOut.hasTimedOut()) { List<String> electionNodes = getElectionNodes(collection, "shard1", cluster.getZkClient()); electionNodes.retainAll(oldElectionNodes); if (electionNodes.isEmpty()) break; } assertFalse("Timeout waiting for replicas rejoin election", timeOut.hasTimedOut()); for (JettySolrRunner jetty : cluster.getJettySolrRunners()) { if (nodeNameToJetty.get(jetty).equals(replicaNotInLIR.getNodeName())) { jetty.start(); } } waitForState("Timeout waiting for new leader", collection, (liveNodes, collectionState) -> { Replica leader = collectionState.getSlice("shard1").getLeader(); return leader != null; }); waitForState("Timeout waiting for new leader", collection, clusterShape(1, 3)); assertEquals(2L, cluster.getSolrClient().query(collection, new SolrQuery("*:*")).getResults().getNumFound()); CollectionAdminRequest.deleteCollection(collection).process(cluster.getSolrClient()); } private List<String> getElectionNodes(String collection, String shard, SolrZkClient client) throws KeeperException, InterruptedException { return client.getChildren("/collections/"+collection+"/leader_elect/"+shard+LeaderElector.ELECTION_NODE, null, true); } }
SOLR-12168: LIROnShardRestartTest failures
solr/core/src/test/org/apache/solr/cloud/LIROnShardRestartTest.java
SOLR-12168: LIROnShardRestartTest failures
Java
apache-2.0
ec44fe950871530b486ac97790626a9f6e575fd1
0
hmsonline/cassandra-triggers,hmsonline/cassandra-triggers
package com.hmsonline.cassandra.triggers; import junit.framework.Assert; import org.junit.Test; /** * @author <a [email protected]>Isaac Rieksts</a> */ public class TriggerTaskTest { @Test public void testStackToStringNPE() { try { ((String) null).toString(); } catch (Exception e) { Assert.assertTrue("Should throw a null pointer", TriggerExecutionThread.stackToString(e).contains("java.lang.NullPointerException")); } } @Test public void testStackToStringNullStack() { try { Exception t = new Exception(); t.setStackTrace(new StackTraceElement[] {}); throw t; } catch (Exception e) { Assert.assertEquals("Should throw a null pointer", "java.lang.Exception", TriggerExecutionThread.stackToString(e).trim()); } } }
src/test/java/com/hmsonline/cassandra/triggers/TriggerTaskTest.java
package com.hmsonline.cassandra.triggers; import junit.framework.Assert; import org.junit.Test; /** * @author <a [email protected]>Isaac Rieksts</a> */ public class TriggerTaskTest { @Test public void testStackToStringNPE() { try { ((String) null).toString(); } catch (Exception e) { Assert.assertTrue("Should throw a null pointer", TriggerExecutionThread.stackToString(e).contains("java.lang.NullPointerException")); } } @Test public void testStackToStringNullStack() { try { Exception t = new Exception(); t.setStackTrace(new StackTraceElement[] {}); throw t; } catch (Exception e) { Assert.assertEquals("Should throw a null pointer", "java.lang.Exception\n", TriggerExecutionThread.stackToString(e)); } } }
Removing the line feed and adding a trim in case a different line feed char is used.
src/test/java/com/hmsonline/cassandra/triggers/TriggerTaskTest.java
Removing the line feed and adding a trim in case a different line feed char is used.
Java
bsd-3-clause
561b1c2ddf391f731c529013236427f6322b5dad
0
GreenCubes/jmonkeyengine,InShadow/jmonkeyengine,amit2103/jmonkeyengine,skapi1992/jmonkeyengine,skapi1992/jmonkeyengine,mbenson/jmonkeyengine,weilichuang/jmonkeyengine,phr00t/jmonkeyengine,GreenCubes/jmonkeyengine,mbenson/jmonkeyengine,nickschot/jmonkeyengine,phr00t/jmonkeyengine,g-rocket/jmonkeyengine,wrvangeest/jmonkeyengine,danteinforno/jmonkeyengine,bertleft/jmonkeyengine,InShadow/jmonkeyengine,rbottema/jmonkeyengine,nickschot/jmonkeyengine,sandervdo/jmonkeyengine,GreenCubes/jmonkeyengine,delftsre/jmonkeyengine,mbenson/jmonkeyengine,rbottema/jmonkeyengine,tr0k/jmonkeyengine,Georgeto/jmonkeyengine,d235j/jmonkeyengine,g-rocket/jmonkeyengine,OpenGrabeso/jmonkeyengine,shurun19851206/jMonkeyEngine,skapi1992/jmonkeyengine,jMonkeyEngine/jmonkeyengine,OpenGrabeso/jmonkeyengine,delftsre/jmonkeyengine,wrvangeest/jmonkeyengine,olafmaas/jmonkeyengine,olafmaas/jmonkeyengine,aaronang/jmonkeyengine,danteinforno/jmonkeyengine,aaronang/jmonkeyengine,d235j/jmonkeyengine,yetanotherindie/jMonkey-Engine,amit2103/jmonkeyengine,wrvangeest/jmonkeyengine,davidB/jmonkeyengine,d235j/jmonkeyengine,delftsre/jmonkeyengine,OpenGrabeso/jmonkeyengine,shurun19851206/jMonkeyEngine,rbottema/jmonkeyengine,jMonkeyEngine/jmonkeyengine,atomixnmc/jmonkeyengine,davidB/jmonkeyengine,mbenson/jmonkeyengine,yetanotherindie/jMonkey-Engine,yetanotherindie/jMonkey-Engine,atomixnmc/jmonkeyengine,mbenson/jmonkeyengine,OpenGrabeso/jmonkeyengine,sandervdo/jmonkeyengine,shurun19851206/jMonkeyEngine,OpenGrabeso/jmonkeyengine,davidB/jmonkeyengine,aaronang/jmonkeyengine,atomixnmc/jmonkeyengine,weilichuang/jmonkeyengine,shurun19851206/jMonkeyEngine,Georgeto/jmonkeyengine,weilichuang/jmonkeyengine,bsmr-java/jmonkeyengine,zzuegg/jmonkeyengine,danteinforno/jmonkeyengine,g-rocket/jmonkeyengine,tr0k/jmonkeyengine,zzuegg/jmonkeyengine,yetanotherindie/jMonkey-Engine,davidB/jmonkeyengine,bertleft/jmonkeyengine,mbenson/jmonkeyengine,Georgeto/jmonkeyengine,InShadow/jmonkeyengine,atomixnmc/jmonkeyengine,weilichuang/jmonkeyengine,bertleft/jmonkeyengine,yetanotherindie/jMonkey-Engine,tr0k/jmonkeyengine,sandervdo/jmonkeyengine,yetanotherindie/jMonkey-Engine,atomixnmc/jmonkeyengine,sandervdo/jmonkeyengine,jMonkeyEngine/jmonkeyengine,amit2103/jmonkeyengine,rbottema/jmonkeyengine,nickschot/jmonkeyengine,atomixnmc/jmonkeyengine,d235j/jmonkeyengine,olafmaas/jmonkeyengine,danteinforno/jmonkeyengine,davidB/jmonkeyengine,amit2103/jmonkeyengine,shurun19851206/jMonkeyEngine,danteinforno/jmonkeyengine,Georgeto/jmonkeyengine,bsmr-java/jmonkeyengine,d235j/jmonkeyengine,bsmr-java/jmonkeyengine,bsmr-java/jmonkeyengine,zzuegg/jmonkeyengine,g-rocket/jmonkeyengine,Georgeto/jmonkeyengine,nickschot/jmonkeyengine,weilichuang/jmonkeyengine,GreenCubes/jmonkeyengine,wrvangeest/jmonkeyengine,skapi1992/jmonkeyengine,amit2103/jmonkeyengine,bertleft/jmonkeyengine,g-rocket/jmonkeyengine,davidB/jmonkeyengine,g-rocket/jmonkeyengine,danteinforno/jmonkeyengine,InShadow/jmonkeyengine,aaronang/jmonkeyengine,zzuegg/jmonkeyengine,phr00t/jmonkeyengine,phr00t/jmonkeyengine,d235j/jmonkeyengine,tr0k/jmonkeyengine,Georgeto/jmonkeyengine,jMonkeyEngine/jmonkeyengine,weilichuang/jmonkeyengine,OpenGrabeso/jmonkeyengine,shurun19851206/jMonkeyEngine,delftsre/jmonkeyengine,amit2103/jmonkeyengine,olafmaas/jmonkeyengine
/* * Copyright (c) 2009-2012 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' 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 com.jme3.scene.plugins.blender.objects; import java.nio.Buffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.ShortBuffer; import java.util.Collection; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import com.jme3.asset.BlenderKey.FeaturesToLoad; import com.jme3.math.FastMath; import com.jme3.math.Matrix4f; import com.jme3.math.Transform; import com.jme3.math.Vector3f; import com.jme3.scene.Geometry; import com.jme3.scene.Mesh.Mode; import com.jme3.scene.Node; import com.jme3.scene.Spatial; import com.jme3.scene.Spatial.CullHint; import com.jme3.scene.VertexBuffer.Type; import com.jme3.scene.plugins.blender.AbstractBlenderHelper; import com.jme3.scene.plugins.blender.BlenderContext; import com.jme3.scene.plugins.blender.BlenderContext.LoadedFeatureDataType; import com.jme3.scene.plugins.blender.animations.AnimationHelper; import com.jme3.scene.plugins.blender.cameras.CameraHelper; import com.jme3.scene.plugins.blender.constraints.ConstraintHelper; import com.jme3.scene.plugins.blender.curves.CurvesHelper; import com.jme3.scene.plugins.blender.file.BlenderFileException; import com.jme3.scene.plugins.blender.file.DynamicArray; import com.jme3.scene.plugins.blender.file.Pointer; import com.jme3.scene.plugins.blender.file.Structure; import com.jme3.scene.plugins.blender.lights.LightHelper; import com.jme3.scene.plugins.blender.meshes.MeshHelper; import com.jme3.scene.plugins.blender.modifiers.Modifier; import com.jme3.scene.plugins.blender.modifiers.ModifierHelper; import com.jme3.util.TempVars; /** * A class that is used in object calculations. * * @author Marcin Roguski (Kaelthas) */ public class ObjectHelper extends AbstractBlenderHelper { private static final Logger LOGGER = Logger.getLogger(ObjectHelper.class.getName()); public static final String OMA_MARKER = "oma"; public static final String ARMATURE_NODE_MARKER = "armature-node"; /** * This constructor parses the given blender version and stores the result. * Some functionalities may differ in different blender versions. * * @param blenderVersion * the version read from the blend file * @param blenderContext * the blender context */ public ObjectHelper(String blenderVersion, BlenderContext blenderContext) { super(blenderVersion, blenderContext); } /** * This method reads the given structure and createn an object that * represents the data. * * @param objectStructure * the object's structure * @param blenderContext * the blender context * @return blener's object representation or null if its type is excluded from loading * @throws BlenderFileException * an exception is thrown when the given data is inapropriate */ public Object toObject(Structure objectStructure, BlenderContext blenderContext) throws BlenderFileException { LOGGER.fine("Loading blender object."); int type = ((Number) objectStructure.getFieldValue("type")).intValue(); ObjectType objectType = ObjectType.valueOf(type); LOGGER.log(Level.FINE, "Type of the object: {0}.", objectType); if (objectType == ObjectType.LAMP && !blenderContext.getBlenderKey().shouldLoad(FeaturesToLoad.LIGHTS)) { LOGGER.fine("Lamps are not included in loading."); return null; } if (objectType == ObjectType.CAMERA && !blenderContext.getBlenderKey().shouldLoad(FeaturesToLoad.CAMERAS)) { LOGGER.fine("Cameras are not included in loading."); return null; } if (!blenderContext.getBlenderKey().shouldLoad(FeaturesToLoad.OBJECTS)) { LOGGER.fine("Objects are not included in loading."); return null; } int lay = ((Number) objectStructure.getFieldValue("lay")).intValue(); if ((lay & blenderContext.getBlenderKey().getLayersToLoad()) == 0) { LOGGER.fine("The layer this object is located in is not included in loading."); return null; } LOGGER.fine("Checking if the object has not been already loaded."); Object loadedResult = blenderContext.getLoadedFeature(objectStructure.getOldMemoryAddress(), LoadedFeatureDataType.LOADED_FEATURE); if (loadedResult != null) { return loadedResult; } blenderContext.pushParent(objectStructure); String name = objectStructure.getName(); LOGGER.log(Level.FINE, "Loading obejct: {0}", name); int restrictflag = ((Number) objectStructure.getFieldValue("restrictflag")).intValue(); boolean visible = (restrictflag & 0x01) != 0; Pointer pParent = (Pointer) objectStructure.getFieldValue("parent"); Object parent = blenderContext.getLoadedFeature(pParent.getOldMemoryAddress(), LoadedFeatureDataType.LOADED_FEATURE); if (parent == null && pParent.isNotNull()) { Structure parentStructure = pParent.fetchData().get(0); parent = this.toObject(parentStructure, blenderContext); } Transform t = this.getTransformation(objectStructure, blenderContext); LOGGER.log(Level.FINE, "Importing object of type: {0}", objectType); Node result = null; try { switch (objectType) { case EMPTY: case ARMATURE: // need to use an empty node to properly create // parent-children relationships between nodes result = new Node(name); break; case MESH: result = new Node(name); MeshHelper meshHelper = blenderContext.getHelper(MeshHelper.class); Pointer pMesh = (Pointer) objectStructure.getFieldValue("data"); List<Structure> meshesArray = pMesh.fetchData(); List<Geometry> geometries = meshHelper.toMesh(meshesArray.get(0), blenderContext); if (geometries != null) { for (Geometry geometry : geometries) { result.attachChild(geometry); } } break; case SURF: case CURVE: result = new Node(name); Pointer pCurve = (Pointer) objectStructure.getFieldValue("data"); if (pCurve.isNotNull()) { CurvesHelper curvesHelper = blenderContext.getHelper(CurvesHelper.class); Structure curveData = pCurve.fetchData().get(0); List<Geometry> curves = curvesHelper.toCurve(curveData, blenderContext); for (Geometry curve : curves) { result.attachChild(curve); } } break; case LAMP: Pointer pLamp = (Pointer) objectStructure.getFieldValue("data"); if (pLamp.isNotNull()) { LightHelper lightHelper = blenderContext.getHelper(LightHelper.class); List<Structure> lampsArray = pLamp.fetchData(); result = lightHelper.toLight(lampsArray.get(0), blenderContext); if(result == null) { //probably some light type is not supported, just create a node so that we can maintain child-parent relationship for nodes result = new Node(name); } } break; case CAMERA: Pointer pCamera = (Pointer) objectStructure.getFieldValue("data"); if (pCamera.isNotNull()) { CameraHelper cameraHelper = blenderContext.getHelper(CameraHelper.class); List<Structure> camerasArray = pCamera.fetchData(); result = cameraHelper.toCamera(camerasArray.get(0), blenderContext); } break; default: LOGGER.log(Level.WARNING, "Unsupported object type: {0}", type); } } finally { blenderContext.popParent(); } if (result != null) { LOGGER.fine("Storing loaded feature in blender context and applying markers (those will be removed before the final result is released)."); blenderContext.addLoadedFeatures(objectStructure.getOldMemoryAddress(), name, objectStructure, result); blenderContext.addMarker(OMA_MARKER, result, objectStructure.getOldMemoryAddress()); if (objectType == ObjectType.ARMATURE) { blenderContext.addMarker(ARMATURE_NODE_MARKER, result, Boolean.TRUE); } result.setLocalTransform(t); result.setCullHint(visible ? CullHint.Always : CullHint.Inherit); if (parent instanceof Node) { ((Node) parent).attachChild(result); } if (result.getChildren() != null) { for (Spatial child : result.getChildren()) { if (child instanceof Geometry) { this.flipMeshIfRequired((Geometry) child, child.getWorldScale()); } } } LOGGER.fine("Reading and applying object's modifiers."); ModifierHelper modifierHelper = blenderContext.getHelper(ModifierHelper.class); Collection<Modifier> modifiers = modifierHelper.readModifiers(objectStructure, blenderContext); for (Modifier modifier : modifiers) { modifier.apply(result, blenderContext); } // I prefer do compute bounding box here than read it from the file result.updateModelBound(); LOGGER.fine("Applying animations to the object if such are defined."); AnimationHelper animationHelper = blenderContext.getHelper(AnimationHelper.class); animationHelper.applyAnimations(result, blenderContext.getBlenderKey().getNodeAnimationNames(name)); LOGGER.fine("Loading constraints connected with this object."); ConstraintHelper constraintHelper = blenderContext.getHelper(ConstraintHelper.class); constraintHelper.loadConstraints(objectStructure, blenderContext); LOGGER.fine("Loading custom properties."); if (blenderContext.getBlenderKey().isLoadObjectProperties()) { Properties properties = this.loadProperties(objectStructure, blenderContext); // the loaded property is a group property, so we need to get // each value and set it to Spatial if (properties != null && properties.getValue() != null) { this.applyProperties(result, properties); } } } return result; } /** * The method flips the mesh if the scale is mirroring it. Mirroring scale has either 1 or all 3 factors negative. * If two factors are negative then there is no mirroring because a rotation and translation can be found that will * lead to the same transform when all scales are positive. * * @param geometry * the geometry that is being flipped if necessary * @param scale * the scale vector of the given geometry */ private void flipMeshIfRequired(Geometry geometry, Vector3f scale) { float s = scale.x * scale.y * scale.z; if (s < 0 && geometry.getMesh() != null) {// negative s means that the scale is mirroring the object FloatBuffer normals = geometry.getMesh().getFloatBuffer(Type.Normal); if (normals != null) { for (int i = 0; i < normals.limit(); i += 3) { if (scale.x < 0) { normals.put(i, -normals.get(i)); } if (scale.y < 0) { normals.put(i + 1, -normals.get(i + 1)); } if (scale.z < 0) { normals.put(i + 2, -normals.get(i + 2)); } } } if (geometry.getMesh().getMode() == Mode.Triangles) {// there is no need to flip the indexes for lines and points LOGGER.finer("Flipping index order in triangle mesh."); Buffer indexBuffer = geometry.getMesh().getBuffer(Type.Index).getData(); for (int i = 0; i < indexBuffer.limit(); i += 3) { if (indexBuffer instanceof ShortBuffer) { short index = ((ShortBuffer) indexBuffer).get(i + 1); ((ShortBuffer) indexBuffer).put(i + 1, ((ShortBuffer) indexBuffer).get(i + 2)); ((ShortBuffer) indexBuffer).put(i + 2, index); } else { int index = ((IntBuffer) indexBuffer).get(i + 1); ((IntBuffer) indexBuffer).put(i + 1, ((IntBuffer) indexBuffer).get(i + 2)); ((IntBuffer) indexBuffer).put(i + 2, index); } } } } } /** * Checks if the first given OMA points to a parent of the second one. * The parent need not to be the direct one. This method should be called when we are sure * that both of the features are alred loaded because it does not check it. * The OMA's should point to a spatials, otherwise the function will throw ClassCastException. * @param supposedParentOMA * the OMA of the node that we suppose might be a parent of the second one * @param spatialOMA * the OMA of the scene's node * @return <b>true</b> if the first given OMA points to a parent of the second one and <b>false</b> otherwise */ public boolean isParent(Long supposedParentOMA, Long spatialOMA) { Spatial supposedParent = (Spatial) blenderContext.getLoadedFeature(supposedParentOMA, LoadedFeatureDataType.LOADED_FEATURE); Spatial spatial = (Spatial) blenderContext.getLoadedFeature(spatialOMA, LoadedFeatureDataType.LOADED_FEATURE); Spatial parent = spatial.getParent(); while (parent != null) { if (parent.equals(supposedParent)) { return true; } parent = parent.getParent(); } return false; } /** * This method calculates local transformation for the object. Parentage is * taken under consideration. * * @param objectStructure * the object's structure * @return objects transformation relative to its parent */ public Transform getTransformation(Structure objectStructure, BlenderContext blenderContext) { TempVars tempVars = TempVars.get(); Matrix4f parentInv = tempVars.tempMat4; Pointer pParent = (Pointer) objectStructure.getFieldValue("parent"); if (pParent.isNotNull()) { Structure parentObjectStructure = (Structure) blenderContext.getLoadedFeature(pParent.getOldMemoryAddress(), LoadedFeatureDataType.LOADED_STRUCTURE); this.getMatrix(parentObjectStructure, "obmat", fixUpAxis, parentInv).invertLocal(); } else { parentInv.loadIdentity(); } Matrix4f globalMatrix = this.getMatrix(objectStructure, "obmat", fixUpAxis, tempVars.tempMat42); Matrix4f localMatrix = parentInv.multLocal(globalMatrix); this.getSizeSignums(objectStructure, tempVars.vect1); localMatrix.toTranslationVector(tempVars.vect2); localMatrix.toRotationQuat(tempVars.quat1); localMatrix.toScaleVector(tempVars.vect3); Transform t = new Transform(tempVars.vect2, tempVars.quat1.normalizeLocal(), tempVars.vect3.multLocal(tempVars.vect1)); tempVars.release(); return t; } /** * The method gets the signs of the scale factors and stores them properly in the given vector. * @param objectStructure * the object's structure * @param store * the vector where the result will be stored */ @SuppressWarnings("unchecked") private void getSizeSignums(Structure objectStructure, Vector3f store) { DynamicArray<Number> size = (DynamicArray<Number>) objectStructure.getFieldValue("size"); if (fixUpAxis) { store.x = Math.signum(size.get(0).floatValue()); store.y = Math.signum(size.get(2).floatValue()); store.z = Math.signum(size.get(1).floatValue()); } else { store.x = Math.signum(size.get(0).floatValue()); store.y = Math.signum(size.get(1).floatValue()); store.z = Math.signum(size.get(2).floatValue()); } } /** * This method returns the matrix of a given name for the given structure. * It takes up axis into consideration. * * The method that moves the matrix from Z-up axis to Y-up axis space is as follows: * - load the matrix directly from blender (it has the Z-up axis orientation) * - switch the second and third rows in the matrix * - switch the second and third column in the matrix * - multiply the values in the third row by -1 * - multiply the values in the third column by -1 * * The result matrix is now in Y-up axis orientation. * The procedure was discovered by experimenting but it looks like it's working :) * The previous procedure transformet the loaded matrix into component (loc, rot, scale), * switched several values and pu the back into the matrix. * It worked fine until models with negative scale are used. * The current method is not touched by that flaw. * * @param structure * the structure with matrix data * @param matrixName * the name of the matrix * @param fixUpAxis * tells if the Y axis is a UP axis * @param store * the matrix where the result will pe placed * @return the required matrix */ @SuppressWarnings("unchecked") private Matrix4f getMatrix(Structure structure, String matrixName, boolean fixUpAxis, Matrix4f store) { DynamicArray<Number> obmat = (DynamicArray<Number>) structure.getFieldValue(matrixName); // the matrix must be square int rowAndColumnSize = Math.abs((int) Math.sqrt(obmat.getTotalSize())); for (int i = 0; i < rowAndColumnSize; ++i) { for (int j = 0; j < rowAndColumnSize; ++j) { float value = obmat.get(j, i).floatValue(); if (Math.abs(value) <= FastMath.FLT_EPSILON) { value = 0; } store.set(i, j, value); } } if (fixUpAxis) { // first switch the second and third row for (int i = 0; i < 4; ++i) { float temp = store.get(1, i); store.set(1, i, store.get(2, i)); store.set(2, i, temp); } // then switch the second and third column for (int i = 0; i < 4; ++i) { float temp = store.get(i, 1); store.set(i, 1, store.get(i, 2)); store.set(i, 2, temp); } // multiply the values in the third row by -1 store.m20 *= -1; store.m21 *= -1; store.m22 *= -1; store.m23 *= -1; // multiply the values in the third column by -1 store.m02 *= -1; store.m12 *= -1; store.m22 *= -1; store.m32 *= -1; } return store; } /** * This method returns the matrix of a given name for the given structure. * It takes up axis into consideration. * * @param structure * the structure with matrix data * @param matrixName * the name of the matrix * @param fixUpAxis * tells if the Y axis is a UP axis * @return the required matrix */ public Matrix4f getMatrix(Structure structure, String matrixName, boolean fixUpAxis) { return this.getMatrix(structure, matrixName, fixUpAxis, new Matrix4f()); } private static enum ObjectType { EMPTY(0), MESH(1), CURVE(2), SURF(3), TEXT(4), METABALL(5), LAMP(10), CAMERA(11), WAVE(21), LATTICE(22), ARMATURE(25); private int blenderTypeValue; private ObjectType(int blenderTypeValue) { this.blenderTypeValue = blenderTypeValue; } public static ObjectType valueOf(int blenderTypeValue) throws BlenderFileException { for (ObjectType type : ObjectType.values()) { if (type.blenderTypeValue == blenderTypeValue) { return type; } } throw new BlenderFileException("Unknown type value: " + blenderTypeValue); } } }
engine/src/blender/com/jme3/scene/plugins/blender/objects/ObjectHelper.java
/* * Copyright (c) 2009-2012 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' 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 com.jme3.scene.plugins.blender.objects; import java.nio.Buffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.ShortBuffer; import java.util.Collection; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import com.jme3.asset.BlenderKey.FeaturesToLoad; import com.jme3.math.FastMath; import com.jme3.math.Matrix4f; import com.jme3.math.Transform; import com.jme3.math.Vector3f; import com.jme3.scene.Geometry; import com.jme3.scene.Mesh.Mode; import com.jme3.scene.Node; import com.jme3.scene.Spatial; import com.jme3.scene.Spatial.CullHint; import com.jme3.scene.VertexBuffer.Type; import com.jme3.scene.plugins.blender.AbstractBlenderHelper; import com.jme3.scene.plugins.blender.BlenderContext; import com.jme3.scene.plugins.blender.BlenderContext.LoadedFeatureDataType; import com.jme3.scene.plugins.blender.animations.AnimationHelper; import com.jme3.scene.plugins.blender.cameras.CameraHelper; import com.jme3.scene.plugins.blender.constraints.ConstraintHelper; import com.jme3.scene.plugins.blender.curves.CurvesHelper; import com.jme3.scene.plugins.blender.file.BlenderFileException; import com.jme3.scene.plugins.blender.file.DynamicArray; import com.jme3.scene.plugins.blender.file.Pointer; import com.jme3.scene.plugins.blender.file.Structure; import com.jme3.scene.plugins.blender.lights.LightHelper; import com.jme3.scene.plugins.blender.meshes.MeshHelper; import com.jme3.scene.plugins.blender.modifiers.Modifier; import com.jme3.scene.plugins.blender.modifiers.ModifierHelper; import com.jme3.util.TempVars; /** * A class that is used in object calculations. * * @author Marcin Roguski (Kaelthas) */ public class ObjectHelper extends AbstractBlenderHelper { private static final Logger LOGGER = Logger.getLogger(ObjectHelper.class.getName()); public static final String OMA_MARKER = "oma"; public static final String ARMATURE_NODE_MARKER = "armature-node"; /** * This constructor parses the given blender version and stores the result. * Some functionalities may differ in different blender versions. * * @param blenderVersion * the version read from the blend file * @param blenderContext * the blender context */ public ObjectHelper(String blenderVersion, BlenderContext blenderContext) { super(blenderVersion, blenderContext); } /** * This method reads the given structure and createn an object that * represents the data. * * @param objectStructure * the object's structure * @param blenderContext * the blender context * @return blener's object representation or null if its type is excluded from loading * @throws BlenderFileException * an exception is thrown when the given data is inapropriate */ public Object toObject(Structure objectStructure, BlenderContext blenderContext) throws BlenderFileException { LOGGER.fine("Loading blender object."); int type = ((Number) objectStructure.getFieldValue("type")).intValue(); ObjectType objectType = ObjectType.valueOf(type); LOGGER.log(Level.FINE, "Type of the object: {0}.", objectType); if (objectType == ObjectType.LAMP && !blenderContext.getBlenderKey().shouldLoad(FeaturesToLoad.LIGHTS)) { LOGGER.fine("Lamps are not included in loading."); return null; } if (objectType == ObjectType.CAMERA && !blenderContext.getBlenderKey().shouldLoad(FeaturesToLoad.CAMERAS)) { LOGGER.fine("Cameras are not included in loading."); return null; } if (!blenderContext.getBlenderKey().shouldLoad(FeaturesToLoad.OBJECTS)) { LOGGER.fine("Objects are not included in loading."); return null; } int lay = ((Number) objectStructure.getFieldValue("lay")).intValue(); if ((lay & blenderContext.getBlenderKey().getLayersToLoad()) == 0) { LOGGER.fine("The layer this object is located in is not included in loading."); return null; } LOGGER.fine("Checking if the object has not been already loaded."); Object loadedResult = blenderContext.getLoadedFeature(objectStructure.getOldMemoryAddress(), LoadedFeatureDataType.LOADED_FEATURE); if (loadedResult != null) { return loadedResult; } blenderContext.pushParent(objectStructure); String name = objectStructure.getName(); LOGGER.log(Level.FINE, "Loading obejct: {0}", name); int restrictflag = ((Number) objectStructure.getFieldValue("restrictflag")).intValue(); boolean visible = (restrictflag & 0x01) != 0; Pointer pParent = (Pointer) objectStructure.getFieldValue("parent"); Object parent = blenderContext.getLoadedFeature(pParent.getOldMemoryAddress(), LoadedFeatureDataType.LOADED_FEATURE); if (parent == null && pParent.isNotNull()) { Structure parentStructure = pParent.fetchData().get(0); parent = this.toObject(parentStructure, blenderContext); } Transform t = this.getTransformation(objectStructure, blenderContext); LOGGER.log(Level.FINE, "Importing object of type: {0}", objectType); Node result = null; try { switch (objectType) { case EMPTY: case ARMATURE: // need to use an empty node to properly create // parent-children relationships between nodes result = new Node(name); break; case MESH: result = new Node(name); MeshHelper meshHelper = blenderContext.getHelper(MeshHelper.class); Pointer pMesh = (Pointer) objectStructure.getFieldValue("data"); List<Structure> meshesArray = pMesh.fetchData(); List<Geometry> geometries = meshHelper.toMesh(meshesArray.get(0), blenderContext); if (geometries != null) { for (Geometry geometry : geometries) { result.attachChild(geometry); } } break; case SURF: case CURVE: result = new Node(name); Pointer pCurve = (Pointer) objectStructure.getFieldValue("data"); if (pCurve.isNotNull()) { CurvesHelper curvesHelper = blenderContext.getHelper(CurvesHelper.class); Structure curveData = pCurve.fetchData().get(0); List<Geometry> curves = curvesHelper.toCurve(curveData, blenderContext); for (Geometry curve : curves) { result.attachChild(curve); } } break; case LAMP: Pointer pLamp = (Pointer) objectStructure.getFieldValue("data"); if (pLamp.isNotNull()) { LightHelper lightHelper = blenderContext.getHelper(LightHelper.class); List<Structure> lampsArray = pLamp.fetchData(); result = lightHelper.toLight(lampsArray.get(0), blenderContext); } break; case CAMERA: Pointer pCamera = (Pointer) objectStructure.getFieldValue("data"); if (pCamera.isNotNull()) { CameraHelper cameraHelper = blenderContext.getHelper(CameraHelper.class); List<Structure> camerasArray = pCamera.fetchData(); result = cameraHelper.toCamera(camerasArray.get(0), blenderContext); } break; default: LOGGER.log(Level.WARNING, "Unsupported object type: {0}", type); } } finally { blenderContext.popParent(); } if (result != null) { LOGGER.fine("Storing loaded feature in blender context and applying markers (those will be removed before the final result is released)."); blenderContext.addLoadedFeatures(objectStructure.getOldMemoryAddress(), name, objectStructure, result); blenderContext.addMarker(OMA_MARKER, result, objectStructure.getOldMemoryAddress()); if (objectType == ObjectType.ARMATURE) { blenderContext.addMarker(ARMATURE_NODE_MARKER, result, Boolean.TRUE); } result.setLocalTransform(t); result.setCullHint(visible ? CullHint.Always : CullHint.Inherit); if (parent instanceof Node) { ((Node) parent).attachChild(result); } if (result.getChildren() != null) { for (Spatial child : result.getChildren()) { if (child instanceof Geometry) { this.flipMeshIfRequired((Geometry) child, child.getWorldScale()); } } } LOGGER.fine("Reading and applying object's modifiers."); ModifierHelper modifierHelper = blenderContext.getHelper(ModifierHelper.class); Collection<Modifier> modifiers = modifierHelper.readModifiers(objectStructure, blenderContext); for (Modifier modifier : modifiers) { modifier.apply(result, blenderContext); } // I prefer do compute bounding box here than read it from the file result.updateModelBound(); LOGGER.fine("Applying animations to the object if such are defined."); AnimationHelper animationHelper = blenderContext.getHelper(AnimationHelper.class); animationHelper.applyAnimations(result, blenderContext.getBlenderKey().getNodeAnimationNames(name)); LOGGER.fine("Loading constraints connected with this object."); ConstraintHelper constraintHelper = blenderContext.getHelper(ConstraintHelper.class); constraintHelper.loadConstraints(objectStructure, blenderContext); LOGGER.fine("Loading custom properties."); if (blenderContext.getBlenderKey().isLoadObjectProperties()) { Properties properties = this.loadProperties(objectStructure, blenderContext); // the loaded property is a group property, so we need to get // each value and set it to Spatial if (properties != null && properties.getValue() != null) { this.applyProperties(result, properties); } } } return result; } /** * The method flips the mesh if the scale is mirroring it. Mirroring scale has either 1 or all 3 factors negative. * If two factors are negative then there is no mirroring because a rotation and translation can be found that will * lead to the same transform when all scales are positive. * * @param geometry * the geometry that is being flipped if necessary * @param scale * the scale vector of the given geometry */ private void flipMeshIfRequired(Geometry geometry, Vector3f scale) { float s = scale.x * scale.y * scale.z; if (s < 0 && geometry.getMesh() != null) {// negative s means that the scale is mirroring the object FloatBuffer normals = geometry.getMesh().getFloatBuffer(Type.Normal); if (normals != null) { for (int i = 0; i < normals.limit(); i += 3) { if (scale.x < 0) { normals.put(i, -normals.get(i)); } if (scale.y < 0) { normals.put(i + 1, -normals.get(i + 1)); } if (scale.z < 0) { normals.put(i + 2, -normals.get(i + 2)); } } } if (geometry.getMesh().getMode() == Mode.Triangles) {// there is no need to flip the indexes for lines and points LOGGER.finer("Flipping index order in triangle mesh."); Buffer indexBuffer = geometry.getMesh().getBuffer(Type.Index).getData(); for (int i = 0; i < indexBuffer.limit(); i += 3) { if (indexBuffer instanceof ShortBuffer) { short index = ((ShortBuffer) indexBuffer).get(i + 1); ((ShortBuffer) indexBuffer).put(i + 1, ((ShortBuffer) indexBuffer).get(i + 2)); ((ShortBuffer) indexBuffer).put(i + 2, index); } else { int index = ((IntBuffer) indexBuffer).get(i + 1); ((IntBuffer) indexBuffer).put(i + 1, ((IntBuffer) indexBuffer).get(i + 2)); ((IntBuffer) indexBuffer).put(i + 2, index); } } } } } /** * Checks if the first given OMA points to a parent of the second one. * The parent need not to be the direct one. This method should be called when we are sure * that both of the features are alred loaded because it does not check it. * The OMA's should point to a spatials, otherwise the function will throw ClassCastException. * @param supposedParentOMA * the OMA of the node that we suppose might be a parent of the second one * @param spatialOMA * the OMA of the scene's node * @return <b>true</b> if the first given OMA points to a parent of the second one and <b>false</b> otherwise */ public boolean isParent(Long supposedParentOMA, Long spatialOMA) { Spatial supposedParent = (Spatial) blenderContext.getLoadedFeature(supposedParentOMA, LoadedFeatureDataType.LOADED_FEATURE); Spatial spatial = (Spatial) blenderContext.getLoadedFeature(spatialOMA, LoadedFeatureDataType.LOADED_FEATURE); Spatial parent = spatial.getParent(); while (parent != null) { if (parent.equals(supposedParent)) { return true; } parent = parent.getParent(); } return false; } /** * This method calculates local transformation for the object. Parentage is * taken under consideration. * * @param objectStructure * the object's structure * @return objects transformation relative to its parent */ public Transform getTransformation(Structure objectStructure, BlenderContext blenderContext) { TempVars tempVars = TempVars.get(); Matrix4f parentInv = tempVars.tempMat4; Pointer pParent = (Pointer) objectStructure.getFieldValue("parent"); if (pParent.isNotNull()) { Structure parentObjectStructure = (Structure) blenderContext.getLoadedFeature(pParent.getOldMemoryAddress(), LoadedFeatureDataType.LOADED_STRUCTURE); this.getMatrix(parentObjectStructure, "obmat", fixUpAxis, parentInv).invertLocal(); } else { parentInv.loadIdentity(); } Matrix4f globalMatrix = this.getMatrix(objectStructure, "obmat", fixUpAxis, tempVars.tempMat42); Matrix4f localMatrix = parentInv.multLocal(globalMatrix); this.getSizeSignums(objectStructure, tempVars.vect1); localMatrix.toTranslationVector(tempVars.vect2); localMatrix.toRotationQuat(tempVars.quat1); localMatrix.toScaleVector(tempVars.vect3); Transform t = new Transform(tempVars.vect2, tempVars.quat1.normalizeLocal(), tempVars.vect3.multLocal(tempVars.vect1)); tempVars.release(); return t; } /** * The method gets the signs of the scale factors and stores them properly in the given vector. * @param objectStructure * the object's structure * @param store * the vector where the result will be stored */ @SuppressWarnings("unchecked") private void getSizeSignums(Structure objectStructure, Vector3f store) { DynamicArray<Number> size = (DynamicArray<Number>) objectStructure.getFieldValue("size"); if (fixUpAxis) { store.x = Math.signum(size.get(0).floatValue()); store.y = Math.signum(size.get(2).floatValue()); store.z = Math.signum(size.get(1).floatValue()); } else { store.x = Math.signum(size.get(0).floatValue()); store.y = Math.signum(size.get(1).floatValue()); store.z = Math.signum(size.get(2).floatValue()); } } /** * This method returns the matrix of a given name for the given structure. * It takes up axis into consideration. * * The method that moves the matrix from Z-up axis to Y-up axis space is as follows: * - load the matrix directly from blender (it has the Z-up axis orientation) * - switch the second and third rows in the matrix * - switch the second and third column in the matrix * - multiply the values in the third row by -1 * - multiply the values in the third column by -1 * * The result matrix is now in Y-up axis orientation. * The procedure was discovered by experimenting but it looks like it's working :) * The previous procedure transformet the loaded matrix into component (loc, rot, scale), * switched several values and pu the back into the matrix. * It worked fine until models with negative scale are used. * The current method is not touched by that flaw. * * @param structure * the structure with matrix data * @param matrixName * the name of the matrix * @param fixUpAxis * tells if the Y axis is a UP axis * @param store * the matrix where the result will pe placed * @return the required matrix */ @SuppressWarnings("unchecked") private Matrix4f getMatrix(Structure structure, String matrixName, boolean fixUpAxis, Matrix4f store) { DynamicArray<Number> obmat = (DynamicArray<Number>) structure.getFieldValue(matrixName); // the matrix must be square int rowAndColumnSize = Math.abs((int) Math.sqrt(obmat.getTotalSize())); for (int i = 0; i < rowAndColumnSize; ++i) { for (int j = 0; j < rowAndColumnSize; ++j) { float value = obmat.get(j, i).floatValue(); if (Math.abs(value) <= FastMath.FLT_EPSILON) { value = 0; } store.set(i, j, value); } } if (fixUpAxis) { // first switch the second and third row for (int i = 0; i < 4; ++i) { float temp = store.get(1, i); store.set(1, i, store.get(2, i)); store.set(2, i, temp); } // then switch the second and third column for (int i = 0; i < 4; ++i) { float temp = store.get(i, 1); store.set(i, 1, store.get(i, 2)); store.set(i, 2, temp); } // multiply the values in the third row by -1 store.m20 *= -1; store.m21 *= -1; store.m22 *= -1; store.m23 *= -1; // multiply the values in the third column by -1 store.m02 *= -1; store.m12 *= -1; store.m22 *= -1; store.m32 *= -1; } return store; } /** * This method returns the matrix of a given name for the given structure. * It takes up axis into consideration. * * @param structure * the structure with matrix data * @param matrixName * the name of the matrix * @param fixUpAxis * tells if the Y axis is a UP axis * @return the required matrix */ public Matrix4f getMatrix(Structure structure, String matrixName, boolean fixUpAxis) { return this.getMatrix(structure, matrixName, fixUpAxis, new Matrix4f()); } private static enum ObjectType { EMPTY(0), MESH(1), CURVE(2), SURF(3), TEXT(4), METABALL(5), LAMP(10), CAMERA(11), WAVE(21), LATTICE(22), ARMATURE(25); private int blenderTypeValue; private ObjectType(int blenderTypeValue) { this.blenderTypeValue = blenderTypeValue; } public static ObjectType valueOf(int blenderTypeValue) throws BlenderFileException { for (ObjectType type : ObjectType.values()) { if (type.blenderTypeValue == blenderTypeValue) { return type; } } throw new BlenderFileException("Unknown type value: " + blenderTypeValue); } } }
Bugfix: fixed an issue that could cause NPE when lamp that is not supported in JME ('Hemi' light for example) had children nodes attached. git-svn-id: f9411aee4f13664f2fc428a5b3e824fe43a079a3@11062 75d07b2b-3a1a-0410-a2c5-0572b91ccdca
engine/src/blender/com/jme3/scene/plugins/blender/objects/ObjectHelper.java
Bugfix: fixed an issue that could cause NPE when lamp that is not supported in JME ('Hemi' light for example) had children nodes attached.
Java
bsd-3-clause
ac5f5a5451774b3bd9955a73f9476be39dfd15cf
0
credentials/irma_android_cardemu
package org.irmacard.cardemu.selfenrol; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; import com.google.gson.JsonSyntaxException; import com.google.gson.reflect.TypeToken; import net.sf.scuba.smartcards.*; import net.sf.scuba.tlv.TLVInputStream; import net.sf.scuba.tlv.TLVOutputStream; import org.acra.ACRA; import org.irmacard.cardemu.CardManager; import org.irmacard.cardemu.R; import org.irmacard.cardemu.httpclient.HttpClientException; import org.irmacard.credentials.Attributes; import org.irmacard.credentials.CredentialsException; import org.irmacard.credentials.idemix.IdemixCredentials; import org.irmacard.credentials.idemix.descriptions.IdemixVerificationDescription; import org.irmacard.credentials.idemix.smartcard.SmartCardEmulatorService; import org.irmacard.credentials.info.CredentialIdentifier; import org.irmacard.credentials.info.InfoException; import org.irmacard.idemix.IdemixService; import org.irmacard.idemix.IdemixSmartcard; import org.irmacard.mno.common.*; import org.jmrtd.PassportService; import org.jmrtd.Util; import org.jmrtd.lds.DG14File; import org.jmrtd.lds.DG15File; import org.jmrtd.lds.SODFile; import javax.crypto.Cipher; import javax.crypto.Mac; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.Type; import java.security.*; import java.util.HashMap; import java.util.Map; import java.util.Random; public class DriversLicenseEnrollActivity extends AbstractNFCEnrollActivity { // Configuration private static final String TAG = "DriversLicenseEnrollAct"; public static final int DriversLicenseEnrollActivityCode = 400; private static final int SCREEN_BAC = 2; private static final int SCREEN_PASSPORT = 3; private static final int SCREEN_ISSUE = 4; // State variables //private EDLDataMessage eDLMsg = null; protected int tagReadAttempt = 0; @Override protected String getURLPath() { return "/dl"; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setNfcScreen(SCREEN_PASSPORT); // Get the BasicClientMessage containing our nonce to send to the passport. getEnrollmentSession(new Handler() { @Override public void handleMessage(Message msg) { EnrollmentStartResult result = (EnrollmentStartResult) msg.obj; if (result.exception != null) { // Something went wrong showErrorScreen(result.errorId); } else { TextView connectedTextView = (TextView) findViewById(R.id.se_connected); connectedTextView.setTextColor(getResources().getColor(R.color.irmagreen)); connectedTextView.setText(R.string.se_connected_mno); findViewById(R.id.se_feedback_text).setVisibility(View.VISIBLE); findViewById(R.id.se_progress_bar).setVisibility(View.VISIBLE); } } }); // Spongycastle provides the MAC ISO9797Alg3Mac, which JMRTD usesin the doBAC method below (at // DESedeSecureMessagingWrapper.java, line 115) Security.addProvider(new org.spongycastle.jce.provider.BouncyCastleProvider()); // Update the UI setContentView(R.layout.enroll_activity_passport); screen = SCREEN_PASSPORT; updateProgressCounter(); // The next advanceScreen() is called when the passport reading was successful (see onPostExecute() in // readPassport() above). Thus, if no passport arrives or we can't successfully read it, we have to // ensure here that we don't stay on the passport screen forever with this timeout. new Handler().postDelayed(new Runnable() { @Override public void run() { if (screen == SCREEN_PASSPORT && (documentMsg == null || !documentMsg.isComplete())) { showErrorScreen(getString(R.string.error_enroll_passporterror)); } } }, MAX_TAG_READ_TIME); } @Override void handleNfcEvent(CardService service, EnrollmentStartMessage message) { TextView feedbackTextView = (TextView) findViewById(R.id.se_feedback_text); if (feedbackTextView != null) { feedbackTextView.setText(R.string.feedback_communicating_driverslicense); } try { service.open(); PassportService passportService = new PassportService(service); if (documentMsg == null) { documentMsg = new EDLDataMessage(message.getSessionToken(), imsi, message.getNonce()); } readDriversLicense(passportService, documentMsg); } catch (CardServiceException e) { // TODO under what circumstances does this happen? Maybe handle it more intelligently? ACRA.getErrorReporter().handleException(e); showErrorScreen(getString(R.string.error_enroll_driverslicense_error), getString(R.string.abort), 0, getString(R.string.retry), SCREEN_PASSPORT); } } @Override protected void advanceScreen() { switch (screen) { case SCREEN_PASSPORT: setContentView(R.layout.enroll_activity_issue); screen = SCREEN_ISSUE; updateProgressCounter(); // Save the card before messing with it so we can roll back if // something goes wrong CardManager.storeCard(); // Do it! enroll(new Handler() { @Override public void handleMessage(Message msg) { if (msg.obj == null) { // Success, save our new credentials CardManager.storeCard(); enableContinueButton(); findViewById(R.id.se_done_text).setVisibility(View.VISIBLE); } else { // Rollback the card card = CardManager.loadCard(); is = new IdemixService(new SmartCardEmulatorService(card)); if (msg.what != 0) // .what may contain a string identifier saying what went wrong showErrorScreen(msg.what); else showErrorScreen(R.string.unknown_error); } } }); break; case SCREEN_ISSUE: case SCREEN_ERROR: screen = SCREEN_START; finish(); break; default: Log.e(TAG, "Error, screen switch fall through"); break; } } public synchronized void doBAP(PassportService ps, String mrz) throws CardServiceException { if (mrz != null && mrz.length()>0) { try { String kdoc = mrz.substring(1, mrz.length() - 1); byte[] keySeed = computeKeySeedForBAP(kdoc); SecretKey kEnc = Util.deriveKey(keySeed, Util.ENC_MODE); SecretKey kMac = Util.deriveKey(keySeed, Util.MAC_MODE); try { //the eDL BAC is actually the same as the BAC for passports ps.doBAC(kEnc,kMac); } catch (CardServiceException cse) { Log.e(TAG,"BAP failed"); Log.e(TAG, cse.getMessage().toString()); throw cse; } } catch (GeneralSecurityException gse) { Log.e(TAG,gse.getStackTrace().toString()); throw new CardServiceException(gse.toString()); } } else { Log.e(TAG,"no valid MRZ found"); //TODO error no valid mrz string } } private static byte[] computeKeySeedForBAP(String kdoc) throws GeneralSecurityException { if (kdoc == null || kdoc.length() < 6) { throw new IllegalArgumentException("Wrong document key for drivers license, found " + kdoc); } MessageDigest shaDigest = MessageDigest.getInstance("SHA-1"); shaDigest.update(getBytes(kdoc)); byte[] hash = shaDigest.digest(); //truncate byte[] keySeed = new byte[16]; System.arraycopy(hash, 0, keySeed, 0, 16); return keySeed; } //helper function from JMRTD Util. Unchanged. private static byte[] getBytes(String str) { byte[] bytes = str.getBytes(); try { bytes = str.getBytes("UTF-8"); } catch (UnsupportedEncodingException use) { /* NOTE: unlikely. */ Log.e(TAG,"Exception: " + use.getMessage()); } return bytes; } /** * Reads the datagroups 1, 14 and 15, and the SOD file and requests an active authentication from an e-passport * in a seperate thread. */ private void readDriversLicense(PassportService ps, DocumentDataMessage eDLMessage) { new AsyncTask<Object,Void,EDLDataMessage>(){ ProgressBar progressBar = (ProgressBar) findViewById(R.id.se_progress_bar); boolean passportError = false; boolean bacError = false; long start; long stop; @Override protected EDLDataMessage doInBackground(Object... params) { if (params.length <2) { return null; //TODO appropriate error } PassportService ps = (PassportService) params[0]; EDLDataMessage eDLMessage = (EDLDataMessage) params[1]; if (tagReadAttempt == 0) { start = System.currentTimeMillis(); } tagReadAttempt++; // Do the BAC separately from generating the eDLMessage, so we can be specific in our error message if // necessary. (Note: the IllegalStateException should not happen, but if it does for some unforseen // reason there is no need to let it crash the app.) String mrz = settings.getString("mrz", ""); try { doBAP(ps, mrz); Log.i(TAG, "BAP Succeeded"); } catch (CardServiceException | IllegalStateException e) { bacError = true; Log.e(TAG, "doing BAP failed"); return null; } //If we get here, the BAP succeeded. Which means the MRZ was correct, so we can trust the documentNumber if (eDLMessage.getDocumentNr() == null){ eDLMessage.setDocumentNr(mrz.substring(5,15)); } Exception ex = null; try { Log.i(TAG, "PassportEnrollActivity: reading attempt " + tagReadAttempt); generateEDLDataMessage(ps, eDLMessage); } catch (IOException |CardServiceException e) { Log.w(TAG, "PassportEnrollActivity: reading attempt " + tagReadAttempt + " failed, stack trace:"); Log.w(TAG, " " + e.getMessage()); ex = e; } passportError = !eDLMessage.isComplete(); if (!eDLMessage.isComplete() && tagReadAttempt == MAX_TAG_READ_ATTEMPTS && ex != null) { // Build a fancy report saying which fields we did and which we did not manage to get Log.e(TAG, "PassportEnrollActivity: too many attempts failed, aborting"); ACRA.getErrorReporter().reportBuilder() .customData("sod", String.valueOf(eDLMessage.getSodFile() == null)) .customData("dg1File", String.valueOf(eDLMessage.getDg1File() == null)) .customData("dg14File", String.valueOf(eDLMessage.getDg14File() == null)) .customData("dg13File", String.valueOf(eDLMessage.getDg13File() == null)) .customData("response", String.valueOf(eDLMessage.getResponse() == null)) .exception(ex) .send(); } publishProgress(); return eDLMessage; } @Override protected void onProgressUpdate(Void... values) { if (progressBar != null) { // progressBar can vanish if the progress goes wrong halfway through progressBar.incrementProgressBy(1); } } /* we need this method for now to be able to send secured APDUs to cards */ private ResponseAPDU transmitWrappedAPDU (PassportService ps, CommandAPDU capdu) throws CardServiceException { APDUWrapper wrapper = ps.getWrapper(); if (wrapper == null){ throw new NullPointerException("No wrapper was set for secure messaging"); } CommandAPDU wcapdu = wrapper.wrap(capdu); ResponseAPDU wrapdu = ps.transmit(wcapdu); return wrapper.unwrap(wrapdu, wrapdu.getBytes().length); } protected byte[] readDg1File(InputStream inputStream) throws IOException { int dataGroupTag = 0x61; TLVInputStream tlvIn = inputStream instanceof TLVInputStream ? (TLVInputStream)inputStream : new TLVInputStream(inputStream); int tag = tlvIn.readTag(); if (tag != dataGroupTag) { throw new IllegalArgumentException("Was expecting tag " + Integer.toHexString(dataGroupTag) + ", found " + Integer.toHexString(tag)); } int dataGroupLength = tlvIn.readLength(); byte[] value = tlvIn.readValue(); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); TLVOutputStream tlvOut = new TLVOutputStream(bOut); tlvOut.writeTag(tag); tlvOut.writeValue(value); byte[] contents = bOut.toByteArray(); return contents; } /** * Do the AA protocol with the passport using the passportService, and put the response in a new * PassportDataMessage. Also read some data groups. */ public void generateEDLDataMessage(PassportService passportService, EDLDataMessage eDLMessage) throws CardServiceException, IOException { publishProgress(); try { if (eDLMessage.getDg1File() == null) { CardFileInputStream in = passportService.getInputStream((short) 0x0001); eDLMessage.setDg1File(readDg1File(in)); Log.i(TAG, "Reading DG1"); publishProgress(); } if (eDLMessage.getSodFile() == null) { eDLMessage.setSodFile(new SODFile(passportService.getInputStream((short) 0x001d))); Log.i(TAG, "reading SOD"); publishProgress(); } if (eDLMessage.getSodFile() != null) { // We need the SOD file to check if DG14 exists if (eDLMessage.getSodFile().getDataGroupHashes().get(14) != null) { // Checks if DG14 exists if (eDLMessage.getDg14File() == null) { eDLMessage.setDg14File(new DG14File(passportService.getInputStream((short) 0x000e))); Log.i(TAG, "reading DG14"); publishProgress(); } } else { // If DG14 does not exist, just advance the progress bar Log.i(TAG, "reading DG14 not necessary, skipping"); publishProgress(); } } if (eDLMessage.getDg13File() == null) { eDLMessage.setDg13File(new DG15File(passportService.getInputStream((short) 0x000d))); Log.i(TAG, "reading DG13"); publishProgress(); } // The doAA() method does not use its first three arguments, it only passes the challenge // on to another functio within JMRTD. if (eDLMessage.getResponse() == null) { eDLMessage.setResponse(passportService.doAA(null, null, null, eDLMessage.getChallenge())); Log.i(TAG, "doing AA"); publishProgress(); } } catch (NullPointerException e) { // JMRTD sometimes throws a nullpointer exception if the passport communcation goes wrong // (I've seen it happening if the passport is removed from the device halfway through) throw new IOException("NullPointerException during passport communication", e); } } @Override protected void onPostExecute(EDLDataMessage eDLMessage) { // First set the result, since it may be partially okay documentMsg = eDLMessage; Boolean done = eDLMessage != null && eDLMessage.isComplete(); progressBar.setProgress(progressBar.getMax()); Log.i(TAG, "PassportEnrollActivity: attempt " + tagReadAttempt + " finished, done: " + done); if (!bacError && !passportError) { advanceScreen(); } if (bacError) { showErrorScreen(getString(R.string.error_enroll_bacfailed), getString(R.string.abort), 0, getString(R.string.retry), SCREEN_BAC); } if (passportError) { showErrorScreen(R.string.error_enroll_passporterror); } } }.execute(ps,eDLMessage); } }
src/main/java/org/irmacard/cardemu/selfenrol/DriversLicenseEnrollActivity.java
package org.irmacard.cardemu.selfenrol; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; import com.google.gson.JsonSyntaxException; import com.google.gson.reflect.TypeToken; import net.sf.scuba.smartcards.*; import net.sf.scuba.tlv.TLVInputStream; import net.sf.scuba.tlv.TLVOutputStream; import org.acra.ACRA; import org.irmacard.cardemu.CardManager; import org.irmacard.cardemu.R; import org.irmacard.cardemu.httpclient.HttpClientException; import org.irmacard.credentials.Attributes; import org.irmacard.credentials.CredentialsException; import org.irmacard.credentials.idemix.IdemixCredentials; import org.irmacard.credentials.idemix.descriptions.IdemixVerificationDescription; import org.irmacard.credentials.idemix.smartcard.SmartCardEmulatorService; import org.irmacard.credentials.info.CredentialIdentifier; import org.irmacard.credentials.info.InfoException; import org.irmacard.idemix.IdemixService; import org.irmacard.idemix.IdemixSmartcard; import org.irmacard.mno.common.*; import org.jmrtd.PassportService; import org.jmrtd.Util; import org.jmrtd.lds.DG14File; import org.jmrtd.lds.DG15File; import org.jmrtd.lds.SODFile; import javax.crypto.Cipher; import javax.crypto.Mac; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.Type; import java.security.*; import java.util.HashMap; import java.util.Map; import java.util.Random; public class DriversLicenseEnrollActivity extends AbstractNFCEnrollActivity { // Configuration private static final String TAG = "DriversLicenseEnrollAct"; public static final int DriversLicenseEnrollActivityCode = 400; private static final int SCREEN_BAC = 2; private static final int SCREEN_PASSPORT = 3; private static final int SCREEN_ISSUE = 4; // State variables //private EDLDataMessage eDLMsg = null; protected int tagReadAttempt = 0; @Override protected String getURLPath() { return "/dl"; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setNfcScreen(SCREEN_PASSPORT); // Get the BasicClientMessage containing our nonce to send to the passport. getEnrollmentSession(new Handler() { @Override public void handleMessage(Message msg) { EnrollmentStartResult result = (EnrollmentStartResult) msg.obj; if (result.exception != null) { // Something went wrong showErrorScreen(result.errorId); } else { TextView connectedTextView = (TextView) findViewById(R.id.se_connected); connectedTextView.setTextColor(getResources().getColor(R.color.irmagreen)); connectedTextView.setText(R.string.se_connected_mno); findViewById(R.id.se_feedback_text).setVisibility(View.VISIBLE); findViewById(R.id.se_progress_bar).setVisibility(View.VISIBLE); } } }); // Spongycastle provides the MAC ISO9797Alg3Mac, which JMRTD usesin the doBAC method below (at // DESedeSecureMessagingWrapper.java, line 115) Security.addProvider(new org.spongycastle.jce.provider.BouncyCastleProvider()); // Update the UI setContentView(R.layout.enroll_activity_passport); screen = SCREEN_PASSPORT; updateProgressCounter(); // The next advanceScreen() is called when the passport reading was successful (see onPostExecute() in // readPassport() above). Thus, if no passport arrives or we can't successfully read it, we have to // ensure here that we don't stay on the passport screen forever with this timeout. new Handler().postDelayed(new Runnable() { @Override public void run() { if (screen == SCREEN_PASSPORT && (documentMsg == null || !documentMsg.isComplete())) { showErrorScreen(getString(R.string.error_enroll_passporterror)); } } }, MAX_TAG_READ_TIME); } @Override void handleNfcEvent(CardService service, EnrollmentStartMessage message) { TextView feedbackTextView = (TextView) findViewById(R.id.se_feedback_text); if (feedbackTextView != null) { feedbackTextView.setText(R.string.feedback_communicating_driverslicense); } try { service.open(); PassportService passportService = new PassportService(service); if (documentMsg == null) { documentMsg = new EDLDataMessage(message.getSessionToken(), imsi, message.getNonce()); } readDriversLicense(passportService, documentMsg); } catch (CardServiceException e) { // TODO under what circumstances does this happen? Maybe handle it more intelligently? ACRA.getErrorReporter().handleException(e); showErrorScreen(getString(R.string.error_enroll_driverslicense_error), getString(R.string.abort), 0, getString(R.string.retry), SCREEN_PASSPORT); } } @Override protected void advanceScreen() { switch (screen) { case SCREEN_PASSPORT: setContentView(R.layout.enroll_activity_issue); screen = SCREEN_ISSUE; updateProgressCounter(); // Save the card before messing with it so we can roll back if // something goes wrong CardManager.storeCard(); // Do it! enroll(new Handler() { @Override public void handleMessage(Message msg) { if (msg.obj == null) { // Success, save our new credentials CardManager.storeCard(); enableContinueButton(); findViewById(R.id.se_done_text).setVisibility(View.VISIBLE); } else { // Rollback the card card = CardManager.loadCard(); is = new IdemixService(new SmartCardEmulatorService(card)); if (msg.what != 0) // .what may contain a string identifier saying what went wrong showErrorScreen(msg.what); else showErrorScreen(R.string.unknown_error); } } }); break; case SCREEN_ISSUE: case SCREEN_ERROR: screen = SCREEN_START; finish(); break; default: Log.e(TAG, "Error, screen switch fall through"); break; } } public synchronized void doBAP(PassportService ps, String mrz) throws CardServiceException { if (mrz != null && mrz.length()>0) { try { String kdoc = mrz.substring(1, mrz.length() - 1); byte[] keySeed = computeKeySeedForBAP(kdoc); SecretKey kEnc = Util.deriveKey(keySeed, Util.ENC_MODE); SecretKey kMac = Util.deriveKey(keySeed, Util.MAC_MODE); try { //the eDL BAC is actually the same as the BAC for passports ps.doBAC(kEnc,kMac); } catch (CardServiceException cse) { Log.e(TAG,"BAP failed"); Log.e(TAG, cse.getMessage().toString()); throw cse; } } catch (GeneralSecurityException gse) { Log.e(TAG,gse.getStackTrace().toString()); throw new CardServiceException(gse.toString()); } } else { Log.e(TAG,"no valid MRZ found"); //TODO error no valid mrz string } } private static byte[] computeKeySeedForBAP(String kdoc) throws GeneralSecurityException { if (kdoc == null || kdoc.length() < 6) { throw new IllegalArgumentException("Wrong document key for drivers license, found " + kdoc); } MessageDigest shaDigest = MessageDigest.getInstance("SHA-1"); shaDigest.update(getBytes(kdoc)); byte[] hash = shaDigest.digest(); //truncate byte[] keySeed = new byte[16]; System.arraycopy(hash, 0, keySeed, 0, 16); return keySeed; } //helper function from JMRTD Util. Unchanged. private static byte[] getBytes(String str) { byte[] bytes = str.getBytes(); try { bytes = str.getBytes("UTF-8"); } catch (UnsupportedEncodingException use) { /* NOTE: unlikely. */ Log.e(TAG,"Exception: " + use.getMessage()); } return bytes; } /** * Reads the datagroups 1, 14 and 15, and the SOD file and requests an active authentication from an e-passport * in a seperate thread. */ private void readDriversLicense(PassportService ps, DocumentDataMessage eDLMessage) { new AsyncTask<Object,Void,EDLDataMessage>(){ ProgressBar progressBar = (ProgressBar) findViewById(R.id.se_progress_bar); boolean passportError = false; boolean bacError = false; long start; long stop; @Override protected EDLDataMessage doInBackground(Object... params) { if (params.length <2) { return null; //TODO appropriate error } PassportService ps = (PassportService) params[0]; EDLDataMessage eDLMessage = (EDLDataMessage) params[1]; if (tagReadAttempt == 0) { start = System.currentTimeMillis(); } tagReadAttempt++; // Do the BAC separately from generating the eDLMessage, so we can be specific in our error message if // necessary. (Note: the IllegalStateException should not happen, but if it does for some unforseen // reason there is no need to let it crash the app.) String mrz = settings.getString("mrz", ""); try { doBAP(ps, mrz); Log.i(TAG, "BAP Succeeded"); } catch (CardServiceException | IllegalStateException e) { bacError = true; Log.e(TAG, "doing BAP failed"); return null; } //If we get here, the BAP succeeded. Which means the MRZ was correct, so we can trust the documentNumber if (eDLMessage.getDocumentNr() == null){ eDLMessage.setDocumentNr(mrz.substring(5,15)); } Exception ex = null; try { Log.i(TAG, "PassportEnrollActivity: reading attempt " + tagReadAttempt); generateEDLDataMessage(ps, eDLMessage); } catch (IOException |CardServiceException e) { Log.w(TAG, "PassportEnrollActivity: reading attempt " + tagReadAttempt + " failed, stack trace:"); Log.w(TAG, " " + e.getMessage()); ex = e; } passportError = !eDLMessage.isComplete(); if (!eDLMessage.isComplete() && tagReadAttempt == MAX_TAG_READ_ATTEMPTS && ex != null) { // Build a fancy report saying which fields we did and which we did not manage to get Log.e(TAG, "PassportEnrollActivity: too many attempts failed, aborting"); ACRA.getErrorReporter().reportBuilder() .customData("sod", String.valueOf(eDLMessage.getSodFile() == null)) .customData("dg1File", String.valueOf(eDLMessage.getDg1File() == null)) .customData("dg14File", String.valueOf(eDLMessage.getDg14File() == null)) .customData("dg13File", String.valueOf(eDLMessage.getDg13File() == null)) .customData("response", String.valueOf(eDLMessage.getResponse() == null)) .exception(ex) .send(); } publishProgress(); return eDLMessage; } @Override protected void onProgressUpdate(Void... values) { if (progressBar != null) { // progressBar can vanish if the progress goes wrong halfway through progressBar.incrementProgressBy(1); } } /* we need this method for now to be able to send secured APDUs to cards */ private ResponseAPDU transmitWrappedAPDU (PassportService ps, CommandAPDU capdu) throws CardServiceException { APDUWrapper wrapper = ps.getWrapper(); if (wrapper == null){ throw new NullPointerException("No wrapper was set for secure messaging"); } CommandAPDU wcapdu = wrapper.wrap(capdu); ResponseAPDU wrapdu = ps.transmit(wcapdu); return wrapper.unwrap(wrapdu, wrapdu.getBytes().length); } protected byte[] readDg1File(InputStream inputStream) throws IOException { int dataGroupTag = 0x61; TLVInputStream tlvIn = inputStream instanceof TLVInputStream ? (TLVInputStream)inputStream : new TLVInputStream(inputStream); int tag = tlvIn.readTag(); if (tag != dataGroupTag) { throw new IllegalArgumentException("Was expecting tag " + Integer.toHexString(dataGroupTag) + ", found " + Integer.toHexString(tag)); } int dataGroupLength = tlvIn.readLength(); byte[] value = tlvIn.readValue(); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); TLVOutputStream tlvOut = new TLVOutputStream(bOut); tlvOut.writeTag(tag); tlvOut.writeValue(value); byte[] contents = bOut.toByteArray(); return contents; } /** * Do the AA protocol with the passport using the passportService, and put the response in a new * PassportDataMessage. Also read some data groups. */ public void generateEDLDataMessage(PassportService passportService, EDLDataMessage eDLMessage) throws CardServiceException, IOException { publishProgress(); try { if (eDLMessage.getDg1File() == null) { CardFileInputStream in = passportService.getInputStream((short) 0x0001); eDLMessage.setDg1File(readDg1File(in)); Log.i(TAG, "Reading DG1"); //TODO: this is a debugging check! to be renoved Log.e(TAG,"[" + bytesToHex(eDLMessage.getDg1File()) + "]"); publishProgress(); } if (eDLMessage.getSodFile() == null) { eDLMessage.setSodFile(new SODFile(passportService.getInputStream((short) 0x001d))); Log.i(TAG, "reading SOD"); publishProgress(); } if (eDLMessage.getSodFile() != null) { // We need the SOD file to check if DG14 exists if (eDLMessage.getSodFile().getDataGroupHashes().get(14) != null) { // Checks if DG14 exists if (eDLMessage.getDg14File() == null) { eDLMessage.setDg14File(new DG14File(passportService.getInputStream((short) 0x000e))); Log.i(TAG, "reading DG14"); publishProgress(); } } else { // If DG14 does not exist, just advance the progress bar Log.i(TAG, "reading DG14 not necessary, skipping"); publishProgress(); } } if (eDLMessage.getDg13File() == null) { eDLMessage.setDg13File(new DG15File(passportService.getInputStream((short) 0x000d))); Log.i(TAG, "reading DG13"); publishProgress(); } // The doAA() method does not use its first three arguments, it only passes the challenge // on to another functio within JMRTD. if (eDLMessage.getResponse() == null) { eDLMessage.setResponse(passportService.doAA(null, null, null, eDLMessage.getChallenge())); Log.i(TAG, "doing AA"); publishProgress(); } } catch (NullPointerException e) { // JMRTD sometimes throws a nullpointer exception if the passport communcation goes wrong // (I've seen it happening if the passport is removed from the device halfway through) throw new IOException("NullPointerException during passport communication", e); } } final protected char[] hexArray = "0123456789ABCDEF".toCharArray(); public String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for ( int j = 0; j < bytes.length; j++ ) { int v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } @Override protected void onPostExecute(EDLDataMessage eDLMessage) { // First set the result, since it may be partially okay documentMsg = eDLMessage; Boolean done = eDLMessage != null && eDLMessage.isComplete(); progressBar.setProgress(progressBar.getMax()); Log.i(TAG, "PassportEnrollActivity: attempt " + tagReadAttempt + " finished, done: " + done); if (!bacError && !passportError) { advanceScreen(); } if (bacError) { showErrorScreen(getString(R.string.error_enroll_bacfailed), getString(R.string.abort), 0, getString(R.string.retry), SCREEN_BAC); } if (passportError) { showErrorScreen(R.string.error_enroll_passporterror); } } }.execute(ps,eDLMessage); } }
removed unnecessary debug code
src/main/java/org/irmacard/cardemu/selfenrol/DriversLicenseEnrollActivity.java
removed unnecessary debug code
Java
bsd-3-clause
71c219f5fc9a1aa5ba2f9b03a7f00027e1517638
0
bluerover/6lbr,bluerover/6lbr,MohamedSeliem/contiki,MohamedSeliem/contiki,bluerover/6lbr,bluerover/6lbr,arurke/contiki,arurke/contiki,arurke/contiki,MohamedSeliem/contiki,MohamedSeliem/contiki,MohamedSeliem/contiki,bluerover/6lbr,MohamedSeliem/contiki,bluerover/6lbr,arurke/contiki,bluerover/6lbr,arurke/contiki,MohamedSeliem/contiki,arurke/contiki,arurke/contiki
/* * Copyright (c) 2008, Swedish Institute of Computer Science. * 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 the Institute 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 INSTITUTE 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 INSTITUTE 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. * * $Id: TimeChartPanel.java,v 1.2 2008/08/29 08:42:30 nifi Exp $ * * ----------------------------------------------------------------- * * TimeChartPanel * * Authors : Joakim Eriksson, Niclas Finne * Created : 3 jul 2008 * Updated : $Date: 2008/08/29 08:42:30 $ * $Revision: 1.2 $ */ package se.sics.contiki.collect.gui; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.util.Date; import javax.swing.JPanel; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.data.time.Second; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; import se.sics.contiki.collect.CollectServer; import se.sics.contiki.collect.Node; import se.sics.contiki.collect.SensorData; import se.sics.contiki.collect.Visualizer; /** * */ public abstract class TimeChartPanel extends JPanel implements Visualizer { private static final long serialVersionUID = -607864439709540641L; protected final CollectServer server; protected final String title; protected final TimeSeriesCollection timeSeries; protected final JFreeChart chart; protected final ChartPanel chartPanel; private Node[] selectedNodes; private double minValue; private double maxValue; private int rangeTick = 0; private boolean hasGlobalRange; private int maxItemCount; public TimeChartPanel(CollectServer server, String title, String chartTitle, String timeAxisLabel, String valueAxisLabel) { super(new BorderLayout()); this.server = server; this.title = title; this.timeSeries = new TimeSeriesCollection(); this.chart = ChartFactory.createTimeSeriesChart( chartTitle, timeAxisLabel, valueAxisLabel, timeSeries, true, true, false ); this.chartPanel = new ChartPanel(chart); this.chartPanel.setPreferredSize(new Dimension(500, 270)); add(chartPanel, BorderLayout.CENTER); } @Override public String getTitle() { return title; } @Override public Component getPanel() { return this; } @Override public void nodeAdded(Node node) { // Ignore } @Override public void nodesSelected(Node[] nodes) { if (this.selectedNodes != nodes) { this.selectedNodes = nodes; if (isVisible()) { updateCharts(); } } } @Override public void nodeDataReceived(SensorData data) { if (hasGlobalRange) { boolean update = false; if (minValue > maxValue) { update = true; } else { double value = getSensorDataValue(data); if (value < minValue) { minValue = value; update = true; } if (value > maxValue) { maxValue = value; update = true; } } if (update && isVisible()) { updateGlobalRange(); } } if (isVisible() && selectedNodes != null && selectedNodes.length == timeSeries.getSeriesCount()) { Node node = data.getNode(); for (int i = 0, n = selectedNodes.length; i < n; i++) { if (node == selectedNodes[i]) { TimeSeries series = timeSeries.getSeries(i); int groupSize = getGroupSize(node); if (groupSize > 1) { series.clear(); updateSeries(series, node, groupSize); } else { series.addOrUpdate(new Second(new Date(data.getTime())), getSensorDataValue(data)); } chartPanel.repaint(); break; } } } } @Override public void clearNodeData() { if (isVisible()) { updateCharts(); } } private void updateCharts() { timeSeries.removeAllSeries(); if (this.selectedNodes != null) { for(Node node: this.selectedNodes) { TimeSeries series = new TimeSeries(node.getName(), Second.class); // Reduce the number of items by grouping them and use the average for each group int groupSize = getGroupSize(node); if (groupSize > 1) { updateSeries(series, node, groupSize); } else { for (int i = 0, n = node.getSensorDataCount(); i < n; i++) { SensorData data = node.getSensorData(i); series.addOrUpdate(new Second(new Date(data.getTime())), getSensorDataValue(data)); } } timeSeries.addSeries(series); } } } protected int getGroupSize(Node node) { if (maxItemCount > 0) { int sensorDataCount = node.getSensorDataCount(); if (sensorDataCount > maxItemCount) { int groupSize = sensorDataCount / maxItemCount; if (sensorDataCount / groupSize > maxItemCount) { groupSize++; } return groupSize; } } return 1; } protected void updateSeries(TimeSeries series, Node node, int groupSize) { for (int i = 0, n = node.getSensorDataCount(); i < n; i += groupSize) { double value = 0.0; long time = 0L; for (int j = 0; j < groupSize; j++) { SensorData data = node.getSensorData(i); value += getSensorDataValue(data); time += data.getTime() / 1000L; } series.addOrUpdate(new Second(new Date((time / groupSize) * 1000L)), value / groupSize); } } public int getRangeTick() { return rangeTick; } public void setRangeTick(int rangeTick) { this.rangeTick = rangeTick; } public double getRangeMinimumSize() { return chart.getXYPlot().getRangeAxis().getAutoRangeMinimumSize(); } public void setRangeMinimumSize(double size) { chart.getXYPlot().getRangeAxis().setAutoRangeMinimumSize(size); } public boolean hasGlobalRange() { return hasGlobalRange; } public void setGlobalRange(boolean hasGlobalRange) { if (this.hasGlobalRange != hasGlobalRange) { this.hasGlobalRange = hasGlobalRange; if (hasGlobalRange) { minValue = Double.MAX_VALUE; maxValue = Double.MIN_NORMAL; if (isVisible()) { updateGlobalRange(); } } else { chart.getXYPlot().getRangeAxis().setAutoRange(true); } } } private void updateGlobalRange() { if (hasGlobalRange) { if (minValue > maxValue) { for (int i = 0, n = server.getSensorDataCount(); i < n; i++) { double value = getSensorDataValue(server.getSensorData(i)); if (value < minValue) minValue = value; if (value > maxValue) maxValue = value; } } if (minValue < maxValue) { double minSize = getRangeMinimumSize(); double min = minValue; double max = maxValue; if (max - min < minSize) { double d = (minSize - (max - min)) / 2; min -= d; max += d; } if (rangeTick > 0) { min = ((int) (min - rangeTick / 2) / rangeTick) * rangeTick; // max = ((int) (max + rangeTick / 2) / rangeTick) * rangeTick; } chart.getXYPlot().getRangeAxis().setRange(min, max); } } } /** * Returns the maximal number of chart items to display for each node. * * @return the maximal number of chart items to display for each node or <code>0</code> * for unlimited number of chart items. */ public int getMaxItemCount() { return maxItemCount; } /** * Sets the maximal number of chart items to display for each node. Items will be * grouped and replaced by the average value when needed. * * @param maxItemCount - the maximal number of chart items to display for each node or * <code>0</code> for unlimited number (default) */ public void setMaxItemCount(int maxItemCount) { this.maxItemCount = maxItemCount; if (isVisible()) { updateCharts(); } } public void setVisible(boolean visible) { if (visible) { updateGlobalRange(); updateCharts(); } else { timeSeries.removeAllSeries(); } super.setVisible(visible); } protected abstract double getSensorDataValue(SensorData data); }
examples/sky-shell/src/se/sics/contiki/collect/gui/TimeChartPanel.java
/* * Copyright (c) 2008, Swedish Institute of Computer Science. * 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 the Institute 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 INSTITUTE 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 INSTITUTE 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. * * $Id: TimeChartPanel.java,v 1.1 2008/07/09 23:18:07 nifi Exp $ * * ----------------------------------------------------------------- * * PowerPanel * * Authors : Joakim Eriksson, Niclas Finne * Created : 3 jul 2008 * Updated : $Date: 2008/07/09 23:18:07 $ * $Revision: 1.1 $ */ package se.sics.contiki.collect.gui; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.util.Date; import javax.swing.JPanel; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.data.time.Second; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; import se.sics.contiki.collect.CollectServer; import se.sics.contiki.collect.Node; import se.sics.contiki.collect.SensorData; import se.sics.contiki.collect.Visualizer; /** * */ public abstract class TimeChartPanel extends JPanel implements Visualizer { private static final long serialVersionUID = -607864439709540641L; protected final CollectServer server; protected final String title; protected final TimeSeriesCollection timeSeries; protected final JFreeChart chart; protected final ChartPanel chartPanel; private Node[] selectedNodes; private double minValue; private double maxValue; private int rangeTick = 0; private boolean hasGlobalRange; public TimeChartPanel(CollectServer server, String title, String chartTitle, String timeAxisLabel, String valueAxisLabel) { super(new BorderLayout()); this.server = server; this.title = title; this.timeSeries = new TimeSeriesCollection(); this.chart = ChartFactory.createTimeSeriesChart( chartTitle, timeAxisLabel, valueAxisLabel, timeSeries, true, true, false ); this.chartPanel = new ChartPanel(chart); this.chartPanel.setPreferredSize(new Dimension(500, 270)); add(chartPanel, BorderLayout.CENTER); } @Override public String getTitle() { return title; } @Override public Component getPanel() { return this; } @Override public void nodeAdded(Node node) { // Ignore } @Override public void nodesSelected(Node[] nodes) { if (this.selectedNodes != nodes) { this.selectedNodes = nodes; if (isVisible()) { updateCharts(); } } } @Override public void nodeDataReceived(SensorData data) { if (hasGlobalRange) { boolean update = false; if (minValue > maxValue) { update = true; } else { double value = getSensorDataValue(data); if (value < minValue) { minValue = value; update = true; } if (value > maxValue) { maxValue = value; update = true; } } if (update && isVisible()) { updateGlobalRange(); } } if (isVisible() && selectedNodes != null && selectedNodes.length == timeSeries.getSeriesCount()) { Node node = data.getNode(); for (int i = 0, n = selectedNodes.length; i < n; i++) { if (node == selectedNodes[i]) { TimeSeries series = timeSeries.getSeries(i); series.addOrUpdate(new Second(new Date(data.getTime())), getSensorDataValue(data)); chartPanel.repaint(); break; } } } } @Override public void clearNodeData() { if (isVisible()) { updateCharts(); } } private void updateCharts() { timeSeries.removeAllSeries(); if (this.selectedNodes != null) { for(Node node: this.selectedNodes) { TimeSeries series = new TimeSeries(node.getName(), Second.class); for (int i = 0, n = node.getSensorDataCount(); i < n; i++) { SensorData data = node.getSensorData(i); series.addOrUpdate(new Second(new Date(data.getTime())), getSensorDataValue(data)); } timeSeries.addSeries(series); } } } public int getRangeTick() { return rangeTick; } public void setRangeTick(int rangeTick) { this.rangeTick = rangeTick; } public double getRangeMinimumSize() { return chart.getXYPlot().getRangeAxis().getAutoRangeMinimumSize(); } public void setRangeMinimumSize(double size) { chart.getXYPlot().getRangeAxis().setAutoRangeMinimumSize(size); } public boolean hasGlobalRange() { return hasGlobalRange; } public void setGlobalRange(boolean hasGlobalRange) { if (this.hasGlobalRange != hasGlobalRange) { this.hasGlobalRange = hasGlobalRange; if (hasGlobalRange) { minValue = Double.MAX_VALUE; maxValue = Double.MIN_NORMAL; if (isVisible()) { updateGlobalRange(); } } else { chart.getXYPlot().getRangeAxis().setAutoRange(true); } } } private void updateGlobalRange() { if (hasGlobalRange) { if (minValue > maxValue) { for (int i = 0, n = server.getSensorDataCount(); i < n; i++) { double value = getSensorDataValue(server.getSensorData(i)); if (value < minValue) minValue = value; if (value > maxValue) maxValue = value; } } if (minValue < maxValue) { double minSize = getRangeMinimumSize(); double min = minValue; double max = maxValue; if (max - min < minSize) { double d = (minSize - (max - min)) / 2; min -= d; max += d; } if (rangeTick > 0) { min = ((int) (min - rangeTick / 2) / rangeTick) * rangeTick; // max = ((int) (max + rangeTick / 2) / rangeTick) * rangeTick; } chart.getXYPlot().getRangeAxis().setRange(min, max); } } } protected abstract double getSensorDataValue(SensorData data); public void setVisible(boolean visible) { if (visible) { updateGlobalRange(); updateCharts(); } else { timeSeries.removeAllSeries(); } super.setVisible(visible); } }
added option to limit the number of displayed chart items
examples/sky-shell/src/se/sics/contiki/collect/gui/TimeChartPanel.java
added option to limit the number of displayed chart items
Java
mit
324cf5991cbac9f7734c5885da7a7d9ea6e7da21
0
jenkinsci/memegen-plugin,jenkinsci/memegen-plugin,joonty/memegen,joonty/memegen
package hudson.plugins.memegen; import hudson.Extension; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.model.Result; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Notifier; import hudson.tasks.Publisher; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import java.util.logging.Level; import java.io.IOException; import java.io.PrintStream; import org.kohsuke.stapler.StaplerRequest; import net.sf.json.JSONObject; import net.sf.json.JSONArray; import org.kohsuke.stapler.DataBoundConstructor; /** * @author Asgeir Storesund Nilsen * */ public class MemeNotifier extends Notifier { private static final Logger LOGGER = Logger.getLogger(MemeNotifier.class.getName()); public boolean memeEnabledFailure; public boolean memeEnabledSuccess; public boolean memeEnabledAlways; @DataBoundConstructor public MemeNotifier(boolean memeEnabledFailure, boolean memeEnabledSuccess, boolean memeEnabledAlways) { //System.err.println("MemeNotifier called with args: "+memeUsername+", "+memePassword+", "+enableFailure+", "+enableSucceed+", "+enableAlways); this.memeEnabledAlways = memeEnabledAlways; this.memeEnabledSuccess = memeEnabledSuccess; this.memeEnabledFailure = memeEnabledFailure; } /* * (non-Javadoc) * * @see hudson.tasks.BuildStep#getRequiredMonitorService() */ public BuildStepMonitor getRequiredMonitorService() { return BuildStepMonitor.NONE; } private void generate(AbstractBuild build, BuildListener listener) { PrintStream output = listener.getLogger(); output.println("Generating Meme with account " + ((DescriptorImpl) getDescriptor()).getMemeUsername()); final String buildId = build.getProject().getDisplayName() + " " + build.getDisplayName(); MemegeneratorAPI memegenAPI = new MemegeneratorAPI(((DescriptorImpl) getDescriptor()).getMemeUsername(), ((DescriptorImpl) getDescriptor()).getMemePassword()); boolean memeResult; try { Result res = build.getResult(); Meme meme = MemeFactory.getMeme((res==Result.FAILURE)?((DescriptorImpl) getDescriptor()).getFailMemes():((DescriptorImpl) getDescriptor()).getSuccessMemes(),build); memeResult = memegenAPI.instanceCreate(meme); if (memeResult) { output.println("Meme: " + meme.getImageURL()); build.setDescription("<img class=\"meme\" src=\"" + meme.getImageURL() + "\" />"); AbstractProject proj = build.getProject(); String desc = proj.getDescription(); desc = desc.replaceAll("<img class=\"meme\"[^>]+>", ""); desc += "<img class=\"meme\" src=\"" + meme.getImageURL() + "\" />"; proj.setDescription(desc); } else { output.println("Sorry, couldn't create a Meme - check the logs for more detail"); } } catch (NoMemesException nme) { LOGGER.log(Level.WARNING, "{0}{1}", new Object[]{"Meme generation failed: ", nme.getMessage()}); output.println("There are no memes to use! Please add some in the Jenkins configuration page."); } catch (IOException ie) { LOGGER.log(Level.WARNING, "{0}{1}", new Object[]{"Meme generation failed: ", ie.getMessage()}); output.println("Sorry, couldn't create a Meme - check the logs for more detail"); } catch (Exception e) { LOGGER.log(Level.WARNING, "{0}{1}", new Object[]{"Meme generation failed: ", e.getMessage()}); output.println("Sorry, couldn't create a Meme - check the logs for more detail"); } } /* * (non-Javadoc) * * @see * hudson.tasks.BuildStepCompatibilityLayer#perform(hudson.model.AbstractBuild * , hudson.Launcher, hudson.model.BuildListener) */ @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { if (memeEnabledAlways) { listener.getLogger().println("Generating Meme..."); generate(build, listener); } else if (memeEnabledSuccess && build.getResult() == Result.SUCCESS) { AbstractBuild prevBuild = build.getPreviousBuild(); if (prevBuild != null && prevBuild.getResult() == Result.FAILURE) { listener.getLogger().println("Build has returned to successful, generating Meme..."); generate(build, listener); } } else if (memeEnabledFailure && build.getResult() == Result.FAILURE) { listener.getLogger().println("Build failure, generating Meme..."); generate(build, listener); } return true; } @Extension public static final class DescriptorImpl extends BuildStepDescriptor<Publisher> { public String memeUsername; public String memePassword; public ArrayList<Meme> smemes = new ArrayList<Meme>(); public ArrayList<Meme> fmemes = new ArrayList<Meme>(); public DescriptorImpl() { super(MemeNotifier.class); load(); } public String getMemeUsername() { return memeUsername; } public String getMemePassword() { return memePassword; } public ArrayList<Meme> getFailMemes() { if (fmemes.isEmpty()) { return getDefaultFailMemes(); } else { return fmemes; } } public ArrayList<Meme> getSuccessMemes() { if (smemes.isEmpty()) { return getDefaultSuccessMemes(); } else { return smemes; } } private ArrayList<Meme> getDefaultSuccessMemes() { String[][] list = getMemeList(); smemes.add(new Meme(list[0][0],"But when I do, I win","I don't always commit")); return smemes; } private ArrayList<Meme> getDefaultFailMemes() { String[][] list = getMemeList(); fmemes.add(new Meme(list[0][0],"But when I do, I break the build","I don't always commit")); return fmemes; } /* * (non-Javadoc) * * @see * hudson.tasks.BuildStepDescriptor#isApplicable(java.lang.Class) */ @Override public boolean isApplicable(Class<? extends AbstractProject> jobType) { return true; } @Override public boolean configure(StaplerRequest req, JSONObject json) throws FormException { memeUsername = req.getParameter("memeUsername"); memePassword = req.getParameter("memePassword"); smemes.clear(); for (Object data : getArray(json.get("smemes"))) { Meme m = req.bindJSON(Meme.class, (JSONObject) data); smemes.add(m); } fmemes.clear(); for (Object data : getArray(json.get("fmemes"))) { Meme m = req.bindJSON(Meme.class, (JSONObject) data); fmemes.add(m); } save(); return super.configure(req, json); } public static JSONArray getArray(Object data) { JSONArray result; if (data instanceof JSONArray) { result = (JSONArray) data; } else { result = new JSONArray(); if (data != null) { result.add(data); } } return result; } public String[][] getMemeList() { return new String[][] { {"74-2485","The Most Interesting Man In The World"}, {"2-166088","Y U No"}, {"17-984","Philosoraptor"}, {"305-84688","Futurama Fry"}, {"121-1031","Success Kid"}, {"116-142442","Forever Alone"}, {"29-983","Socially Awkward Penguin"}, {"534-699717","Good Guy Greg"}, {"3-203","Foul Bachelor Frog"}, {"45-20","Insanity Wolf"}, {"54-42","Joseph Ducreux"}, {"79-108785","Yo Dawg"}, {"111-1436","High Expectations Asian Father"}, {"112-288872","Paranoid Parrot"}, {"308-332591","Business Cat"}, {"225-32","Advice Dog"}, {"113750-1591284","iHate"}, {"96-89714","Bear Grylls"}, {"629-963","Advice Yoda Gives"}, {"5588-4944","Chuck Norris"}, {"5115-1110726","Chemistry Cat"}, }; } /* * (non-Javadoc) * * @see hudson.model.Descriptor#getDisplayName() */ @Override public String getDisplayName() { return "Meme Generator"; } } }
src/main/java/hudson/plugins/memegen/MemeNotifier.java
package hudson.plugins.memegen; import hudson.Extension; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.model.Result; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Notifier; import hudson.tasks.Publisher; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import java.util.logging.Level; import java.io.IOException; import java.io.PrintStream; import org.kohsuke.stapler.StaplerRequest; import net.sf.json.JSONObject; import net.sf.json.JSONArray; import org.kohsuke.stapler.DataBoundConstructor; /** * @author Asgeir Storesund Nilsen * */ public class MemeNotifier extends Notifier { private static final Logger LOGGER = Logger.getLogger(MemeNotifier.class.getName()); public boolean memeEnabledFailure; public boolean memeEnabledSuccess; public boolean memeEnabledAlways; @DataBoundConstructor public MemeNotifier(boolean memeEnabledFailure, boolean memeEnabledSuccess, boolean memeEnabledAlways) { //System.err.println("MemeNotifier called with args: "+memeUsername+", "+memePassword+", "+enableFailure+", "+enableSucceed+", "+enableAlways); this.memeEnabledAlways = memeEnabledAlways; this.memeEnabledSuccess = memeEnabledSuccess; this.memeEnabledFailure = memeEnabledFailure; } /* * (non-Javadoc) * * @see hudson.tasks.BuildStep#getRequiredMonitorService() */ public BuildStepMonitor getRequiredMonitorService() { return BuildStepMonitor.NONE; } private void generate(AbstractBuild build, BuildListener listener) { PrintStream output = listener.getLogger(); output.println("Generating Meme with account " + ((DescriptorImpl) getDescriptor()).getMemeUsername()); final String buildId = build.getProject().getDisplayName() + " " + build.getDisplayName(); MemegeneratorAPI memegenAPI = new MemegeneratorAPI(((DescriptorImpl) getDescriptor()).getMemeUsername(), ((DescriptorImpl) getDescriptor()).getMemePassword()); boolean memeResult; try { Result res = build.getResult(); Meme meme = MemeFactory.getMeme((res==Result.FAILURE)?((DescriptorImpl) getDescriptor()).getFailMemes():((DescriptorImpl) getDescriptor()).getSuccessMemes(),build); memeResult = memegenAPI.instanceCreate(meme); if (memeResult) { output.println("Meme: " + meme.getImageURL()); build.setDescription("<img class=\"meme\" src=\"" + meme.getImageURL() + "\" />"); AbstractProject proj = build.getProject(); String desc = proj.getDescription(); desc = desc.replaceAll("<img class=\"meme\"[^>]+>", ""); desc += "<img class=\"meme\" src=\"" + meme.getImageURL() + "\" />"; proj.setDescription(desc); } else { output.println("Sorry, couldn't create a Meme - check the logs for more detail"); } } catch (NoMemesException nme) { LOGGER.log(Level.WARNING, "{0}{1}", new Object[]{"Meme generation failed: ", nme.getMessage()}); output.println("There are no memes to use! Please add some in the Jenkins configuration page."); } catch (IOException ie) { LOGGER.log(Level.WARNING, "{0}{1}", new Object[]{"Meme generation failed: ", ie.getMessage()}); output.println("Sorry, couldn't create a Meme - check the logs for more detail"); } catch (Exception e) { LOGGER.log(Level.WARNING, "{0}{1}", new Object[]{"Meme generation failed: ", e.getMessage()}); output.println("Sorry, couldn't create a Meme - check the logs for more detail"); } } /* * (non-Javadoc) * * @see * hudson.tasks.BuildStepCompatibilityLayer#perform(hudson.model.AbstractBuild * , hudson.Launcher, hudson.model.BuildListener) */ @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { if (memeEnabledAlways) { listener.getLogger().println("Generating Meme..."); generate(build, listener); } else if (memeEnabledSuccess && build.getResult() == Result.SUCCESS) { AbstractBuild prevBuild = build.getPreviousBuild(); if (prevBuild.getResult() == Result.FAILURE) { listener.getLogger().println("Build has returned to successful, generating Meme..."); generate(build, listener); } } else if (memeEnabledFailure && build.getResult() == Result.FAILURE) { listener.getLogger().println("Build failure, generating Meme..."); generate(build, listener); } return true; } @Extension public static final class DescriptorImpl extends BuildStepDescriptor<Publisher> { public String memeUsername; public String memePassword; public ArrayList<Meme> smemes = new ArrayList<Meme>(); public ArrayList<Meme> fmemes = new ArrayList<Meme>(); public DescriptorImpl() { super(MemeNotifier.class); load(); } public String getMemeUsername() { return memeUsername; } public String getMemePassword() { return memePassword; } public ArrayList<Meme> getFailMemes() { if (fmemes.isEmpty()) { return getDefaultFailMemes(); } else { return fmemes; } } public ArrayList<Meme> getSuccessMemes() { if (smemes.isEmpty()) { return getDefaultSuccessMemes(); } else { return smemes; } } private ArrayList<Meme> getDefaultSuccessMemes() { String[][] list = getMemeList(); smemes.add(new Meme(list[0][0],"But when I do, I win","I don't always commit")); return smemes; } private ArrayList<Meme> getDefaultFailMemes() { String[][] list = getMemeList(); fmemes.add(new Meme(list[0][0],"But when I do, I break the build","I don't always commit")); return fmemes; } /* * (non-Javadoc) * * @see * hudson.tasks.BuildStepDescriptor#isApplicable(java.lang.Class) */ @Override public boolean isApplicable(Class<? extends AbstractProject> jobType) { return true; } @Override public boolean configure(StaplerRequest req, JSONObject json) throws FormException { memeUsername = req.getParameter("memeUsername"); memePassword = req.getParameter("memePassword"); smemes.clear(); for (Object data : getArray(json.get("smemes"))) { Meme m = req.bindJSON(Meme.class, (JSONObject) data); smemes.add(m); } fmemes.clear(); for (Object data : getArray(json.get("fmemes"))) { Meme m = req.bindJSON(Meme.class, (JSONObject) data); fmemes.add(m); } save(); return super.configure(req, json); } public static JSONArray getArray(Object data) { JSONArray result; if (data instanceof JSONArray) { result = (JSONArray) data; } else { result = new JSONArray(); if (data != null) { result.add(data); } } return result; } public String[][] getMemeList() { return new String[][] { {"74-2485","The Most Interesting Man In The World"}, {"2-166088","Y U No"}, {"17-984","Philosoraptor"}, {"305-84688","Futurama Fry"}, {"121-1031","Success Kid"}, {"116-142442","Forever Alone"}, {"29-983","Socially Awkward Penguin"}, {"534-699717","Good Guy Greg"}, {"3-203","Foul Bachelor Frog"}, {"45-20","Insanity Wolf"}, {"54-42","Joseph Ducreux"}, {"79-108785","Yo Dawg"}, {"111-1436","High Expectations Asian Father"}, {"112-288872","Paranoid Parrot"}, {"308-332591","Business Cat"}, {"225-32","Advice Dog"}, {"113750-1591284","iHate"}, {"96-89714","Bear Grylls"}, {"629-963","Advice Yoda Gives"}, {"5588-4944","Chuck Norris"}, {"5115-1110726","Chemistry Cat"}, }; } /* * (non-Javadoc) * * @see hudson.model.Descriptor#getDisplayName() */ @Override public String getDisplayName() { return "Meme Generator"; } } }
Fixed NPE with getting previous build status If the first build is successful and meme generation is enabled, a null pointer exception used to be thrown when the status of the previous build was attempted to be read. That has been fixed.
src/main/java/hudson/plugins/memegen/MemeNotifier.java
Fixed NPE with getting previous build status
Java
mit
9b201051c2d3591a9c1c3c622d45d799ea1edfeb
0
optimatika/ojAlgo,optimatika/ojAlgo,optimatika/ojAlgo,optimatika/ojAlgo
/* * Copyright 1997-2019 Optimatika * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.ojalgo.optimisation; import static org.ojalgo.function.constant.BigMath.*; import java.math.BigDecimal; import java.util.*; import java.util.stream.Stream; import org.ojalgo.ProgrammingError; import org.ojalgo.array.Array1D; import org.ojalgo.array.Primitive64Array; import org.ojalgo.function.constant.BigMath; import org.ojalgo.matrix.store.MatrixStore; import org.ojalgo.netio.BasicLogger; import org.ojalgo.netio.BasicLogger.Printer; import org.ojalgo.optimisation.convex.ConvexSolver; import org.ojalgo.optimisation.integer.IntegerSolver; import org.ojalgo.optimisation.linear.LinearSolver; import org.ojalgo.structure.Access1D; import org.ojalgo.structure.Structure1D.IntIndex; import org.ojalgo.structure.Structure2D.IntRowColumn; import org.ojalgo.type.context.NumberContext; /** * <p> * Lets you construct optimisation problems by combining (mathematical) expressions in terms of variables. * Each expression or variable can be a constraint and/or contribute to the objective function. An expression * or variable is turned into a constraint by setting a lower and/or upper limit. Use * {@linkplain Expression#lower(Number)}, {@linkplain Expression#upper(Number)} or * {@linkplain Expression#level(Number)}. An expression or variable is made part of (contributing to) the * objective function by setting a contribution weight. Use {@linkplain Expression#weight(Number)}. * </p> * <p> * You may think of variables as simple (the simplest possible) expressions, and of expressions as weighted * combinations of variables. They are both model entities and it is as such they can be turned into * constraints and set to contribute to the objective function. Alternatively you may choose to disregard the * fact that variables are model entities and simply treat them as index values. In this case everything * (constraints and objective) needs to be defined using expressions. * </p> * <p> * Basic instructions: * </p> * <ol> * <li>Define (create) a set of variables. Set contribution weights and lower/upper limits as needed.</li> * <li>Create a model using that set of variables.</li> * <li>Add expressions to the model. The model is the expression factory. Set contribution weights and * lower/upper limits as needed.</li> * <li>Solve your problem using either minimise() or maximise()</li> * </ol> * <p> * When using this class you do not need to worry about which solver will actually be used. The docs of the * various solvers describe requirements on input formats and similar. This is handled for you and should * absolutely NOT be considered here! Compared to using the various solvers directly this class actually does * something for you: * </p> * <ol> * <li>You can model your problems without worrying about specific solver requirements.</li> * <li>It knows which solver to use.</li> * <li>It knows how to use that solver.</li> * <li>It has a presolver that tries to simplify the problem before invoking a solver (sometimes it turns out * there is no need to invoke a solver at all).</li> * <li>When/if needed it scales problem parameters, before creating solver specific data structures, to * minimize numerical problems in the solvers.</li> * <li>It's the only way to access the integer solver.</li> * </ol> * <p> * Different solvers can be used, and ojAlgo comes with collection built in. The default built-in solvers can * handle anythimng you can model with a couple of restrictions: * </p> * <ul> * <li>No quadratic constraints (The plan is that future versions should not have this limitation.)</li> * <li>If you use quadratic expressions make sure they're convex. This is most likely a requirement even with * 3:d party solvers.</li> * </ul> * * @author apete */ public final class ExpressionsBasedModel extends AbstractModel { public static abstract class Integration<S extends Optimisation.Solver> implements Optimisation.Integration<ExpressionsBasedModel, S> { /** * @see org.ojalgo.optimisation.Optimisation.Integration#extractSolverState(org.ojalgo.optimisation.Optimisation.Model) */ public final Result extractSolverState(final ExpressionsBasedModel model) { return this.toSolverState(model.getVariableValues(), model); } public Result toModelState(final Result solverState, final ExpressionsBasedModel model) { final int numbVariables = model.countVariables(); if (this.isSolutionMapped()) { final List<Variable> freeVariables = model.getFreeVariables(); final Set<IntIndex> fixedVariables = model.getFixedVariables(); if (solverState.count() != freeVariables.size()) { throw new IllegalStateException(); } final Primitive64Array modelSolution = Primitive64Array.make(numbVariables); for (final IntIndex fixedIndex : fixedVariables) { modelSolution.set(fixedIndex.index, model.getVariable(fixedIndex.index).getValue()); } for (int f = 0; f < freeVariables.size(); f++) { final int freeIndex = model.indexOf(freeVariables.get(f)); modelSolution.set(freeIndex, solverState.doubleValue(f)); } return new Result(solverState.getState(), modelSolution); } else { if (solverState.count() != numbVariables) { throw new IllegalStateException(); } return solverState; } } public Result toSolverState(final Result modelState, final ExpressionsBasedModel model) { if (this.isSolutionMapped()) { final List<Variable> tmpFreeVariables = model.getFreeVariables(); final int numbFreeVars = tmpFreeVariables.size(); final Primitive64Array solverSolution = Primitive64Array.make(numbFreeVars); for (int i = 0; i < numbFreeVars; i++) { final Variable variable = tmpFreeVariables.get(i); final int modelIndex = model.indexOf(variable); solverSolution.set(i, modelState.doubleValue(modelIndex)); } return new Result(modelState.getState(), solverSolution); } else { return modelState; } } /** * @return The index with which one can reference parameters related to this variable in the solver. */ protected int getIndexInSolver(final ExpressionsBasedModel model, final Variable variable) { return model.indexOfFreeVariable(variable); } /** * @return true if the set of variables present in the solver is not precisely the same as in the * model. If fixed variables are omitted or if variables are split into a positive and * negative part, then this method must return true */ protected abstract boolean isSolutionMapped(); } public static final class Intermediate implements Optimisation.Solver { private boolean myInPlaceUpdatesOK = true; private transient ExpressionsBasedModel.Integration<?> myIntegration = null; private final ExpressionsBasedModel myModel; private transient Optimisation.Solver mySolver = null; Intermediate(final ExpressionsBasedModel model) { super(); myModel = model; myIntegration = null; mySolver = null; } /** * Force re-generation of any cached/transient data */ public void dispose() { Solver.super.dispose(); if (mySolver != null) { mySolver.dispose(); mySolver = null; } myIntegration = null; } public ExpressionsBasedModel getModel() { return myModel; } public Variable getVariable(final int globalIndex) { return myModel.getVariable(globalIndex); } public Variable getVariable(final IntIndex globalIndex) { return myModel.getVariable(globalIndex); } public Optimisation.Result solve(final Optimisation.Result candidate) { if (mySolver == null) { myModel.presolve(); } if (myModel.isInfeasible()) { final Optimisation.Result solution = candidate != null ? candidate : myModel.getVariableValues(); return new Optimisation.Result(State.INFEASIBLE, solution); } else if (myModel.isUnbounded()) { if ((candidate != null) && myModel.validate(candidate)) { return new Optimisation.Result(State.UNBOUNDED, candidate); } final Optimisation.Result derivedSolution = myModel.getVariableValues(); if (derivedSolution.getState().isFeasible()) { return new Optimisation.Result(State.UNBOUNDED, derivedSolution); } } else if (myModel.isFixed()) { final Optimisation.Result derivedSolution = myModel.getVariableValues(); if (derivedSolution.getState().isFeasible()) { return new Optimisation.Result(State.DISTINCT, derivedSolution); } else { return new Optimisation.Result(State.INVALID, derivedSolution); } } final ExpressionsBasedModel.Integration<?> integration = this.getIntegration(); final Optimisation.Solver solver = this.getSolver(); Optimisation.Result retVal = candidate != null ? candidate : myModel.getVariableValues(); retVal = integration.toSolverState(retVal, myModel); retVal = solver.solve(retVal); retVal = integration.toModelState(retVal, myModel); return retVal; } @Override public String toString() { return myModel.toString(); } public void update(final int index) { this.update(myModel.getVariable(index)); } public void update(final IntIndex index) { this.update(myModel.getVariable(index)); } public void update(final Variable variable) { if (myInPlaceUpdatesOK && (mySolver != null) && (mySolver instanceof UpdatableSolver) && variable.isFixed()) { final UpdatableSolver updatableSolver = (UpdatableSolver) mySolver; final int indexInSolver = this.getIntegration().getIndexInSolver(myModel, variable); final double fixedValue = variable.getValue().doubleValue(); if (updatableSolver.fixVariable(indexInSolver, fixedValue)) { // Solver updated in-place return; } else { myInPlaceUpdatesOK = false; } } // Solver will be re-generated mySolver = null; } public boolean validate(final Access1D<BigDecimal> solution, final Printer appender) { return myModel.validate(solution, appender); } public boolean validate(final Result solution) { return myModel.validate(solution); } ExpressionsBasedModel.Integration<?> getIntegration() { if (myIntegration == null) { myIntegration = myModel.getIntegration(); } return myIntegration; } Optimisation.Solver getSolver() { if (mySolver == null) { mySolver = this.getIntegration().build(myModel); } return mySolver; } } public static abstract class Presolver extends Simplifier<Expression, Presolver> { protected Presolver(final int executionOrder) { super(executionOrder); } /** * @param remaining TODO * @param lower TODO * @param upper TODO * @return True if any model entity was modified so that a re-run of the presolvers is necessary - * typically when/if a variable was fixed. */ public abstract boolean simplify(Expression expression, Set<IntIndex> remaining, BigDecimal lower, BigDecimal upper, NumberContext precision); @Override boolean isApplicable(final Expression target) { return target.isConstraint() && !target.isInfeasible() && !target.isRedundant() && (target.countQuadraticFactors() == 0); } } static abstract class Simplifier<ME extends ModelEntity<?>, S extends Simplifier<?, ?>> implements Comparable<S> { private final int myExecutionOrder; private final UUID myUUID = UUID.randomUUID(); Simplifier(final int executionOrder) { super(); myExecutionOrder = executionOrder; } public final int compareTo(final S reference) { return Integer.compare(myExecutionOrder, reference.getExecutionOrder()); } @Override public final boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Simplifier)) { return false; } final Simplifier<?, ?> other = (Simplifier<?, ?>) obj; if (myUUID == null) { if (other.myUUID != null) { return false; } } else if (!myUUID.equals(other.myUUID)) { return false; } return true; } @Override public final int hashCode() { final int prime = 31; int result = 1; result = (prime * result) + ((myUUID == null) ? 0 : myUUID.hashCode()); return result; } final int getExecutionOrder() { return myExecutionOrder; } abstract boolean isApplicable(final ME target); } static abstract class VariableAnalyser extends Simplifier<Variable, VariableAnalyser> { protected VariableAnalyser(final int executionOrder) { super(executionOrder); } public abstract boolean simplify(Variable variable, ExpressionsBasedModel model); @Override boolean isApplicable(final Variable target) { return true; } } private static final ConvexSolver.ModelIntegration CONVEX_INTEGRATION = new ConvexSolver.ModelIntegration(); private static final List<ExpressionsBasedModel.Integration<?>> FALLBACK_INTEGRATIONS = new ArrayList<>(); private static final IntegerSolver.ModelIntegration INTEGER_INTEGRATION = new IntegerSolver.ModelIntegration(); private static final LinearSolver.ModelIntegration LINEAR_INTEGRATION = new LinearSolver.ModelIntegration(); private static final String NEW_LINE = "\n"; private static final String OBJ_FUNC_AS_CONSTR_KEY = UUID.randomUUID().toString(); private static final String OBJECTIVE = "Generated/Aggregated Objective"; private static final List<ExpressionsBasedModel.Integration<?>> PREFERRED_INTEGRATIONS = new ArrayList<>(); private static final TreeSet<Presolver> PRESOLVERS = new TreeSet<>(); private static final String START_END = "############################################\n"; static { ExpressionsBasedModel.addPresolver(Presolvers.ZERO_ONE_TWO); ExpressionsBasedModel.addPresolver(Presolvers.REDUNDANT_CONSTRAINT); } /** * Add a solver that will be used for problem types the built-in solvers cannot handle as defined by * {@link Integration#isCapable(org.ojalgo.optimisation.Optimisation.Model)}. */ public static boolean addFallbackSolver(final Integration<?> integration) { return FALLBACK_INTEGRATIONS.add(integration); } /** * @deprecated v48 Use either {@link #addPreferredSolver(Integration)} or * {@link #addFallbackSolver(Integration)} instead */ @Deprecated public static boolean addIntegration(final Integration<?> integration) { return ExpressionsBasedModel.addPreferredSolver(integration); } /** * Add a solver that will be used rather than the built-in solvers */ public static boolean addPreferredSolver(final Integration<?> integration) { return PREFERRED_INTEGRATIONS.add(integration); } public static boolean addPresolver(final Presolver presolver) { return PRESOLVERS.add(presolver); } public static void clearIntegrations() { PREFERRED_INTEGRATIONS.clear(); FALLBACK_INTEGRATIONS.clear(); } public static void clearPresolvers() { PRESOLVERS.clear(); } public static boolean removeIntegration(final Integration<?> integration) { return PREFERRED_INTEGRATIONS.remove(integration) | FALLBACK_INTEGRATIONS.remove(integration); } public static boolean removePresolver(final Presolver presolver) { return PRESOLVERS.remove(presolver); } private final Map<String, Expression> myExpressions = new HashMap<>(); private final Set<IntIndex> myFixedVariables = new HashSet<>(); private transient int[] myFreeIndices = null; private final List<Variable> myFreeVariables = new ArrayList<>(); private transient boolean myInfeasible = false; private transient int[] myIntegerIndices = null; private final List<Variable> myIntegerVariables = new ArrayList<>(); private transient int[] myNegativeIndices = null; private final List<Variable> myNegativeVariables = new ArrayList<>(); private transient int[] myPositiveIndices = null; private final List<Variable> myPositiveVariables = new ArrayList<>(); private final Set<IntIndex> myReferences = new HashSet<>(); private boolean myRelaxed; /** * Temporary storage for some expresssion specific subset of variables */ private final Set<IntIndex> myTemporary = new HashSet<>(); private final ArrayList<Variable> myVariables = new ArrayList<>(); private final boolean myWorkCopy; public ExpressionsBasedModel() { super(); myWorkCopy = false; myRelaxed = false; } public ExpressionsBasedModel(final Collection<? extends Variable> variables) { super(); for (final Variable tmpVariable : variables) { this.addVariable(tmpVariable); } myWorkCopy = false; myRelaxed = false; } public ExpressionsBasedModel(final Optimisation.Options someOptions) { super(someOptions); myWorkCopy = false; myRelaxed = false; } public ExpressionsBasedModel(final Variable... variables) { super(); for (final Variable tmpVariable : variables) { this.addVariable(tmpVariable); } myWorkCopy = false; myRelaxed = false; } ExpressionsBasedModel(final ExpressionsBasedModel modelToCopy, final boolean workCopy, final boolean allEntities) { super(modelToCopy.options); this.setMinimisation(modelToCopy.isMinimisation()); for (final Variable tmpVariable : modelToCopy.getVariables()) { this.addVariable(tmpVariable.copy()); } for (final Expression tmpExpression : modelToCopy.getExpressions()) { if (allEntities || tmpExpression.isObjective() || (tmpExpression.isConstraint() && !tmpExpression.isRedundant())) { myExpressions.put(tmpExpression.getName(), tmpExpression.copy(this, !workCopy)); } else { // BasicLogger.DEBUG.println("Discarding expression: {}", tmpExpression); } } myWorkCopy = workCopy; myRelaxed = workCopy; } public Expression addExpression() { return this.addExpression("EXPR" + myExpressions.size()); } public Expression addExpression(final String name) { final Expression retVal = new Expression(name, this); myExpressions.put(name, retVal); return retVal; } /** * Creates a special ordered set (SOS) presolver instance and links that to the supplied expression. * When/if the presolver concludes that the SOS "constraints" are not possible the linked expression is * marked as infeasible. */ public void addSpecialOrderedSet(final Collection<Variable> orderedSet, final int type, final Expression linkedTo) { if (type <= 0) { throw new ProgrammingError("Invalid SOS type!"); } if (!linkedTo.isConstraint()) { throw new ProgrammingError("The linked to expression needs to be a constraint!"); } final IntIndex[] sequence = new IntIndex[orderedSet.size()]; int index = 0; for (final Variable variable : orderedSet) { if ((variable == null) || (variable.getIndex() == null)) { throw new ProgrammingError("Variables must be already inserted in the model!"); } else { sequence[index++] = variable.getIndex(); } } ExpressionsBasedModel.addPresolver(new SpecialOrderedSet(sequence, type, linkedTo)); } /** * Calling this method will create 2 things: * <ol> * <li>A simple expression meassuring the sum of the (binary) variable values (the number of binary * variables that are "ON"). The upper, and optionally lower, limits are set as defined by the * <code>max</code> and <code>min</code> parameter values.</li> * <li>A custom presolver (specific to this SOS) to be used by the MIP solver. This presolver help to keep * track of which combinations of variable values or feasible, and is the only thing that enforces the * order.</li> * </ol> * * @param orderedSet The set members in correct order. Each of these variables must be binary. * @param min The minimum number of binary varibales in the set that must be "ON" (Set this to 0 if there * is no minimum.) * @param max The SOS type or maximum number of binary varibales in the set that may be "ON" */ public void addSpecialOrderedSet(final Collection<Variable> orderedSet, final int min, final int max) { if ((max <= 0) || (min > max)) { throw new ProgrammingError("Invalid min/max number of ON variables!"); } final String name = "SOS" + max + "-" + orderedSet.toString(); final Expression expression = this.addExpression(name); for (final Variable variable : orderedSet) { if ((variable == null) || (variable.getIndex() == null) || !variable.isBinary()) { throw new ProgrammingError("Variables must be binary and already inserted in the model!"); } else { expression.set(variable.getIndex(), ONE); } } expression.upper(BigDecimal.valueOf(max)); if (min > 0) { expression.lower(BigDecimal.valueOf(min)); } this.addSpecialOrderedSet(orderedSet, max, expression); } public Variable addVariable() { return this.addVariable("X" + myVariables.size()); } public Variable addVariable(final String name) { final Variable retVal = new Variable(name); this.addVariable(retVal); return retVal; } public void addVariable(final Variable variable) { if (myWorkCopy) { throw new IllegalStateException("This model is a work copy - its set of variables cannot be modified!"); } else { myVariables.add(variable); variable.setIndex(new IntIndex(myVariables.size() - 1)); } } public void addVariables(final Collection<? extends Variable> variables) { for (final Variable tmpVariable : variables) { this.addVariable(tmpVariable); } } public void addVariables(final Variable[] variables) { for (final Variable tmpVariable : variables) { this.addVariable(tmpVariable); } } /** * @return A stream of variables that are constraints and not fixed */ public Stream<Variable> bounds() { return this.variables().filter(v -> v.isConstraint() && !v.isFixed()); } /** * @return A prefiltered stream of expressions that are constraints and have not been markes as redundant */ public Stream<Expression> constraints() { return myExpressions.values().stream().filter(c -> c.isConstraint() && !c.isRedundant()); } public ExpressionsBasedModel copy() { return new ExpressionsBasedModel(this, false, true); } public int countExpressions() { return myExpressions.size(); } public int countVariables() { return myVariables.size(); } @Override public void dispose() { for (final Expression tmpExprerssion : myExpressions.values()) { tmpExprerssion.destroy(); } myExpressions.clear(); for (final Variable tmpVariable : myVariables) { tmpVariable.destroy(); } myVariables.clear(); myFixedVariables.clear(); myFreeVariables.clear(); myFreeIndices = null; myPositiveVariables.clear(); myPositiveIndices = null; myNegativeVariables.clear(); myNegativeIndices = null; myIntegerVariables.clear(); myIntegerIndices = null; } public Expression generateCut(final Expression constraint, final Optimisation.Result solution) { return null; } public Expression getExpression(final String name) { return myExpressions.get(name); } public Collection<Expression> getExpressions() { return Collections.unmodifiableCollection(myExpressions.values()); } public Set<IntIndex> getFixedVariables() { myFixedVariables.clear(); for (final Variable tmpVar : myVariables) { if (tmpVar.isFixed()) { myFixedVariables.add(tmpVar.getIndex()); } } return Collections.unmodifiableSet(myFixedVariables); } /** * @return A list of the variables that are not fixed at a specific value */ public List<Variable> getFreeVariables() { if (myFreeIndices == null) { this.categoriseVariables(); } return Collections.unmodifiableList(myFreeVariables); } /** * @return A list of the variables that are not fixed at a specific value and are marked as integer * variables */ public List<Variable> getIntegerVariables() { if (myIntegerIndices == null) { this.categoriseVariables(); } return Collections.unmodifiableList(myIntegerVariables); } /** * @return A list of the variables that are not fixed at a specific value and whos range include negative * values */ public List<Variable> getNegativeVariables() { if (myNegativeIndices == null) { this.categoriseVariables(); } return Collections.unmodifiableList(myNegativeVariables); } /** * @return A list of the variables that are not fixed at a specific value and whos range include positive * values and/or zero */ public List<Variable> getPositiveVariables() { if (myPositiveIndices == null) { this.categoriseVariables(); } return Collections.unmodifiableList(myPositiveVariables); } public Variable getVariable(final int index) { return myVariables.get(index); } public Variable getVariable(final IntIndex index) { return myVariables.get(index.index); } public List<Variable> getVariables() { return Collections.unmodifiableList(myVariables); } public Optimisation.Result getVariableValues() { return this.getVariableValues(options.feasibility); } /** * Null variable values are replaced with 0.0. If any variable value is null the state is set to * INFEASIBLE even if zero would actually be a feasible value. The objective function value is not * calculated for infeasible variable values. */ public Optimisation.Result getVariableValues(final NumberContext validationContext) { final int numberOfVariables = myVariables.size(); State retState = State.UNEXPLORED; double retValue = Double.NaN; final Array1D<BigDecimal> retSolution = Array1D.BIG.makeZero(numberOfVariables); boolean allVarsSomeInfo = true; boolean shouldCheckGradient = false; for (int i = 0; i < numberOfVariables; i++) { final Variable tmpVariable = myVariables.get(i); if (tmpVariable.getValue() != null) { retSolution.set(i, tmpVariable.getValue()); } else { if (tmpVariable.isEqualityConstraint()) { retSolution.set(i, tmpVariable.getLowerLimit()); } else if (tmpVariable.isLowerLimitSet() && tmpVariable.isUpperLimitSet()) { retSolution.set(i, BigMath.DIVIDE.invoke(tmpVariable.getLowerLimit().add(tmpVariable.getUpperLimit()), TWO)); shouldCheckGradient = true; } else if (tmpVariable.isLowerLimitSet()) { retSolution.set(i, tmpVariable.getLowerLimit()); } else if (tmpVariable.isUpperLimitSet()) { retSolution.set(i, tmpVariable.getUpperLimit()); } else { retSolution.set(i, ZERO); allVarsSomeInfo = false; // This var no info } } } if (shouldCheckGradient && this.isAnyObjectiveQuadratic()) { MatrixStore<Double> gradient = this.objective().getAdjustedGradient(retSolution); double grad = 0.0; for (int i = 0; i < numberOfVariables; i++) { final Variable tmpVariable = myVariables.get(i); if (tmpVariable.isLowerLimitSet() && tmpVariable.isUpperLimitSet()) { grad = gradient.doubleValue(i); if (this.isMinimisation()) { grad = -grad; } if (grad < 0.0) { retSolution.set(i, tmpVariable.getLowerLimit()); } else { retSolution.set(i, tmpVariable.getUpperLimit()); } } } } if (allVarsSomeInfo) { if (this.validate(retSolution, validationContext)) { retState = State.FEASIBLE; retValue = this.objective().evaluate(retSolution).doubleValue(); } else { retState = State.APPROXIMATE; } } else { retState = State.INFEASIBLE; } return new Optimisation.Result(retState, retValue, retSolution); } public int indexOf(final Variable variable) { return variable.getIndex().index; } /** * @param globalIndex General, global, variable index * @return Local index among the free variables. -1 indicates the variable is not a positive variable. */ public int indexOfFreeVariable(final int globalIndex) { return myFreeIndices[globalIndex]; } public int indexOfFreeVariable(final IntIndex variableIndex) { return this.indexOfFreeVariable(variableIndex.index); } public int indexOfFreeVariable(final Variable variable) { return this.indexOfFreeVariable(this.indexOf(variable)); } /** * @param globalIndex General, global, variable index * @return Local index among the integer variables. -1 indicates the variable is not an integer variable. */ public int indexOfIntegerVariable(final int globalIndex) { return myIntegerIndices[globalIndex]; } public int indexOfIntegerVariable(final IntIndex variableIndex) { return this.indexOfIntegerVariable(variableIndex.index); } public int indexOfIntegerVariable(final Variable variable) { return this.indexOfIntegerVariable(variable.getIndex().index); } /** * @param globalIndex General, global, variable index * @return Local index among the negative variables. -1 indicates the variable is not a negative variable. */ public int indexOfNegativeVariable(final int globalIndex) { return myNegativeIndices[globalIndex]; } public int indexOfNegativeVariable(final IntIndex variableIndex) { return this.indexOfNegativeVariable(variableIndex.index); } public int indexOfNegativeVariable(final Variable variable) { return this.indexOfNegativeVariable(this.indexOf(variable)); } /** * @param globalIndex General, global, variable index * @return Local index among the positive variables. -1 indicates the variable is not a positive variable. */ public int indexOfPositiveVariable(final int globalIndex) { return myPositiveIndices[globalIndex]; } public int indexOfPositiveVariable(final IntIndex variableIndex) { return this.indexOfPositiveVariable(variableIndex.index); } public int indexOfPositiveVariable(final Variable variable) { return this.indexOfPositiveVariable(this.indexOf(variable)); } public boolean isAnyConstraintQuadratic() { boolean retVal = false; for (Expression expr : myExpressions.values()) { retVal |= (expr.isConstraint() && !expr.isRedundant() && expr.isAnyQuadraticFactorNonZero()); } return retVal; } /** * Objective or any constraint has quadratic part. * * @deprecated v45 Use {@link #isAnyConstraintQuadratic()} or {@link #isAnyObjectiveQuadratic()} instead */ @Deprecated public boolean isAnyExpressionQuadratic() { boolean retVal = false; for (Expression expr : myExpressions.values()) { retVal |= (expr.isAnyQuadraticFactorNonZero() && (expr.isObjective() || (expr.isConstraint() && !expr.isRedundant()))); } return retVal; } public boolean isAnyObjectiveQuadratic() { boolean retVal = false; for (Expression expr : myExpressions.values()) { retVal |= (expr.isObjective() && expr.isAnyQuadraticFactorNonZero()); } return retVal; } public boolean isAnyVariableFixed() { return myVariables.stream().anyMatch(v -> v.isFixed()); } public boolean isAnyVariableInteger() { if (myRelaxed) { return false; } boolean retVal = false; for (int i = 0, limit = myVariables.size(); !retVal && (i < limit); i++) { Variable variable = myVariables.get(i); retVal |= (variable.isInteger() && !variable.isFixed()); } return retVal; } public boolean isWorkCopy() { return myWorkCopy; } public void limitObjective(final BigDecimal lower, final BigDecimal upper) { Expression constrExpr = myExpressions.get(OBJ_FUNC_AS_CONSTR_KEY); if (constrExpr == null) { final Expression objExpr = this.objective(); if (!objExpr.isAnyQuadraticFactorNonZero()) { constrExpr = objExpr.copy(this, false); myExpressions.put(OBJ_FUNC_AS_CONSTR_KEY, constrExpr); } } if (constrExpr != null) { constrExpr.lower(lower).upper(upper); if (constrExpr.isLinearAndAllInteger()) { constrExpr.doIntegerRounding(); } } } public Optimisation.Result maximise() { this.setMaximisation(); return this.optimise(); } public Optimisation.Result minimise() { this.setMinimisation(); return this.optimise(); } /** * This is generated on demend – you should not cache this. More specifically, modifications made to this * expression will not be part of the optimisation model. You define the objective by setting the * {@link Variable#weight(Number)}/{@link Expression#weight(Number)} on one or more variables and/or * expressions. * * @return The generated/aggregated objective function */ public Expression objective() { final Expression retVal = new Expression(OBJECTIVE, this); Variable tmpVariable; for (int i = 0; i < myVariables.size(); i++) { tmpVariable = myVariables.get(i); if (tmpVariable.isObjective()) { retVal.set(i, tmpVariable.getContributionWeight()); } } BigDecimal tmpOldVal = null; BigDecimal tmpDiff = null; BigDecimal tmpNewVal = null; for (final Expression tmpExpression : myExpressions.values()) { if (tmpExpression.isObjective()) { final BigDecimal tmpContributionWeight = tmpExpression.getContributionWeight(); final boolean tmpNotOne = tmpContributionWeight.compareTo(ONE) != 0; // To avoid multiplication by 1.0 if (tmpExpression.isAnyLinearFactorNonZero()) { for (final IntIndex tmpKey : tmpExpression.getLinearKeySet()) { tmpOldVal = retVal.get(tmpKey); tmpDiff = tmpExpression.get(tmpKey); tmpNewVal = tmpOldVal.add(tmpNotOne ? tmpContributionWeight.multiply(tmpDiff) : tmpDiff); final Number value = tmpNewVal; retVal.set(tmpKey, value); } } if (tmpExpression.isAnyQuadraticFactorNonZero()) { for (final IntRowColumn tmpKey : tmpExpression.getQuadraticKeySet()) { tmpOldVal = retVal.get(tmpKey); tmpDiff = tmpExpression.get(tmpKey); tmpNewVal = tmpOldVal.add(tmpNotOne ? tmpContributionWeight.multiply(tmpDiff) : tmpDiff); final Number value = tmpNewVal; retVal.set(tmpKey, value); } } } } return retVal; } /** * <p> * The general recommendation is to NOT call this method directly. Instead you should use/call * {@link #maximise()} or {@link #minimise()}. * </P> * <p> * The primary use case for this method is as a callback method for solvers that iteratively modifies the * model and solves at each iteration point. * </P> * <p> * With direct usage of this method: * </P> * <ul> * <li>Maximisation/Minimisation is undefined (you don't know which it is)</li> * <li>The solution is not written back to the model</li> * <li>The solution is not validated by the model</li> * </ul> */ public ExpressionsBasedModel.Intermediate prepare() { return new ExpressionsBasedModel.Intermediate(this); } public ExpressionsBasedModel relax(final boolean inPlace) { final ExpressionsBasedModel retVal = inPlace ? this : new ExpressionsBasedModel(this, true, false); if (inPlace) { myRelaxed = true; } return retVal; } public ExpressionsBasedModel simplify() { this.scanEntities(); this.presolve(); final ExpressionsBasedModel retVal = new ExpressionsBasedModel(this, true, false); return retVal; } public ExpressionsBasedModel snapshot() { return new ExpressionsBasedModel(this, true, false); } @Override public String toString() { final StringBuilder retVal = new StringBuilder(START_END); for (final Variable tmpVariable : myVariables) { tmpVariable.appendToString(retVal); retVal.append(NEW_LINE); } for (final Expression tmpExpression : myExpressions.values()) { // if ((tmpExpression.isConstraint() && !tmpExpression.isRedundant()) || tmpExpression.isObjective()) { tmpExpression.appendToString(retVal, this.getVariableValues()); retVal.append(NEW_LINE); // } } return retVal.append(START_END).toString(); } /** * This methods validtes model construction only. All the other validate(...) method validates the * solution (one way or another). * * @see org.ojalgo.optimisation.Optimisation.Model#validate() */ public boolean validate() { final Printer appender = options.logger_detailed ? options.logger_appender : BasicLogger.NULL; boolean retVal = true; for (final Variable tmpVariable : myVariables) { retVal &= tmpVariable.validate(appender); } for (final Expression tmpExpression : myExpressions.values()) { retVal &= tmpExpression.validate(appender); } return retVal; } public boolean validate(final Access1D<BigDecimal> solution) { final NumberContext context = options.feasibility; final Printer appender = (options.logger_detailed && (options.logger_appender != null)) ? options.logger_appender : BasicLogger.NULL; return this.validate(solution, context, appender); } public boolean validate(final Access1D<BigDecimal> solution, final NumberContext context) { final Printer appender = (options.logger_detailed && (options.logger_appender != null)) ? options.logger_appender : BasicLogger.NULL; return this.validate(solution, context, appender); } public boolean validate(final Access1D<BigDecimal> solution, final NumberContext context, final Printer appender) { ProgrammingError.throwIfNull(solution, context, appender); final int size = myVariables.size(); boolean retVal = size == solution.count(); for (int i = 0; retVal && (i < size); i++) { final Variable tmpVariable = myVariables.get(i); final BigDecimal value = solution.get(i); retVal &= tmpVariable.validate(value, context, appender, myRelaxed); } if (retVal) { for (final Expression tmpExpression : myExpressions.values()) { final BigDecimal value = tmpExpression.evaluate(solution); retVal &= tmpExpression.validate(value, context, appender); } } return retVal; } public boolean validate(final Access1D<BigDecimal> solution, final Printer appender) { final NumberContext context = options.feasibility; return this.validate(solution, context, appender); } public boolean validate(final NumberContext context) { final Result solution = this.getVariableValues(context); final Printer appender = (options.logger_detailed && (options.logger_appender != null)) ? options.logger_appender : BasicLogger.NULL; return this.validate(solution, context, appender); } public boolean validate(final NumberContext context, final Printer appender) { final Access1D<BigDecimal> solution = this.getVariableValues(context); return this.validate(solution, context, appender); } public boolean validate(final Printer appender) { final NumberContext context = options.feasibility; final Result solution = this.getVariableValues(context); return this.validate(solution, context, appender); } /** * @return A stream of variables that are not fixed */ public Stream<Variable> variables() { return myVariables.stream().filter((final Variable v) -> (!v.isEqualityConstraint())); } private void categoriseVariables() { final int tmpLength = myVariables.size(); myFreeVariables.clear(); myFreeIndices = new int[tmpLength]; Arrays.fill(myFreeIndices, -1); myPositiveVariables.clear(); myPositiveIndices = new int[tmpLength]; Arrays.fill(myPositiveIndices, -1); myNegativeVariables.clear(); myNegativeIndices = new int[tmpLength]; Arrays.fill(myNegativeIndices, -1); myIntegerVariables.clear(); myIntegerIndices = new int[tmpLength]; Arrays.fill(myIntegerIndices, -1); for (int i = 0; i < tmpLength; i++) { final Variable tmpVariable = myVariables.get(i); if (!tmpVariable.isFixed()) { myFreeVariables.add(tmpVariable); myFreeIndices[i] = myFreeVariables.size() - 1; if (!tmpVariable.isUpperLimitSet() || (tmpVariable.getUpperLimit().signum() == 1)) { myPositiveVariables.add(tmpVariable); myPositiveIndices[i] = myPositiveVariables.size() - 1; } if (!tmpVariable.isLowerLimitSet() || (tmpVariable.getLowerLimit().signum() == -1)) { myNegativeVariables.add(tmpVariable); myNegativeIndices[i] = myNegativeVariables.size() - 1; } if (tmpVariable.isInteger()) { myIntegerVariables.add(tmpVariable); myIntegerIndices[i] = myIntegerVariables.size() - 1; } } } } private void scanEntities() { boolean anyVarInt = this.isAnyVariableInteger(); for (final Expression tmpExpr : myExpressions.values()) { Set<IntIndex> allVars = tmpExpr.getLinearKeySet(); BigDecimal lower = tmpExpr.getLowerLimit(); BigDecimal upper = tmpExpr.getUpperLimit(); if (tmpExpr.isObjective()) { Presolvers.LINEAR_OBJECTIVE.simplify(tmpExpr, allVars, lower, upper, options.feasibility); } if (tmpExpr.isConstraint()) { Presolvers.ZERO_ONE_TWO.simplify(tmpExpr, allVars, lower, upper, options.feasibility); if (anyVarInt) { Presolvers.INTEGER_EXPRESSION_ROUNDING.simplify(tmpExpr, allVars, lower, upper, options.feasibility); } } } for (final Variable tmpVar : myVariables) { Presolvers.UNREFERENCED.simplify(tmpVar, this); if (tmpVar.isConstraint()) { if (anyVarInt) { Presolvers.INTEGER_VARIABLE_ROUNDING.simplify(tmpVar, this); } } } } void addReference(final IntIndex index) { myReferences.add(index); } Stream<Expression> expressions() { return myExpressions.values().stream(); } ExpressionsBasedModel.Integration<?> getIntegration() { ExpressionsBasedModel.Integration<?> retVal = null; for (final ExpressionsBasedModel.Integration<?> preferred : PREFERRED_INTEGRATIONS) { if (preferred.isCapable(this)) { retVal = preferred; break; } } if (retVal == null) { if (this.isAnyVariableInteger()) { if (INTEGER_INTEGRATION.isCapable(this)) { retVal = INTEGER_INTEGRATION; } } else { if (CONVEX_INTEGRATION.isCapable(this)) { retVal = CONVEX_INTEGRATION; } else if (LINEAR_INTEGRATION.isCapable(this)) { retVal = LINEAR_INTEGRATION; } } } if (retVal == null) { for (final ExpressionsBasedModel.Integration<?> fallback : FALLBACK_INTEGRATIONS) { if (fallback.isCapable(this)) { retVal = fallback; break; } } } if (retVal == null) { throw new ProgrammingError("No solver integration available that can handle this model!"); } return retVal; } boolean isFixed() { return myVariables.stream().allMatch(v -> v.isFixed()); } boolean isInfeasible() { if (myInfeasible) { return true; } for (final Expression tmpExpression : myExpressions.values()) { if (tmpExpression.isInfeasible()) { return myInfeasible = true; } } for (final Variable tmpVariable : myVariables) { if (tmpVariable.isInfeasible()) { return myInfeasible = true; } } return false; } boolean isReferenced(final Variable variable) { return myReferences.contains(variable.getIndex()); } boolean isUnbounded() { return myVariables.stream().anyMatch(v -> v.isUnbounded()); } Optimisation.Result optimise() { if (!myWorkCopy && (PRESOLVERS.size() > 0)) { this.scanEntities(); } Intermediate prepared = this.prepare(); Optimisation.Result result = prepared.solve(null); for (int i = 0, limit = myVariables.size(); i < limit; i++) { final Variable tmpVariable = myVariables.get(i); if (!tmpVariable.isFixed()) { tmpVariable.setValue(options.solution.toBigDecimal(result.doubleValue(i))); } } Result retSolution = this.getVariableValues(); double retValue = this.objective().evaluate(retSolution).doubleValue(); Optimisation.State retState = result.getState(); return new Optimisation.Result(retState, retValue, retSolution); } void presolve() { // myExpressions.values().forEach(expr -> expr.reset()); boolean needToRepeat = false; do { final Set<IntIndex> fixedVariables = this.getFixedVariables(); BigDecimal compensatedLowerLimit; BigDecimal compensatedUpperLimit; needToRepeat = false; for (final Expression expr : this.getExpressions()) { if (!needToRepeat && expr.isConstraint() && !expr.isInfeasible() && !expr.isRedundant() && (expr.countQuadraticFactors() == 0)) { BigDecimal calculateSetValue = expr.calculateSetValue(fixedVariables); compensatedLowerLimit = expr.getCompensatedLowerLimit(calculateSetValue); compensatedUpperLimit = expr.getCompensatedUpperLimit(calculateSetValue); myTemporary.clear(); myTemporary.addAll(expr.getLinearKeySet()); myTemporary.removeAll(fixedVariables); for (final Presolver presolver : PRESOLVERS) { if (!needToRepeat) { needToRepeat |= presolver.simplify(expr, myTemporary, compensatedLowerLimit, compensatedUpperLimit, options.feasibility); } } } } } while (needToRepeat); this.categoriseVariables(); } void setInfeasible() { myInfeasible = true; } }
src/org/ojalgo/optimisation/ExpressionsBasedModel.java
/* * Copyright 1997-2019 Optimatika * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.ojalgo.optimisation; import static org.ojalgo.function.constant.BigMath.*; import java.math.BigDecimal; import java.util.*; import java.util.stream.Stream; import org.ojalgo.ProgrammingError; import org.ojalgo.array.Array1D; import org.ojalgo.array.Primitive64Array; import org.ojalgo.function.constant.BigMath; import org.ojalgo.matrix.store.MatrixStore; import org.ojalgo.netio.BasicLogger; import org.ojalgo.netio.BasicLogger.Printer; import org.ojalgo.optimisation.convex.ConvexSolver; import org.ojalgo.optimisation.integer.IntegerSolver; import org.ojalgo.optimisation.linear.LinearSolver; import org.ojalgo.structure.Access1D; import org.ojalgo.structure.Structure1D.IntIndex; import org.ojalgo.structure.Structure2D.IntRowColumn; import org.ojalgo.type.context.NumberContext; /** * <p> * Lets you construct optimisation problems by combining (mathematical) expressions in terms of variables. * Each expression or variable can be a constraint and/or contribute to the objective function. An expression * or variable is turned into a constraint by setting a lower and/or upper limit. Use * {@linkplain Expression#lower(Number)}, {@linkplain Expression#upper(Number)} or * {@linkplain Expression#level(Number)}. An expression or variable is made part of (contributing to) the * objective function by setting a contribution weight. Use {@linkplain Expression#weight(Number)}. * </p> * <p> * You may think of variables as simple (the simplest possible) expressions, and of expressions as weighted * combinations of variables. They are both model entities and it is as such they can be turned into * constraints and set to contribute to the objective function. Alternatively you may choose to disregard the * fact that variables are model entities and simply treat them as index values. In this case everything * (constraints and objective) needs to be defined using expressions. * </p> * <p> * Basic instructions: * </p> * <ol> * <li>Define (create) a set of variables. Set contribution weights and lower/upper limits as needed.</li> * <li>Create a model using that set of variables.</li> * <li>Add expressions to the model. The model is the expression factory. Set contribution weights and * lower/upper limits as needed.</li> * <li>Solve your problem using either minimise() or maximise()</li> * </ol> * <p> * When using this class you do not need to worry about which solver will actually be used. The docs of the * various solvers describe requirements on input formats and similar. This is handled for you and should * absolutely NOT be considered here! Compared to using the various solvers directly this class actually does * something for you: * </p> * <ol> * <li>You can model your problems without worrying about specific solver requirements.</li> * <li>It knows which solver to use.</li> * <li>It knows how to use that solver.</li> * <li>It has a presolver that tries to simplify the problem before invoking a solver (sometimes it turns out * there is no need to invoke a solver at all).</li> * <li>When/if needed it scales problem parameters, before creating solver specific data structures, to * minimize numerical problems in the solvers.</li> * <li>It's the only way to access the integer solver.</li> * </ol> * <p> * Different solvers can be used, and ojAlgo comes with collection built in. The default built-in solvers can * handle anythimng you can model with a couple of restrictions: * </p> * <ul> * <li>No quadratic constraints (The plan is that future versions should not have this limitation.)</li> * <li>If you use quadratic expressions make sure they're convex. This is most likely a requirement even with * 3:d party solvers.</li> * </ul> * * @author apete */ public final class ExpressionsBasedModel extends AbstractModel { public static abstract class Integration<S extends Optimisation.Solver> implements Optimisation.Integration<ExpressionsBasedModel, S> { /** * @see org.ojalgo.optimisation.Optimisation.Integration#extractSolverState(org.ojalgo.optimisation.Optimisation.Model) */ public final Result extractSolverState(final ExpressionsBasedModel model) { return this.toSolverState(model.getVariableValues(), model); } public Result toModelState(final Result solverState, final ExpressionsBasedModel model) { final int numbVariables = model.countVariables(); if (this.isSolutionMapped()) { final List<Variable> freeVariables = model.getFreeVariables(); final Set<IntIndex> fixedVariables = model.getFixedVariables(); if (solverState.count() != freeVariables.size()) { throw new IllegalStateException(); } final Primitive64Array modelSolution = Primitive64Array.make(numbVariables); for (final IntIndex fixedIndex : fixedVariables) { modelSolution.set(fixedIndex.index, model.getVariable(fixedIndex.index).getValue()); } for (int f = 0; f < freeVariables.size(); f++) { final int freeIndex = model.indexOf(freeVariables.get(f)); modelSolution.set(freeIndex, solverState.doubleValue(f)); } return new Result(solverState.getState(), modelSolution); } else { if (solverState.count() != numbVariables) { throw new IllegalStateException(); } return solverState; } } public Result toSolverState(final Result modelState, final ExpressionsBasedModel model) { if (this.isSolutionMapped()) { final List<Variable> tmpFreeVariables = model.getFreeVariables(); final int numbFreeVars = tmpFreeVariables.size(); final Primitive64Array solverSolution = Primitive64Array.make(numbFreeVars); for (int i = 0; i < numbFreeVars; i++) { final Variable variable = tmpFreeVariables.get(i); final int modelIndex = model.indexOf(variable); solverSolution.set(i, modelState.doubleValue(modelIndex)); } return new Result(modelState.getState(), solverSolution); } else { return modelState; } } /** * @return The index with which one can reference parameters related to this variable in the solver. */ protected int getIndexInSolver(final ExpressionsBasedModel model, final Variable variable) { return model.indexOfFreeVariable(variable); } /** * @return true if the set of variables present in the solver is not precisely the same as in the * model. If fixed variables are omitted or if variables are split into a positive and * negative part, then this method must return true */ protected abstract boolean isSolutionMapped(); } public static final class Intermediate implements Optimisation.Solver { private boolean myInPlaceUpdatesOK = true; private transient ExpressionsBasedModel.Integration<?> myIntegration = null; private final ExpressionsBasedModel myModel; private transient Optimisation.Solver mySolver = null; Intermediate(final ExpressionsBasedModel model) { super(); myModel = model; myIntegration = null; mySolver = null; } /** * Force re-generation of any cached/transient data */ public void dispose() { Solver.super.dispose(); if (mySolver != null) { mySolver.dispose(); mySolver = null; } myIntegration = null; } public ExpressionsBasedModel getModel() { return myModel; } public Variable getVariable(final int globalIndex) { return myModel.getVariable(globalIndex); } public Variable getVariable(final IntIndex globalIndex) { return myModel.getVariable(globalIndex); } public Optimisation.Result solve(final Optimisation.Result candidate) { if (mySolver == null) { myModel.presolve(); } if (myModel.isInfeasible()) { final Optimisation.Result solution = candidate != null ? candidate : myModel.getVariableValues(); return new Optimisation.Result(State.INFEASIBLE, solution); } else if (myModel.isUnbounded()) { if ((candidate != null) && myModel.validate(candidate)) { return new Optimisation.Result(State.UNBOUNDED, candidate); } final Optimisation.Result derivedSolution = myModel.getVariableValues(); if (derivedSolution.getState().isFeasible()) { return new Optimisation.Result(State.UNBOUNDED, derivedSolution); } } else if (myModel.isFixed()) { final Optimisation.Result derivedSolution = myModel.getVariableValues(); if (derivedSolution.getState().isFeasible()) { return new Optimisation.Result(State.DISTINCT, derivedSolution); } else { return new Optimisation.Result(State.INVALID, derivedSolution); } } final ExpressionsBasedModel.Integration<?> integration = this.getIntegration(); final Optimisation.Solver solver = this.getSolver(); Optimisation.Result retVal = candidate != null ? candidate : myModel.getVariableValues(); retVal = integration.toSolverState(retVal, myModel); retVal = solver.solve(retVal); retVal = integration.toModelState(retVal, myModel); return retVal; } @Override public String toString() { return myModel.toString(); } public void update(final int index) { this.update(myModel.getVariable(index)); } public void update(final IntIndex index) { this.update(myModel.getVariable(index)); } public void update(final Variable variable) { if (myInPlaceUpdatesOK && (mySolver != null) && (mySolver instanceof UpdatableSolver) && variable.isFixed()) { final UpdatableSolver updatableSolver = (UpdatableSolver) mySolver; final int indexInSolver = this.getIntegration().getIndexInSolver(myModel, variable); final double fixedValue = variable.getValue().doubleValue(); if (updatableSolver.fixVariable(indexInSolver, fixedValue)) { // Solver updated in-place return; } else { myInPlaceUpdatesOK = false; } } // Solver will be re-generated mySolver = null; } public boolean validate(final Access1D<BigDecimal> solution, final Printer appender) { return myModel.validate(solution, appender); } public boolean validate(final Result solution) { return myModel.validate(solution); } ExpressionsBasedModel.Integration<?> getIntegration() { if (myIntegration == null) { myIntegration = myModel.getIntegration(); } return myIntegration; } Optimisation.Solver getSolver() { if (mySolver == null) { mySolver = this.getIntegration().build(myModel); } return mySolver; } } public static abstract class Presolver extends Simplifier<Expression, Presolver> { protected Presolver(final int executionOrder) { super(executionOrder); } /** * @param remaining TODO * @param lower TODO * @param upper TODO * @return True if any model entity was modified so that a re-run of the presolvers is necessary - * typically when/if a variable was fixed. */ public abstract boolean simplify(Expression expression, Set<IntIndex> remaining, BigDecimal lower, BigDecimal upper, NumberContext precision); @Override boolean isApplicable(final Expression target) { return target.isConstraint() && !target.isInfeasible() && !target.isRedundant() && (target.countQuadraticFactors() == 0); } } static abstract class Simplifier<ME extends ModelEntity<?>, S extends Simplifier<?, ?>> implements Comparable<S> { private final int myExecutionOrder; private final UUID myUUID = UUID.randomUUID(); Simplifier(final int executionOrder) { super(); myExecutionOrder = executionOrder; } public final int compareTo(final S reference) { return Integer.compare(myExecutionOrder, reference.getExecutionOrder()); } @Override public final boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Simplifier)) { return false; } final Simplifier<?, ?> other = (Simplifier<?, ?>) obj; if (myUUID == null) { if (other.myUUID != null) { return false; } } else if (!myUUID.equals(other.myUUID)) { return false; } return true; } @Override public final int hashCode() { final int prime = 31; int result = 1; result = (prime * result) + ((myUUID == null) ? 0 : myUUID.hashCode()); return result; } final int getExecutionOrder() { return myExecutionOrder; } abstract boolean isApplicable(final ME target); } static abstract class VariableAnalyser extends Simplifier<Variable, VariableAnalyser> { protected VariableAnalyser(final int executionOrder) { super(executionOrder); } public abstract boolean simplify(Variable variable, ExpressionsBasedModel model); @Override boolean isApplicable(final Variable target) { return true; } } private static final ConvexSolver.ModelIntegration CONVEX_INTEGRATION = new ConvexSolver.ModelIntegration(); private static final List<ExpressionsBasedModel.Integration<?>> FALLBACK_INTEGRATIONS = new ArrayList<>(); private static final IntegerSolver.ModelIntegration INTEGER_INTEGRATION = new IntegerSolver.ModelIntegration(); private static final LinearSolver.ModelIntegration LINEAR_INTEGRATION = new LinearSolver.ModelIntegration(); private static final String NEW_LINE = "\n"; private static final String OBJ_FUNC_AS_CONSTR_KEY = UUID.randomUUID().toString(); private static final String OBJECTIVE = "Generated/Aggregated Objective"; private static final List<ExpressionsBasedModel.Integration<?>> PREFERRED_INTEGRATIONS = new ArrayList<>(); private static final TreeSet<Presolver> PRESOLVERS = new TreeSet<>(); private static final String START_END = "############################################\n"; static { ExpressionsBasedModel.addPresolver(Presolvers.ZERO_ONE_TWO); ExpressionsBasedModel.addPresolver(Presolvers.REDUNDANT_CONSTRAINT); } public static boolean addFallbackSolver(final Integration<?> integration) { return FALLBACK_INTEGRATIONS.add(integration); } /** * @deprecated v48 Use either {@link #addPreferredSolver(Integration)} or * {@link #addFallbackSolver(Integration)} instead */ @Deprecated public static boolean addIntegration(final Integration<?> integration) { return ExpressionsBasedModel.addPreferredSolver(integration); } public static boolean addPreferredSolver(final Integration<?> integration) { return PREFERRED_INTEGRATIONS.add(integration); } public static boolean addPresolver(final Presolver presolver) { return PRESOLVERS.add(presolver); } public static void clearIntegrations() { PREFERRED_INTEGRATIONS.clear(); FALLBACK_INTEGRATIONS.clear(); } public static void clearPresolvers() { PRESOLVERS.clear(); } public static boolean removeIntegration(final Integration<?> integration) { return PREFERRED_INTEGRATIONS.remove(integration) | FALLBACK_INTEGRATIONS.remove(integration); } public static boolean removePresolver(final Presolver presolver) { return PRESOLVERS.remove(presolver); } private final Map<String, Expression> myExpressions = new HashMap<>(); private final Set<IntIndex> myFixedVariables = new HashSet<>(); private transient int[] myFreeIndices = null; private final List<Variable> myFreeVariables = new ArrayList<>(); private transient boolean myInfeasible = false; private transient int[] myIntegerIndices = null; private final List<Variable> myIntegerVariables = new ArrayList<>(); private transient int[] myNegativeIndices = null; private final List<Variable> myNegativeVariables = new ArrayList<>(); private transient int[] myPositiveIndices = null; private final List<Variable> myPositiveVariables = new ArrayList<>(); private final Set<IntIndex> myReferences = new HashSet<>(); private boolean myRelaxed; /** * Temporary storage for some expresssion specific subset of variables */ private final Set<IntIndex> myTemporary = new HashSet<>(); private final ArrayList<Variable> myVariables = new ArrayList<>(); private final boolean myWorkCopy; public ExpressionsBasedModel() { super(); myWorkCopy = false; myRelaxed = false; } public ExpressionsBasedModel(final Collection<? extends Variable> variables) { super(); for (final Variable tmpVariable : variables) { this.addVariable(tmpVariable); } myWorkCopy = false; myRelaxed = false; } public ExpressionsBasedModel(final Optimisation.Options someOptions) { super(someOptions); myWorkCopy = false; myRelaxed = false; } public ExpressionsBasedModel(final Variable... variables) { super(); for (final Variable tmpVariable : variables) { this.addVariable(tmpVariable); } myWorkCopy = false; myRelaxed = false; } ExpressionsBasedModel(final ExpressionsBasedModel modelToCopy, final boolean workCopy, final boolean allEntities) { super(modelToCopy.options); this.setMinimisation(modelToCopy.isMinimisation()); for (final Variable tmpVariable : modelToCopy.getVariables()) { this.addVariable(tmpVariable.copy()); } for (final Expression tmpExpression : modelToCopy.getExpressions()) { if (allEntities || tmpExpression.isObjective() || (tmpExpression.isConstraint() && !tmpExpression.isRedundant())) { myExpressions.put(tmpExpression.getName(), tmpExpression.copy(this, !workCopy)); } else { // BasicLogger.DEBUG.println("Discarding expression: {}", tmpExpression); } } myWorkCopy = workCopy; myRelaxed = workCopy; } public Expression addExpression() { return this.addExpression("EXPR" + myExpressions.size()); } public Expression addExpression(final String name) { final Expression retVal = new Expression(name, this); myExpressions.put(name, retVal); return retVal; } /** * Creates a special ordered set (SOS) presolver instance and links that to the supplied expression. * When/if the presolver concludes that the SOS "constraints" are not possible the linked expression is * marked as infeasible. */ public void addSpecialOrderedSet(final Collection<Variable> orderedSet, final int type, final Expression linkedTo) { if (type <= 0) { throw new ProgrammingError("Invalid SOS type!"); } if (!linkedTo.isConstraint()) { throw new ProgrammingError("The linked to expression needs to be a constraint!"); } final IntIndex[] sequence = new IntIndex[orderedSet.size()]; int index = 0; for (final Variable variable : orderedSet) { if ((variable == null) || (variable.getIndex() == null)) { throw new ProgrammingError("Variables must be already inserted in the model!"); } else { sequence[index++] = variable.getIndex(); } } ExpressionsBasedModel.addPresolver(new SpecialOrderedSet(sequence, type, linkedTo)); } /** * Calling this method will create 2 things: * <ol> * <li>A simple expression meassuring the sum of the (binary) variable values (the number of binary * variables that are "ON"). The upper, and optionally lower, limits are set as defined by the * <code>max</code> and <code>min</code> parameter values.</li> * <li>A custom presolver (specific to this SOS) to be used by the MIP solver. This presolver help to keep * track of which combinations of variable values or feasible, and is the only thing that enforces the * order.</li> * </ol> * * @param orderedSet The set members in correct order. Each of these variables must be binary. * @param min The minimum number of binary varibales in the set that must be "ON" (Set this to 0 if there * is no minimum.) * @param max The SOS type or maximum number of binary varibales in the set that may be "ON" */ public void addSpecialOrderedSet(final Collection<Variable> orderedSet, final int min, final int max) { if ((max <= 0) || (min > max)) { throw new ProgrammingError("Invalid min/max number of ON variables!"); } final String name = "SOS" + max + "-" + orderedSet.toString(); final Expression expression = this.addExpression(name); for (final Variable variable : orderedSet) { if ((variable == null) || (variable.getIndex() == null) || !variable.isBinary()) { throw new ProgrammingError("Variables must be binary and already inserted in the model!"); } else { expression.set(variable.getIndex(), ONE); } } expression.upper(BigDecimal.valueOf(max)); if (min > 0) { expression.lower(BigDecimal.valueOf(min)); } this.addSpecialOrderedSet(orderedSet, max, expression); } public Variable addVariable() { return this.addVariable("X" + myVariables.size()); } public Variable addVariable(final String name) { final Variable retVal = new Variable(name); this.addVariable(retVal); return retVal; } public void addVariable(final Variable variable) { if (myWorkCopy) { throw new IllegalStateException("This model is a work copy - its set of variables cannot be modified!"); } else { myVariables.add(variable); variable.setIndex(new IntIndex(myVariables.size() - 1)); } } public void addVariables(final Collection<? extends Variable> variables) { for (final Variable tmpVariable : variables) { this.addVariable(tmpVariable); } } public void addVariables(final Variable[] variables) { for (final Variable tmpVariable : variables) { this.addVariable(tmpVariable); } } /** * @return A stream of variables that are constraints and not fixed */ public Stream<Variable> bounds() { return this.variables().filter(v -> v.isConstraint() && !v.isFixed()); } /** * @return A prefiltered stream of expressions that are constraints and have not been markes as redundant */ public Stream<Expression> constraints() { return myExpressions.values().stream().filter(c -> c.isConstraint() && !c.isRedundant()); } public ExpressionsBasedModel copy() { return new ExpressionsBasedModel(this, false, true); } public int countExpressions() { return myExpressions.size(); } public int countVariables() { return myVariables.size(); } @Override public void dispose() { for (final Expression tmpExprerssion : myExpressions.values()) { tmpExprerssion.destroy(); } myExpressions.clear(); for (final Variable tmpVariable : myVariables) { tmpVariable.destroy(); } myVariables.clear(); myFixedVariables.clear(); myFreeVariables.clear(); myFreeIndices = null; myPositiveVariables.clear(); myPositiveIndices = null; myNegativeVariables.clear(); myNegativeIndices = null; myIntegerVariables.clear(); myIntegerIndices = null; } public Expression generateCut(final Expression constraint, final Optimisation.Result solution) { return null; } public Expression getExpression(final String name) { return myExpressions.get(name); } public Collection<Expression> getExpressions() { return Collections.unmodifiableCollection(myExpressions.values()); } public Set<IntIndex> getFixedVariables() { myFixedVariables.clear(); for (final Variable tmpVar : myVariables) { if (tmpVar.isFixed()) { myFixedVariables.add(tmpVar.getIndex()); } } return Collections.unmodifiableSet(myFixedVariables); } /** * @return A list of the variables that are not fixed at a specific value */ public List<Variable> getFreeVariables() { if (myFreeIndices == null) { this.categoriseVariables(); } return Collections.unmodifiableList(myFreeVariables); } /** * @return A list of the variables that are not fixed at a specific value and are marked as integer * variables */ public List<Variable> getIntegerVariables() { if (myIntegerIndices == null) { this.categoriseVariables(); } return Collections.unmodifiableList(myIntegerVariables); } /** * @return A list of the variables that are not fixed at a specific value and whos range include negative * values */ public List<Variable> getNegativeVariables() { if (myNegativeIndices == null) { this.categoriseVariables(); } return Collections.unmodifiableList(myNegativeVariables); } /** * @return A list of the variables that are not fixed at a specific value and whos range include positive * values and/or zero */ public List<Variable> getPositiveVariables() { if (myPositiveIndices == null) { this.categoriseVariables(); } return Collections.unmodifiableList(myPositiveVariables); } public Variable getVariable(final int index) { return myVariables.get(index); } public Variable getVariable(final IntIndex index) { return myVariables.get(index.index); } public List<Variable> getVariables() { return Collections.unmodifiableList(myVariables); } public Optimisation.Result getVariableValues() { return this.getVariableValues(options.feasibility); } /** * Null variable values are replaced with 0.0. If any variable value is null the state is set to * INFEASIBLE even if zero would actually be a feasible value. The objective function value is not * calculated for infeasible variable values. */ public Optimisation.Result getVariableValues(final NumberContext validationContext) { final int numberOfVariables = myVariables.size(); State retState = State.UNEXPLORED; double retValue = Double.NaN; final Array1D<BigDecimal> retSolution = Array1D.BIG.makeZero(numberOfVariables); boolean allVarsSomeInfo = true; boolean shouldCheckGradient = false; for (int i = 0; i < numberOfVariables; i++) { final Variable tmpVariable = myVariables.get(i); if (tmpVariable.getValue() != null) { retSolution.set(i, tmpVariable.getValue()); } else { if (tmpVariable.isEqualityConstraint()) { retSolution.set(i, tmpVariable.getLowerLimit()); } else if (tmpVariable.isLowerLimitSet() && tmpVariable.isUpperLimitSet()) { retSolution.set(i, BigMath.DIVIDE.invoke(tmpVariable.getLowerLimit().add(tmpVariable.getUpperLimit()), TWO)); shouldCheckGradient = true; } else if (tmpVariable.isLowerLimitSet()) { retSolution.set(i, tmpVariable.getLowerLimit()); } else if (tmpVariable.isUpperLimitSet()) { retSolution.set(i, tmpVariable.getUpperLimit()); } else { retSolution.set(i, ZERO); allVarsSomeInfo = false; // This var no info } } } if (shouldCheckGradient && this.isAnyObjectiveQuadratic()) { MatrixStore<Double> gradient = this.objective().getAdjustedGradient(retSolution); double grad = 0.0; for (int i = 0; i < numberOfVariables; i++) { final Variable tmpVariable = myVariables.get(i); if (tmpVariable.isLowerLimitSet() && tmpVariable.isUpperLimitSet()) { grad = gradient.doubleValue(i); if (this.isMinimisation()) { grad = -grad; } if (grad < 0.0) { retSolution.set(i, tmpVariable.getLowerLimit()); } else { retSolution.set(i, tmpVariable.getUpperLimit()); } } } } if (allVarsSomeInfo) { if (this.validate(retSolution, validationContext)) { retState = State.FEASIBLE; retValue = this.objective().evaluate(retSolution).doubleValue(); } else { retState = State.APPROXIMATE; } } else { retState = State.INFEASIBLE; } return new Optimisation.Result(retState, retValue, retSolution); } public int indexOf(final Variable variable) { return variable.getIndex().index; } /** * @param globalIndex General, global, variable index * @return Local index among the free variables. -1 indicates the variable is not a positive variable. */ public int indexOfFreeVariable(final int globalIndex) { return myFreeIndices[globalIndex]; } public int indexOfFreeVariable(final IntIndex variableIndex) { return this.indexOfFreeVariable(variableIndex.index); } public int indexOfFreeVariable(final Variable variable) { return this.indexOfFreeVariable(this.indexOf(variable)); } /** * @param globalIndex General, global, variable index * @return Local index among the integer variables. -1 indicates the variable is not an integer variable. */ public int indexOfIntegerVariable(final int globalIndex) { return myIntegerIndices[globalIndex]; } public int indexOfIntegerVariable(final IntIndex variableIndex) { return this.indexOfIntegerVariable(variableIndex.index); } public int indexOfIntegerVariable(final Variable variable) { return this.indexOfIntegerVariable(variable.getIndex().index); } /** * @param globalIndex General, global, variable index * @return Local index among the negative variables. -1 indicates the variable is not a negative variable. */ public int indexOfNegativeVariable(final int globalIndex) { return myNegativeIndices[globalIndex]; } public int indexOfNegativeVariable(final IntIndex variableIndex) { return this.indexOfNegativeVariable(variableIndex.index); } public int indexOfNegativeVariable(final Variable variable) { return this.indexOfNegativeVariable(this.indexOf(variable)); } /** * @param globalIndex General, global, variable index * @return Local index among the positive variables. -1 indicates the variable is not a positive variable. */ public int indexOfPositiveVariable(final int globalIndex) { return myPositiveIndices[globalIndex]; } public int indexOfPositiveVariable(final IntIndex variableIndex) { return this.indexOfPositiveVariable(variableIndex.index); } public int indexOfPositiveVariable(final Variable variable) { return this.indexOfPositiveVariable(this.indexOf(variable)); } public boolean isAnyConstraintQuadratic() { boolean retVal = false; for (Expression expr : myExpressions.values()) { retVal |= (expr.isConstraint() && !expr.isRedundant() && expr.isAnyQuadraticFactorNonZero()); } return retVal; } /** * Objective or any constraint has quadratic part. * * @deprecated v45 Use {@link #isAnyConstraintQuadratic()} or {@link #isAnyObjectiveQuadratic()} instead */ @Deprecated public boolean isAnyExpressionQuadratic() { boolean retVal = false; for (Expression expr : myExpressions.values()) { retVal |= (expr.isAnyQuadraticFactorNonZero() && (expr.isObjective() || (expr.isConstraint() && !expr.isRedundant()))); } return retVal; } public boolean isAnyObjectiveQuadratic() { boolean retVal = false; for (Expression expr : myExpressions.values()) { retVal |= (expr.isObjective() && expr.isAnyQuadraticFactorNonZero()); } return retVal; } public boolean isAnyVariableFixed() { return myVariables.stream().anyMatch(v -> v.isFixed()); } public boolean isAnyVariableInteger() { if (myRelaxed) { return false; } boolean retVal = false; for (int i = 0, limit = myVariables.size(); !retVal && (i < limit); i++) { Variable variable = myVariables.get(i); retVal |= (variable.isInteger() && !variable.isFixed()); } return retVal; } public boolean isWorkCopy() { return myWorkCopy; } public void limitObjective(final BigDecimal lower, final BigDecimal upper) { Expression constrExpr = myExpressions.get(OBJ_FUNC_AS_CONSTR_KEY); if (constrExpr == null) { final Expression objExpr = this.objective(); if (!objExpr.isAnyQuadraticFactorNonZero()) { constrExpr = objExpr.copy(this, false); myExpressions.put(OBJ_FUNC_AS_CONSTR_KEY, constrExpr); } } if (constrExpr != null) { constrExpr.lower(lower).upper(upper); if (constrExpr.isLinearAndAllInteger()) { constrExpr.doIntegerRounding(); } } } public Optimisation.Result maximise() { this.setMaximisation(); return this.optimise(); } public Optimisation.Result minimise() { this.setMinimisation(); return this.optimise(); } /** * This is generated on demend – you should not cache this. More specifically, modifications made to this * expression will not be part of the optimisation model. You define the objective by setting the * {@link Variable#weight(Number)}/{@link Expression#weight(Number)} on one or more variables and/or * expressions. * * @return The generated/aggregated objective function */ public Expression objective() { final Expression retVal = new Expression(OBJECTIVE, this); Variable tmpVariable; for (int i = 0; i < myVariables.size(); i++) { tmpVariable = myVariables.get(i); if (tmpVariable.isObjective()) { retVal.set(i, tmpVariable.getContributionWeight()); } } BigDecimal tmpOldVal = null; BigDecimal tmpDiff = null; BigDecimal tmpNewVal = null; for (final Expression tmpExpression : myExpressions.values()) { if (tmpExpression.isObjective()) { final BigDecimal tmpContributionWeight = tmpExpression.getContributionWeight(); final boolean tmpNotOne = tmpContributionWeight.compareTo(ONE) != 0; // To avoid multiplication by 1.0 if (tmpExpression.isAnyLinearFactorNonZero()) { for (final IntIndex tmpKey : tmpExpression.getLinearKeySet()) { tmpOldVal = retVal.get(tmpKey); tmpDiff = tmpExpression.get(tmpKey); tmpNewVal = tmpOldVal.add(tmpNotOne ? tmpContributionWeight.multiply(tmpDiff) : tmpDiff); final Number value = tmpNewVal; retVal.set(tmpKey, value); } } if (tmpExpression.isAnyQuadraticFactorNonZero()) { for (final IntRowColumn tmpKey : tmpExpression.getQuadraticKeySet()) { tmpOldVal = retVal.get(tmpKey); tmpDiff = tmpExpression.get(tmpKey); tmpNewVal = tmpOldVal.add(tmpNotOne ? tmpContributionWeight.multiply(tmpDiff) : tmpDiff); final Number value = tmpNewVal; retVal.set(tmpKey, value); } } } } return retVal; } /** * <p> * The general recommendation is to NOT call this method directly. Instead you should use/call * {@link #maximise()} or {@link #minimise()}. * </P> * <p> * The primary use case for this method is as a callback method for solvers that iteratively modifies the * model and solves at each iteration point. * </P> * <p> * With direct usage of this method: * </P> * <ul> * <li>Maximisation/Minimisation is undefined (you don't know which it is)</li> * <li>The solution is not written back to the model</li> * <li>The solution is not validated by the model</li> * </ul> */ public ExpressionsBasedModel.Intermediate prepare() { return new ExpressionsBasedModel.Intermediate(this); } public ExpressionsBasedModel relax(final boolean inPlace) { final ExpressionsBasedModel retVal = inPlace ? this : new ExpressionsBasedModel(this, true, false); if (inPlace) { myRelaxed = true; } return retVal; } public ExpressionsBasedModel simplify() { this.scanEntities(); this.presolve(); final ExpressionsBasedModel retVal = new ExpressionsBasedModel(this, true, false); return retVal; } public ExpressionsBasedModel snapshot() { return new ExpressionsBasedModel(this, true, false); } @Override public String toString() { final StringBuilder retVal = new StringBuilder(START_END); for (final Variable tmpVariable : myVariables) { tmpVariable.appendToString(retVal); retVal.append(NEW_LINE); } for (final Expression tmpExpression : myExpressions.values()) { // if ((tmpExpression.isConstraint() && !tmpExpression.isRedundant()) || tmpExpression.isObjective()) { tmpExpression.appendToString(retVal, this.getVariableValues()); retVal.append(NEW_LINE); // } } return retVal.append(START_END).toString(); } /** * This methods validtes model construction only. All the other validate(...) method validates the * solution (one way or another). * * @see org.ojalgo.optimisation.Optimisation.Model#validate() */ public boolean validate() { final Printer appender = options.logger_detailed ? options.logger_appender : BasicLogger.NULL; boolean retVal = true; for (final Variable tmpVariable : myVariables) { retVal &= tmpVariable.validate(appender); } for (final Expression tmpExpression : myExpressions.values()) { retVal &= tmpExpression.validate(appender); } return retVal; } public boolean validate(final Access1D<BigDecimal> solution) { final NumberContext context = options.feasibility; final Printer appender = (options.logger_detailed && (options.logger_appender != null)) ? options.logger_appender : BasicLogger.NULL; return this.validate(solution, context, appender); } public boolean validate(final Access1D<BigDecimal> solution, final NumberContext context) { final Printer appender = (options.logger_detailed && (options.logger_appender != null)) ? options.logger_appender : BasicLogger.NULL; return this.validate(solution, context, appender); } public boolean validate(final Access1D<BigDecimal> solution, final NumberContext context, final Printer appender) { ProgrammingError.throwIfNull(solution, context, appender); final int size = myVariables.size(); boolean retVal = size == solution.count(); for (int i = 0; retVal && (i < size); i++) { final Variable tmpVariable = myVariables.get(i); final BigDecimal value = solution.get(i); retVal &= tmpVariable.validate(value, context, appender, myRelaxed); } if (retVal) { for (final Expression tmpExpression : myExpressions.values()) { final BigDecimal value = tmpExpression.evaluate(solution); retVal &= tmpExpression.validate(value, context, appender); } } return retVal; } public boolean validate(final Access1D<BigDecimal> solution, final Printer appender) { final NumberContext context = options.feasibility; return this.validate(solution, context, appender); } public boolean validate(final NumberContext context) { final Result solution = this.getVariableValues(context); final Printer appender = (options.logger_detailed && (options.logger_appender != null)) ? options.logger_appender : BasicLogger.NULL; return this.validate(solution, context, appender); } public boolean validate(final NumberContext context, final Printer appender) { final Access1D<BigDecimal> solution = this.getVariableValues(context); return this.validate(solution, context, appender); } public boolean validate(final Printer appender) { final NumberContext context = options.feasibility; final Result solution = this.getVariableValues(context); return this.validate(solution, context, appender); } /** * @return A stream of variables that are not fixed */ public Stream<Variable> variables() { return myVariables.stream().filter((final Variable v) -> (!v.isEqualityConstraint())); } private void categoriseVariables() { final int tmpLength = myVariables.size(); myFreeVariables.clear(); myFreeIndices = new int[tmpLength]; Arrays.fill(myFreeIndices, -1); myPositiveVariables.clear(); myPositiveIndices = new int[tmpLength]; Arrays.fill(myPositiveIndices, -1); myNegativeVariables.clear(); myNegativeIndices = new int[tmpLength]; Arrays.fill(myNegativeIndices, -1); myIntegerVariables.clear(); myIntegerIndices = new int[tmpLength]; Arrays.fill(myIntegerIndices, -1); for (int i = 0; i < tmpLength; i++) { final Variable tmpVariable = myVariables.get(i); if (!tmpVariable.isFixed()) { myFreeVariables.add(tmpVariable); myFreeIndices[i] = myFreeVariables.size() - 1; if (!tmpVariable.isUpperLimitSet() || (tmpVariable.getUpperLimit().signum() == 1)) { myPositiveVariables.add(tmpVariable); myPositiveIndices[i] = myPositiveVariables.size() - 1; } if (!tmpVariable.isLowerLimitSet() || (tmpVariable.getLowerLimit().signum() == -1)) { myNegativeVariables.add(tmpVariable); myNegativeIndices[i] = myNegativeVariables.size() - 1; } if (tmpVariable.isInteger()) { myIntegerVariables.add(tmpVariable); myIntegerIndices[i] = myIntegerVariables.size() - 1; } } } } private void scanEntities() { boolean anyVarInt = this.isAnyVariableInteger(); for (final Expression tmpExpr : myExpressions.values()) { Set<IntIndex> allVars = tmpExpr.getLinearKeySet(); BigDecimal lower = tmpExpr.getLowerLimit(); BigDecimal upper = tmpExpr.getUpperLimit(); if (tmpExpr.isObjective()) { Presolvers.LINEAR_OBJECTIVE.simplify(tmpExpr, allVars, lower, upper, options.feasibility); } if (tmpExpr.isConstraint()) { Presolvers.ZERO_ONE_TWO.simplify(tmpExpr, allVars, lower, upper, options.feasibility); if (anyVarInt) { Presolvers.INTEGER_EXPRESSION_ROUNDING.simplify(tmpExpr, allVars, lower, upper, options.feasibility); } } } for (final Variable tmpVar : myVariables) { Presolvers.UNREFERENCED.simplify(tmpVar, this); if (tmpVar.isConstraint()) { if (anyVarInt) { Presolvers.INTEGER_VARIABLE_ROUNDING.simplify(tmpVar, this); } } } } void addReference(final IntIndex index) { myReferences.add(index); } Stream<Expression> expressions() { return myExpressions.values().stream(); } ExpressionsBasedModel.Integration<?> getIntegration() { ExpressionsBasedModel.Integration<?> retVal = null; for (final ExpressionsBasedModel.Integration<?> preferred : PREFERRED_INTEGRATIONS) { if (preferred.isCapable(this)) { retVal = preferred; break; } } if (retVal == null) { if (this.isAnyVariableInteger()) { if (INTEGER_INTEGRATION.isCapable(this)) { retVal = INTEGER_INTEGRATION; } } else { if (CONVEX_INTEGRATION.isCapable(this)) { retVal = CONVEX_INTEGRATION; } else if (LINEAR_INTEGRATION.isCapable(this)) { retVal = LINEAR_INTEGRATION; } } } if (retVal == null) { for (final ExpressionsBasedModel.Integration<?> fallback : FALLBACK_INTEGRATIONS) { if (fallback.isCapable(this)) { retVal = fallback; break; } } } if (retVal == null) { throw new ProgrammingError("No solver integration available that can handle this model!"); } return retVal; } boolean isFixed() { return myVariables.stream().allMatch(v -> v.isFixed()); } boolean isInfeasible() { if (myInfeasible) { return true; } for (final Expression tmpExpression : myExpressions.values()) { if (tmpExpression.isInfeasible()) { return myInfeasible = true; } } for (final Variable tmpVariable : myVariables) { if (tmpVariable.isInfeasible()) { return myInfeasible = true; } } return false; } boolean isReferenced(final Variable variable) { return myReferences.contains(variable.getIndex()); } boolean isUnbounded() { return myVariables.stream().anyMatch(v -> v.isUnbounded()); } Optimisation.Result optimise() { if (!myWorkCopy && (PRESOLVERS.size() > 0)) { this.scanEntities(); } Intermediate prepared = this.prepare(); Optimisation.Result result = prepared.solve(null); for (int i = 0, limit = myVariables.size(); i < limit; i++) { final Variable tmpVariable = myVariables.get(i); if (!tmpVariable.isFixed()) { tmpVariable.setValue(options.solution.toBigDecimal(result.doubleValue(i))); } } Result retSolution = this.getVariableValues(); double retValue = this.objective().evaluate(retSolution).doubleValue(); Optimisation.State retState = result.getState(); return new Optimisation.Result(retState, retValue, retSolution); } void presolve() { // myExpressions.values().forEach(expr -> expr.reset()); boolean needToRepeat = false; do { final Set<IntIndex> fixedVariables = this.getFixedVariables(); BigDecimal compensatedLowerLimit; BigDecimal compensatedUpperLimit; needToRepeat = false; for (final Expression expr : this.getExpressions()) { if (!needToRepeat && expr.isConstraint() && !expr.isInfeasible() && !expr.isRedundant() && (expr.countQuadraticFactors() == 0)) { BigDecimal calculateSetValue = expr.calculateSetValue(fixedVariables); compensatedLowerLimit = expr.getCompensatedLowerLimit(calculateSetValue); compensatedUpperLimit = expr.getCompensatedUpperLimit(calculateSetValue); myTemporary.clear(); myTemporary.addAll(expr.getLinearKeySet()); myTemporary.removeAll(fixedVariables); for (final Presolver presolver : PRESOLVERS) { if (!needToRepeat) { needToRepeat |= presolver.simplify(expr, myTemporary, compensatedLowerLimit, compensatedUpperLimit, options.feasibility); } } } } } while (needToRepeat); this.categoriseVariables(); } void setInfeasible() { myInfeasible = true; } }
Update ExpressionsBasedModel.java
src/org/ojalgo/optimisation/ExpressionsBasedModel.java
Update ExpressionsBasedModel.java
Java
mit
b8d49a884ed545176bb491b10b59dde9f481ea95
0
rzwitserloot/lombok,rzwitserloot/lombok,rzwitserloot/lombok,rzwitserloot/lombok,rzwitserloot/lombok
/* * Copyright (C) 2015-2020 The Project Lombok Authors. * * 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 lombok.javac.handlers; import static lombok.javac.Javac.*; import static lombok.javac.handlers.JavacHandlerUtil.*; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; import com.sun.source.tree.Tree.Kind; import com.sun.tools.javac.code.BoundKind; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCModifiers; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.JCTree.JCTypeParameter; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.tree.JCTree.JCWildcard; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Name; import lombok.AccessLevel; import lombok.ConfigurationKeys; import lombok.core.LombokImmutableList; import lombok.core.SpiLoadUtil; import lombok.core.TypeLibrary; import lombok.core.configuration.CheckerFrameworkVersion; import lombok.core.handlers.HandlerUtil; import lombok.javac.JavacNode; import lombok.javac.JavacTreeMaker; import lombok.javac.handlers.HandleBuilder.BuilderJob; public class JavacSingularsRecipes { public interface ExpressionMaker { JCExpression make(); } public interface StatementMaker { JCStatement make(); } private static final JavacSingularsRecipes INSTANCE = new JavacSingularsRecipes(); private final Map<String, JavacSingularizer> singularizers = new HashMap<String, JavacSingularizer>(); private final TypeLibrary singularizableTypes = new TypeLibrary(); private JavacSingularsRecipes() { try { loadAll(singularizableTypes, singularizers); singularizableTypes.lock(); } catch (IOException e) { System.err.println("Lombok's @Singularizable feature is broken due to misconfigured SPI files: " + e); } } private static void loadAll(TypeLibrary library, Map<String, JavacSingularizer> map) throws IOException { for (JavacSingularizer handler : SpiLoadUtil.findServices(JavacSingularizer.class, JavacSingularizer.class.getClassLoader())) { for (String type : handler.getSupportedTypes()) { JavacSingularizer existingSingularizer = map.get(type); if (existingSingularizer != null) { JavacSingularizer toKeep = existingSingularizer.getClass().getName().compareTo(handler.getClass().getName()) > 0 ? handler : existingSingularizer; System.err.println("Multiple singularizers found for type " + type + "; the alphabetically first class is used: " + toKeep.getClass().getName()); map.put(type, toKeep); } else { map.put(type, handler); library.addType(type); } } } } public static JavacSingularsRecipes get() { return INSTANCE; } public String toQualified(String typeReference) { java.util.List<String> q = singularizableTypes.toQualifieds(typeReference); if (q.isEmpty()) return null; return q.get(0); } public JavacSingularizer getSingularizer(String fqn, JavacNode node) { final JavacSingularizer singularizer = singularizers.get(fqn); final boolean useGuavaInstead = Boolean.TRUE.equals(node.getAst().readConfiguration(ConfigurationKeys.SINGULAR_USE_GUAVA)); return useGuavaInstead ? singularizer.getGuavaInstead(node) : singularizer; } public static final class SingularData { private final JavacNode annotation; private final Name singularName; private final Name pluralName; private final List<JCExpression> typeArgs; private final String targetFqn; private final JavacSingularizer singularizer; private final String setterPrefix; private final boolean ignoreNullCollections; public SingularData(JavacNode annotation, Name singularName, Name pluralName, List<JCExpression> typeArgs, String targetFqn, JavacSingularizer singularizer, boolean ignoreNullCollections) { this(annotation, singularName, pluralName, typeArgs, targetFqn, singularizer, ignoreNullCollections, ""); } public SingularData(JavacNode annotation, Name singularName, Name pluralName, List<JCExpression> typeArgs, String targetFqn, JavacSingularizer singularizer, boolean ignoreNullCollections, String setterPrefix) { this.annotation = annotation; this.singularName = singularName; this.pluralName = pluralName; this.typeArgs = typeArgs; this.targetFqn = targetFqn; this.singularizer = singularizer; this.setterPrefix = setterPrefix; this.ignoreNullCollections = ignoreNullCollections; } public JavacNode getAnnotation() { return annotation; } public Name getSingularName() { return singularName; } public Name getPluralName() { return pluralName; } public String getSetterPrefix() { return setterPrefix; } public List<JCExpression> getTypeArgs() { return typeArgs; } public String getTargetFqn() { return targetFqn; } public JavacSingularizer getSingularizer() { return singularizer; } public boolean isIgnoreNullCollections() { return ignoreNullCollections; } public String getTargetSimpleType() { int idx = targetFqn.lastIndexOf("."); return idx == -1 ? targetFqn : targetFqn.substring(idx + 1); } } public static abstract class JavacSingularizer { public abstract LombokImmutableList<String> getSupportedTypes(); protected JavacSingularizer getGuavaInstead(JavacNode node) { return this; } protected JCModifiers makeMods(JavacTreeMaker maker, CheckerFrameworkVersion cfv, JavacNode node, boolean deprecate, AccessLevel access, List<JCAnnotation> methodAnnotations) { JCAnnotation deprecateAnn = deprecate ? maker.Annotation(genJavaLangTypeRef(node, "Deprecated"), List.<JCExpression>nil()) : null; JCAnnotation rrAnn = cfv.generateReturnsReceiver() ? maker.Annotation(genTypeRef(node, CheckerFrameworkVersion.NAME__RETURNS_RECEIVER), List.<JCExpression>nil()) : null; List<JCAnnotation> annsOnMethod = (deprecateAnn != null && rrAnn != null) ? List.of(deprecateAnn, rrAnn) : deprecateAnn != null ? List.of(deprecateAnn) : rrAnn != null ? List.of(rrAnn) : List.<JCAnnotation>nil(); annsOnMethod = mergeAnnotations(annsOnMethod,methodAnnotations); return maker.Modifiers(toJavacModifier(access), annsOnMethod); } /** Checks if any of the to-be-generated nodes (fields, methods) already exist. If so, errors on these (singulars don't support manually writing some of it, and returns true). */ public boolean checkForAlreadyExistingNodesAndGenerateError(JavacNode builderType, SingularData data) { for (JavacNode child : builderType.down()) { switch (child.getKind()) { case FIELD: { JCVariableDecl field = (JCVariableDecl) child.get(); Name name = field.name; if (name == null) break; if (getGeneratedBy(field) != null) continue; for (Name fieldToBeGenerated : listFieldsToBeGenerated(data, builderType)) { if (!fieldToBeGenerated.equals(name)) continue; child.addError("Manually adding a field that @Singular @Builder would generate is not supported. If you want to manually manage the builder aspect for this field/parameter, don't use @Singular."); return true; } break; } case METHOD: { JCMethodDecl method = (JCMethodDecl) child.get(); Name name = method.name; if (name == null) break; if (getGeneratedBy(method) != null) continue; for (Name methodToBeGenerated : listMethodsToBeGenerated(data, builderType)) { if (!methodToBeGenerated.equals(name)) continue; child.addError("Manually adding a method that @Singular @Builder would generate is not supported. If you want to manually manage the builder aspect for this field/parameter, don't use @Singular."); return true; } break; }} } return false; } public java.util.List<Name> listFieldsToBeGenerated(SingularData data, JavacNode builderType) { return Collections.singletonList(data.pluralName); } public java.util.List<Name> listMethodsToBeGenerated(SingularData data, JavacNode builderType) { Name p = data.pluralName; Name s = data.singularName; if (p.equals(s)) return Collections.singletonList(p); return Arrays.asList(p, s); } public abstract java.util.List<JavacNode> generateFields(SingularData data, JavacNode builderType, JCTree source); /** * Generates the singular, plural, and clear methods for the given {@link SingularData}. * Uses the given {@code builderType} as return type if {@code chain == true}, {@code void} otherwise. * If you need more control over the return type and value, use * {@link #generateMethods(SingularData, boolean, JavacNode, JCTree, boolean, ExpressionMaker, StatementMaker)}. */ public void generateMethods(final BuilderJob job, SingularData data, boolean deprecate) { //job.checkerFramework, job.builderType, job.source, job.oldFluent, job.oldChain, job.accessInners //CheckerFrameworkVersion cfv, final JavacNode builderType, JCTree source, boolean fluent, final boolean chain, AccessLevel access) { final JavacTreeMaker maker = job.builderType.getTreeMaker(); ExpressionMaker returnTypeMaker = new ExpressionMaker() { @Override public JCExpression make() { return job.oldChain ? cloneSelfType(job.builderType) : maker.Type(createVoidType(job.builderType.getSymbolTable(), CTC_VOID)); }}; StatementMaker returnStatementMaker = new StatementMaker() { @Override public JCStatement make() { return job.oldChain ? maker.Return(maker.Ident(job.builderType.toName("this"))) : null; }}; generateMethods(job.checkerFramework, data, deprecate, job.builderType, job.source, job.oldFluent, returnTypeMaker, returnStatementMaker, job.accessInners); } /** * Generates the singular, plural, and clear methods for the given {@link SingularData}. * Uses the given {@code returnTypeMaker} and {@code returnStatementMaker} for the generated methods. */ public abstract void generateMethods(CheckerFrameworkVersion cfv, SingularData data, boolean deprecate, JavacNode builderType, JCTree source, boolean fluent, ExpressionMaker returnTypeMaker, StatementMaker returnStatementMaker, AccessLevel access); protected void doGenerateMethods(CheckerFrameworkVersion cfv, SingularData data, boolean deprecate, JavacNode builderType, JCTree source, boolean fluent, ExpressionMaker returnTypeMaker, StatementMaker returnStatementMaker, AccessLevel access) { JavacTreeMaker maker = builderType.getTreeMaker(); generateSingularMethod(cfv, deprecate, maker, returnTypeMaker.make(), returnStatementMaker.make(), data, builderType, source, fluent, access); generatePluralMethod(cfv, deprecate, maker, returnTypeMaker.make(), returnStatementMaker.make(), data, builderType, source, fluent, access); generateClearMethod(cfv, deprecate, maker, returnTypeMaker.make(), returnStatementMaker.make(), data, builderType, source, access); } private void finishAndInjectMethod(CheckerFrameworkVersion cfv, JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean deprecate, ListBuffer<JCStatement> statements, Name methodName, List<JCVariableDecl> jcVariableDecls, List<JCAnnotation> methodAnnotations, AccessLevel access, Boolean ignoreNullCollections) { if (returnStatement != null) statements.append(returnStatement); JCBlock body = maker.Block(0, statements.toList()); JCModifiers mods = makeMods(maker, cfv, builderType, deprecate, access, methodAnnotations); List<JCTypeParameter> typeParams = List.nil(); List<JCExpression> thrown = List.nil(); if (ignoreNullCollections != null) { if (ignoreNullCollections.booleanValue()) { for (JCVariableDecl d : jcVariableDecls) createRelevantNullableAnnotation(builderType, d); } else { for (JCVariableDecl d : jcVariableDecls) createRelevantNonNullAnnotation(builderType, d); } } JCMethodDecl method = maker.MethodDef(mods, methodName, returnType, typeParams, jcVariableDecls, thrown, body, null); recursiveSetGeneratedBy(method, source, builderType.getContext()); if (returnStatement != null) createRelevantNonNullAnnotation(builderType, method); injectMethod(builderType, method); } private void generateClearMethod(CheckerFrameworkVersion cfv, boolean deprecate, JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, AccessLevel access) { JCStatement clearStatement = generateClearStatements(maker, data, builderType); ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>(); statements.add(clearStatement); Name methodName = builderType.toName(HandlerUtil.buildAccessorName("clear", data.getPluralName().toString())); finishAndInjectMethod(cfv, maker, returnType, returnStatement, data, builderType, source, deprecate, statements, methodName, List.<JCVariableDecl>nil(), List.<JCAnnotation>nil(), access, null); } protected abstract JCStatement generateClearStatements(JavacTreeMaker maker, SingularData data, JavacNode builderType); private void generateSingularMethod(CheckerFrameworkVersion cfv, boolean deprecate, JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent, AccessLevel access) { ListBuffer<JCStatement> statements = generateSingularMethodStatements(maker, data, builderType, source); List<JCVariableDecl> params = generateSingularMethodParameters(maker, data, builderType, source); Name name = data.getSingularName(); String setterPrefix = data.getSetterPrefix(); if (setterPrefix.isEmpty() && !fluent) setterPrefix = getAddMethodName(); if (!setterPrefix.isEmpty()) name = builderType.toName(HandlerUtil.buildAccessorName(setterPrefix, name.toString())); statements.prepend(createConstructBuilderVarIfNeeded(maker, data, builderType, source)); List<JCAnnotation> methodAnnotations = copyAnnotations(findCopyableToBuilderSingularSetterAnnotations(data.annotation.up())); finishAndInjectMethod(cfv, maker, returnType, returnStatement, data, builderType, source, deprecate, statements, name, params, methodAnnotations, access, null); } protected JCVariableDecl generateSingularMethodParameter(int typeIndex, JavacTreeMaker maker, SingularData data, JavacNode builderType, JCTree source, Name name) { long flags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext()); JCExpression type = cloneParamType(typeIndex, maker, data.getTypeArgs(), builderType, source); List<JCAnnotation> typeUseAnns = getTypeUseAnnotations(type); type = removeTypeUseAnnotations(type); JCModifiers mods = typeUseAnns.isEmpty() ? maker.Modifiers(flags) : maker.Modifiers(flags, typeUseAnns); return maker.VarDef(mods, name, type, null); } protected JCStatement generateSingularMethodAddStatement(JavacTreeMaker maker, JavacNode builderType, Name argumentName, String builderFieldName) { JCExpression thisDotFieldDotAdd = chainDots(builderType, "this", builderFieldName, "add"); JCExpression invokeAdd = maker.Apply(List.<JCExpression>nil(), thisDotFieldDotAdd, List.<JCExpression>of(maker.Ident(argumentName))); return maker.Exec(invokeAdd); } protected abstract ListBuffer<JCStatement> generateSingularMethodStatements(JavacTreeMaker maker, SingularData data, JavacNode builderType, JCTree source); protected abstract List<JCVariableDecl> generateSingularMethodParameters(JavacTreeMaker maker, SingularData data, JavacNode builderType, JCTree source); private void generatePluralMethod(CheckerFrameworkVersion cfv, boolean deprecate, JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent, AccessLevel access) { ListBuffer<JCStatement> statements = generatePluralMethodStatements(maker, data, builderType, source); Name name = data.getPluralName(); String setterPrefix = data.getSetterPrefix(); if (setterPrefix.isEmpty() && !fluent) setterPrefix = getAddMethodName() + "All"; if (!setterPrefix.isEmpty()) name = builderType.toName(HandlerUtil.buildAccessorName(setterPrefix, name.toString())); JCExpression paramType = getPluralMethodParamType(builderType); paramType = addTypeArgs(getTypeArgumentsCount(), true, builderType, paramType, data.getTypeArgs(), source); long paramFlags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext()); boolean ignoreNullCollections = data.isIgnoreNullCollections(); JCModifiers paramMods = maker.Modifiers(paramFlags); JCVariableDecl param = maker.VarDef(paramMods, data.getPluralName(), paramType, null); statements.prepend(createConstructBuilderVarIfNeeded(maker, data, builderType, source)); if (ignoreNullCollections) { JCExpression incomingIsNotNull = maker.Binary(CTC_NOT_EQUAL, maker.Ident(data.getPluralName()), maker.Literal(CTC_BOT, null)); JCStatement onNotNull = maker.Block(0, statements.toList()); statements = new ListBuffer<JCStatement>(); statements.add(maker.If(incomingIsNotNull, onNotNull, null)); } else { statements.prepend(JavacHandlerUtil.generateNullCheck(maker, null, data.getPluralName(), builderType, "%s cannot be null")); } List<JCAnnotation> methodAnnotations = copyAnnotations(findCopyableToSetterAnnotations(data.annotation.up())); finishAndInjectMethod(cfv, maker, returnType, returnStatement, data, builderType, source, deprecate, statements, name, List.of(param), methodAnnotations, access, ignoreNullCollections); } protected ListBuffer<JCStatement> generatePluralMethodStatements(JavacTreeMaker maker, SingularData data, JavacNode builderType, JCTree source) { ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>(); JCExpression thisDotFieldDotAdd = chainDots(builderType, "this", data.getPluralName().toString(), getAddMethodName() + "All"); JCExpression invokeAdd = maker.Apply(List.<JCExpression>nil(), thisDotFieldDotAdd, List.<JCExpression>of(maker.Ident(data.getPluralName()))); statements.append(maker.Exec(invokeAdd)); return statements; } protected abstract JCExpression getPluralMethodParamType(JavacNode builderType); protected abstract JCStatement createConstructBuilderVarIfNeeded(JavacTreeMaker maker, SingularData data, JavacNode builderType, JCTree source); public abstract void appendBuildCode(SingularData data, JavacNode builderType, JCTree source, ListBuffer<JCStatement> statements, Name targetVariableName, String builderVariable); public boolean shadowedDuringBuild() { return true; } public boolean requiresCleaning() { try { return !getClass().getMethod("appendCleaningCode", SingularData.class, JavacNode.class, JCTree.class, ListBuffer.class).getDeclaringClass().equals(JavacSingularizer.class); } catch (NoSuchMethodException e) { return false; } } public void appendCleaningCode(SingularData data, JavacNode builderType, JCTree source, ListBuffer<JCStatement> statements) { } // -- Utility methods -- /** * Adds the requested number of type arguments to the provided type, copying each argument in {@code typeArgs}. If typeArgs is too long, the extra elements are ignored. * If {@code typeArgs} is null or too short, {@code java.lang.Object} will be substituted for each missing type argument. * * @param count The number of type arguments requested. * @param addExtends If {@code true}, all bounds are either '? extends X' or just '?'. If false, the reverse is applied, and '? extends Foo' is converted to Foo, '?' to Object, etc. * @param node Some node in the same AST. Just used to obtain makers and contexts and such. * @param type The type to add generics to. * @param typeArgs the list of type args to clone. * @param source The source annotation that is the root cause of this code generation. */ protected JCExpression addTypeArgs(int count, boolean addExtends, JavacNode node, JCExpression type, List<JCExpression> typeArgs, JCTree source) { JavacTreeMaker maker = node.getTreeMaker(); List<JCExpression> clonedAndFixedTypeArgs = createTypeArgs(count, addExtends, node, typeArgs, source); return maker.TypeApply(type, clonedAndFixedTypeArgs); } protected List<JCExpression> createTypeArgs(int count, boolean addExtends, JavacNode node, List<JCExpression> typeArgs, JCTree source) { JavacTreeMaker maker = node.getTreeMaker(); Context context = node.getContext(); if (count < 0) throw new IllegalArgumentException("count is negative"); if (count == 0) return List.nil(); ListBuffer<JCExpression> arguments = new ListBuffer<JCExpression>(); if (typeArgs != null) for (JCExpression orig : typeArgs) { if (!addExtends) { if (orig.getKind() == Kind.UNBOUNDED_WILDCARD || orig.getKind() == Kind.SUPER_WILDCARD) { arguments.append(genJavaLangTypeRef(node, "Object")); } else if (orig.getKind() == Kind.EXTENDS_WILDCARD) { JCExpression inner; try { inner = (JCExpression) ((JCWildcard) orig).inner; } catch (Exception e) { inner = genJavaLangTypeRef(node, "Object"); } arguments.append(cloneType(maker, inner, source, context)); } else { arguments.append(cloneType(maker, orig, source, context)); } } else { if (orig.getKind() == Kind.UNBOUNDED_WILDCARD || orig.getKind() == Kind.SUPER_WILDCARD) { arguments.append(maker.Wildcard(maker.TypeBoundKind(BoundKind.UNBOUND), null)); } else if (orig.getKind() == Kind.EXTENDS_WILDCARD) { arguments.append(cloneType(maker, orig, source, context)); } else { arguments.append(maker.Wildcard(maker.TypeBoundKind(BoundKind.EXTENDS), cloneType(maker, orig, source, context))); } } if (--count == 0) break; } while (count-- > 0) { if (addExtends) { arguments.append(maker.Wildcard(maker.TypeBoundKind(BoundKind.UNBOUND), null)); } else { arguments.append(genJavaLangTypeRef(node, "Object")); } } return arguments.toList(); } /** Generates '<em>builderVariable</em>.<em>name</em>.size()' as an expression; if nullGuard is true, it's this.name == null ? 0 : this.name.size(). */ protected JCExpression getSize(JavacTreeMaker maker, JavacNode builderType, Name name, boolean nullGuard, boolean parens, String builderVariable) { Name thisName = builderType.toName(builderVariable); JCExpression fn = maker.Select(maker.Select(maker.Ident(thisName), name), builderType.toName("size")); JCExpression sizeInvoke = maker.Apply(List.<JCExpression>nil(), fn, List.<JCExpression>nil()); if (nullGuard) { JCExpression isNull = maker.Binary(CTC_EQUAL, maker.Select(maker.Ident(thisName), name), maker.Literal(CTC_BOT, null)); JCExpression out = maker.Conditional(isNull, maker.Literal(CTC_INT, 0), sizeInvoke); if (parens) return maker.Parens(out); return out; } return sizeInvoke; } protected JCExpression cloneParamType(int index, JavacTreeMaker maker, List<JCExpression> typeArgs, JavacNode builderType, JCTree source) { if (typeArgs == null || typeArgs.size() <= index) { return genJavaLangTypeRef(builderType, "Object"); } else { JCExpression originalType = typeArgs.get(index); if (originalType.getKind() == Kind.UNBOUNDED_WILDCARD || originalType.getKind() == Kind.SUPER_WILDCARD) { return genJavaLangTypeRef(builderType, "Object"); } else if (originalType.getKind() == Kind.EXTENDS_WILDCARD) { try { return cloneType(maker, (JCExpression) ((JCWildcard) originalType).inner, source, builderType.getContext()); } catch (Exception e) { return genJavaLangTypeRef(builderType, "Object"); } } else { return cloneType(maker, originalType, source, builderType.getContext()); } } } protected abstract String getAddMethodName(); protected abstract int getTypeArgumentsCount(); protected abstract String getEmptyMaker(String target); } }
src/core/lombok/javac/handlers/JavacSingularsRecipes.java
/* * Copyright (C) 2015-2020 The Project Lombok Authors. * * 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 lombok.javac.handlers; import static lombok.javac.Javac.*; import static lombok.javac.handlers.JavacHandlerUtil.*; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; import com.sun.source.tree.Tree.Kind; import com.sun.tools.javac.code.BoundKind; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCModifiers; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.JCTree.JCTypeParameter; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.tree.JCTree.JCWildcard; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Name; import lombok.AccessLevel; import lombok.ConfigurationKeys; import lombok.core.LombokImmutableList; import lombok.core.SpiLoadUtil; import lombok.core.TypeLibrary; import lombok.core.configuration.CheckerFrameworkVersion; import lombok.core.handlers.HandlerUtil; import lombok.javac.JavacNode; import lombok.javac.JavacTreeMaker; import lombok.javac.handlers.HandleBuilder.BuilderJob; public class JavacSingularsRecipes { public interface ExpressionMaker { JCExpression make(); } public interface StatementMaker { JCStatement make(); } private static final JavacSingularsRecipes INSTANCE = new JavacSingularsRecipes(); private final Map<String, JavacSingularizer> singularizers = new HashMap<String, JavacSingularizer>(); private final TypeLibrary singularizableTypes = new TypeLibrary(); private JavacSingularsRecipes() { try { loadAll(singularizableTypes, singularizers); singularizableTypes.lock(); } catch (IOException e) { System.err.println("Lombok's @Singularizable feature is broken due to misconfigured SPI files: " + e); } } private static void loadAll(TypeLibrary library, Map<String, JavacSingularizer> map) throws IOException { for (JavacSingularizer handler : SpiLoadUtil.findServices(JavacSingularizer.class, JavacSingularizer.class.getClassLoader())) { for (String type : handler.getSupportedTypes()) { JavacSingularizer existingSingularizer = map.get(type); if (existingSingularizer != null) { JavacSingularizer toKeep = existingSingularizer.getClass().getName().compareTo(handler.getClass().getName()) > 0 ? handler : existingSingularizer; System.err.println("Multiple singularizers found for type " + type + "; the alphabetically first class is used: " + toKeep.getClass().getName()); map.put(type, toKeep); } else { map.put(type, handler); library.addType(type); } } } } public static JavacSingularsRecipes get() { return INSTANCE; } public String toQualified(String typeReference) { java.util.List<String> q = singularizableTypes.toQualifieds(typeReference); if (q.isEmpty()) return null; return q.get(0); } public JavacSingularizer getSingularizer(String fqn, JavacNode node) { final JavacSingularizer singularizer = singularizers.get(fqn); final boolean useGuavaInstead = Boolean.TRUE.equals(node.getAst().readConfiguration(ConfigurationKeys.SINGULAR_USE_GUAVA)); return useGuavaInstead ? singularizer.getGuavaInstead(node) : singularizer; } public static final class SingularData { private final JavacNode annotation; private final Name singularName; private final Name pluralName; private final List<JCExpression> typeArgs; private final String targetFqn; private final JavacSingularizer singularizer; private final String setterPrefix; private final boolean ignoreNullCollections; public SingularData(JavacNode annotation, Name singularName, Name pluralName, List<JCExpression> typeArgs, String targetFqn, JavacSingularizer singularizer, boolean ignoreNullCollections) { this(annotation, singularName, pluralName, typeArgs, targetFqn, singularizer, ignoreNullCollections, ""); } public SingularData(JavacNode annotation, Name singularName, Name pluralName, List<JCExpression> typeArgs, String targetFqn, JavacSingularizer singularizer, boolean ignoreNullCollections, String setterPrefix) { this.annotation = annotation; this.singularName = singularName; this.pluralName = pluralName; this.typeArgs = typeArgs; this.targetFqn = targetFqn; this.singularizer = singularizer; this.setterPrefix = setterPrefix; this.ignoreNullCollections = ignoreNullCollections; } public JavacNode getAnnotation() { return annotation; } public Name getSingularName() { return singularName; } public Name getPluralName() { return pluralName; } public String getSetterPrefix() { return setterPrefix; } public List<JCExpression> getTypeArgs() { return typeArgs; } public String getTargetFqn() { return targetFqn; } public JavacSingularizer getSingularizer() { return singularizer; } public boolean isIgnoreNullCollections() { return ignoreNullCollections; } public String getTargetSimpleType() { int idx = targetFqn.lastIndexOf("."); return idx == -1 ? targetFqn : targetFqn.substring(idx + 1); } } public static abstract class JavacSingularizer { public abstract LombokImmutableList<String> getSupportedTypes(); protected JavacSingularizer getGuavaInstead(JavacNode node) { return this; } protected JCModifiers makeMods(JavacTreeMaker maker, CheckerFrameworkVersion cfv, JavacNode node, boolean deprecate, AccessLevel access, List<JCAnnotation> methodAnnotations) { JCAnnotation deprecateAnn = deprecate ? maker.Annotation(genJavaLangTypeRef(node, "Deprecated"), List.<JCExpression>nil()) : null; JCAnnotation rrAnn = cfv.generateReturnsReceiver() ? maker.Annotation(genTypeRef(node, CheckerFrameworkVersion.NAME__RETURNS_RECEIVER), List.<JCExpression>nil()) : null; List<JCAnnotation> annsOnMethod = (deprecateAnn != null && rrAnn != null) ? List.of(deprecateAnn, rrAnn) : deprecateAnn != null ? List.of(deprecateAnn) : rrAnn != null ? List.of(rrAnn) : List.<JCAnnotation>nil(); annsOnMethod = mergeAnnotations(annsOnMethod,methodAnnotations); return maker.Modifiers(toJavacModifier(access), annsOnMethod); } /** Checks if any of the to-be-generated nodes (fields, methods) already exist. If so, errors on these (singulars don't support manually writing some of it, and returns true). */ public boolean checkForAlreadyExistingNodesAndGenerateError(JavacNode builderType, SingularData data) { for (JavacNode child : builderType.down()) { switch (child.getKind()) { case FIELD: { JCVariableDecl field = (JCVariableDecl) child.get(); Name name = field.name; if (name == null) break; if (getGeneratedBy(field) != null) continue; for (Name fieldToBeGenerated : listFieldsToBeGenerated(data, builderType)) { if (!fieldToBeGenerated.equals(name)) continue; child.addError("Manually adding a field that @Singular @Builder would generate is not supported. If you want to manually manage the builder aspect for this field/parameter, don't use @Singular."); return true; } break; } case METHOD: { JCMethodDecl method = (JCMethodDecl) child.get(); Name name = method.name; if (name == null) break; if (getGeneratedBy(method) != null) continue; for (Name methodToBeGenerated : listMethodsToBeGenerated(data, builderType)) { if (!methodToBeGenerated.equals(name)) continue; child.addError("Manually adding a method that @Singular @Builder would generate is not supported. If you want to manually manage the builder aspect for this field/parameter, don't use @Singular."); return true; } break; }} } return false; } public java.util.List<Name> listFieldsToBeGenerated(SingularData data, JavacNode builderType) { return Collections.singletonList(data.pluralName); } public java.util.List<Name> listMethodsToBeGenerated(SingularData data, JavacNode builderType) { Name p = data.pluralName; Name s = data.singularName; if (p.equals(s)) return Collections.singletonList(p); return Arrays.asList(p, s); } public abstract java.util.List<JavacNode> generateFields(SingularData data, JavacNode builderType, JCTree source); /** * Generates the singular, plural, and clear methods for the given {@link SingularData}. * Uses the given {@code builderType} as return type if {@code chain == true}, {@code void} otherwise. * If you need more control over the return type and value, use * {@link #generateMethods(SingularData, boolean, JavacNode, JCTree, boolean, ExpressionMaker, StatementMaker)}. */ public void generateMethods(final BuilderJob job, SingularData data, boolean deprecate) { //job.checkerFramework, job.builderType, job.source, job.oldFluent, job.oldChain, job.accessInners //CheckerFrameworkVersion cfv, final JavacNode builderType, JCTree source, boolean fluent, final boolean chain, AccessLevel access) { final JavacTreeMaker maker = job.builderType.getTreeMaker(); ExpressionMaker returnTypeMaker = new ExpressionMaker() { @Override public JCExpression make() { return job.oldChain ? cloneSelfType(job.builderType) : maker.Type(createVoidType(job.builderType.getSymbolTable(), CTC_VOID)); }}; StatementMaker returnStatementMaker = new StatementMaker() { @Override public JCStatement make() { return job.oldChain ? maker.Return(maker.Ident(job.builderType.toName("this"))) : null; }}; generateMethods(job.checkerFramework, data, deprecate, job.builderType, job.source, job.oldFluent, returnTypeMaker, returnStatementMaker, job.accessInners); } /** * Generates the singular, plural, and clear methods for the given {@link SingularData}. * Uses the given {@code returnTypeMaker} and {@code returnStatementMaker} for the generated methods. */ public abstract void generateMethods(CheckerFrameworkVersion cfv, SingularData data, boolean deprecate, JavacNode builderType, JCTree source, boolean fluent, ExpressionMaker returnTypeMaker, StatementMaker returnStatementMaker, AccessLevel access); protected void doGenerateMethods(CheckerFrameworkVersion cfv, SingularData data, boolean deprecate, JavacNode builderType, JCTree source, boolean fluent, ExpressionMaker returnTypeMaker, StatementMaker returnStatementMaker, AccessLevel access) { JavacTreeMaker maker = builderType.getTreeMaker(); generateSingularMethod(cfv, deprecate, maker, returnTypeMaker.make(), returnStatementMaker.make(), data, builderType, source, fluent, access); generatePluralMethod(cfv, deprecate, maker, returnTypeMaker.make(), returnStatementMaker.make(), data, builderType, source, fluent, access); generateClearMethod(cfv, deprecate, maker, returnTypeMaker.make(), returnStatementMaker.make(), data, builderType, source, access); } private void finishAndInjectMethod(CheckerFrameworkVersion cfv, JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean deprecate, ListBuffer<JCStatement> statements, Name methodName, List<JCVariableDecl> jcVariableDecls, List<JCAnnotation> methodAnnotations, AccessLevel access, Boolean ignoreNullCollections) { if (returnStatement != null) statements.append(returnStatement); JCBlock body = maker.Block(0, statements.toList()); JCModifiers mods = makeMods(maker, cfv, builderType, deprecate, access, methodAnnotations); List<JCTypeParameter> typeParams = List.nil(); List<JCExpression> thrown = List.nil(); if (ignoreNullCollections != null) { if (ignoreNullCollections.booleanValue()) { for (JCVariableDecl d : jcVariableDecls) createRelevantNullableAnnotation(builderType, d); } else { for (JCVariableDecl d : jcVariableDecls) createRelevantNonNullAnnotation(builderType, d); } } JCMethodDecl method = maker.MethodDef(mods, methodName, returnType, typeParams, jcVariableDecls, thrown, body, null); recursiveSetGeneratedBy(method, source, builderType.getContext()); if (returnStatement != null) createRelevantNonNullAnnotation(builderType, method); injectMethod(builderType, method); } private void generateClearMethod(CheckerFrameworkVersion cfv, boolean deprecate, JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, AccessLevel access) { JCStatement clearStatement = generateClearStatements(maker, data, builderType); ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>(); statements.add(clearStatement); Name methodName = builderType.toName(HandlerUtil.buildAccessorName("clear", data.getPluralName().toString())); finishAndInjectMethod(cfv, maker, returnType, returnStatement, data, builderType, source, deprecate, statements, methodName, List.<JCVariableDecl>nil(), List.<JCAnnotation>nil(), access, null); } protected abstract JCStatement generateClearStatements(JavacTreeMaker maker, SingularData data, JavacNode builderType); private void generateSingularMethod(CheckerFrameworkVersion cfv, boolean deprecate, JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent, AccessLevel access) { ListBuffer<JCStatement> statements = generateSingularMethodStatements(maker, data, builderType, source); List<JCVariableDecl> params = generateSingularMethodParameters(maker, data, builderType, source); Name name = data.getSingularName(); String setterPrefix = data.getSetterPrefix(); if (setterPrefix.isEmpty() && !fluent) setterPrefix = getAddMethodName(); if (!setterPrefix.isEmpty()) name = builderType.toName(HandlerUtil.buildAccessorName(setterPrefix, name.toString())); statements.prepend(createConstructBuilderVarIfNeeded(maker, data, builderType, source)); List<JCAnnotation> methodAnnotations = copyAnnotations(findCopyableToBuilderSingularSetterAnnotations(data.annotation.up())); finishAndInjectMethod(cfv, maker, returnType, returnStatement, data, builderType, source, deprecate, statements, name, params, methodAnnotations, access, null); } protected JCVariableDecl generateSingularMethodParameter(int typeIndex, JavacTreeMaker maker, SingularData data, JavacNode builderType, JCTree source, Name name) { long flags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext()); JCExpression type = cloneParamType(typeIndex, maker, data.getTypeArgs(), builderType, source); List<JCAnnotation> typeUseAnns = getTypeUseAnnotations(type); type = removeTypeUseAnnotations(type); JCModifiers mods = typeUseAnns.isEmpty() ? maker.Modifiers(flags) : maker.Modifiers(flags, typeUseAnns); return maker.VarDef(mods, name, type, null); } protected JCStatement generateSingularMethodAddStatement(JavacTreeMaker maker, JavacNode builderType, Name argumentName, String builderFieldName) { JCExpression thisDotFieldDotAdd = chainDots(builderType, "this", builderFieldName, "add"); JCExpression invokeAdd = maker.Apply(List.<JCExpression>nil(), thisDotFieldDotAdd, List.<JCExpression>of(maker.Ident(argumentName))); return maker.Exec(invokeAdd); } protected abstract ListBuffer<JCStatement> generateSingularMethodStatements(JavacTreeMaker maker, SingularData data, JavacNode builderType, JCTree source); protected abstract List<JCVariableDecl> generateSingularMethodParameters(JavacTreeMaker maker, SingularData data, JavacNode builderType, JCTree source); private void generatePluralMethod(CheckerFrameworkVersion cfv, boolean deprecate, JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent, AccessLevel access) { ListBuffer<JCStatement> statements = generatePluralMethodStatements(maker, data, builderType, source); Name name = data.getPluralName(); String setterPrefix = data.getSetterPrefix(); if (setterPrefix.isEmpty() && !fluent) setterPrefix = getAddMethodName() + "All"; if (!setterPrefix.isEmpty()) name = builderType.toName(HandlerUtil.buildAccessorName(setterPrefix, name.toString())); JCExpression paramType = getPluralMethodParamType(builderType); paramType = addTypeArgs(getTypeArgumentsCount(), true, builderType, paramType, data.getTypeArgs(), source); long paramFlags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext()); boolean ignoreNullCollections = data.isIgnoreNullCollections(); JCModifiers paramMods = maker.Modifiers(paramFlags); JCVariableDecl param = maker.VarDef(paramMods, data.getPluralName(), paramType, null); statements.prepend(createConstructBuilderVarIfNeeded(maker, data, builderType, source)); if (ignoreNullCollections) { JCExpression incomingIsNotNull = maker.Binary(CTC_NOT_EQUAL, maker.Ident(data.getPluralName()), maker.Literal(CTC_BOT, null)); JCStatement onNotNull = maker.Block(0, statements.toList()); statements = new ListBuffer<JCStatement>(); statements.add(maker.If(incomingIsNotNull, onNotNull, null)); } else { statements.prepend(JavacHandlerUtil.generateNullCheck(maker, null, data.getPluralName(), builderType, "%s cannot be null")); } List<JCAnnotation> methodAnnotations = copyAnnotations(findCopyableToSetterAnnotations(data.annotation.up())); finishAndInjectMethod(cfv, maker, returnType, returnStatement, data, builderType, source, deprecate, statements, name, List.of(param), methodAnnotations, access, ignoreNullCollections); } protected ListBuffer<JCStatement> generatePluralMethodStatements(JavacTreeMaker maker, SingularData data, JavacNode builderType, JCTree source) { ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>(); JCExpression thisDotFieldDotAdd = chainDots(builderType, "this", data.getPluralName().toString(), getAddMethodName() + "All"); JCExpression invokeAdd = maker.Apply(List.<JCExpression>nil(), thisDotFieldDotAdd, List.<JCExpression>of(maker.Ident(data.getPluralName()))); statements.append(maker.Exec(invokeAdd)); return statements; } protected abstract JCExpression getPluralMethodParamType(JavacNode builderType); protected abstract JCStatement createConstructBuilderVarIfNeeded(JavacTreeMaker maker, SingularData data, JavacNode builderType, JCTree source); public abstract void appendBuildCode(SingularData data, JavacNode builderType, JCTree source, ListBuffer<JCStatement> statements, Name targetVariableName, String builderVariable); public boolean shadowedDuringBuild() { return true; } public boolean requiresCleaning() { try { return !getClass().getMethod("appendCleaningCode", SingularData.class, JavacNode.class, JCTree.class, ListBuffer.class).getDeclaringClass().equals(JavacSingularizer.class); } catch (NoSuchMethodException e) { return false; } } public void appendCleaningCode(SingularData data, JavacNode builderType, JCTree source, ListBuffer<JCStatement> statements) { } // -- Utility methods -- /** * Adds the requested number of type arguments to the provided type, copying each argument in {@code typeArgs}. If typeArgs is too long, the extra elements are ignored. * If {@code typeArgs} is null or too short, {@code java.lang.Object} will be substituted for each missing type argument. * * @param count The number of type arguments requested. * @param addExtends If {@code true}, all bounds are either '? extends X' or just '?'. If false, the reverse is applied, and '? extends Foo' is converted to Foo, '?' to Object, etc. * @param node Some node in the same AST. Just used to obtain makers and contexts and such. * @param type The type to add generics to. * @param typeArgs the list of type args to clone. * @param source The source annotation that is the root cause of this code generation. */ protected JCExpression addTypeArgs(int count, boolean addExtends, JavacNode node, JCExpression type, List<JCExpression> typeArgs, JCTree source) { JavacTreeMaker maker = node.getTreeMaker(); List<JCExpression> clonedAndFixedTypeArgs = createTypeArgs(count, addExtends, node, typeArgs, source); return maker.TypeApply(type, clonedAndFixedTypeArgs); } protected List<JCExpression> createTypeArgs(int count, boolean addExtends, JavacNode node, List<JCExpression> typeArgs, JCTree source) { JavacTreeMaker maker = node.getTreeMaker(); Context context = node.getContext(); if (count < 0) throw new IllegalArgumentException("count is negative"); if (count == 0) return List.nil(); ListBuffer<JCExpression> arguments = new ListBuffer<JCExpression>(); if (typeArgs != null) for (JCExpression orig : typeArgs) { if (!addExtends) { if (orig.getKind() == Kind.UNBOUNDED_WILDCARD || orig.getKind() == Kind.SUPER_WILDCARD) { arguments.append(genJavaLangTypeRef(node, "Object")); } else if (orig.getKind() == Kind.EXTENDS_WILDCARD) { JCExpression inner; try { inner = (JCExpression) ((JCWildcard) orig).inner; } catch (Exception e) { inner = genJavaLangTypeRef(node, "Object"); } arguments.append(cloneType(maker, inner, source, context)); } else { arguments.append(cloneType(maker, orig, source, context)); } } else { if (orig.getKind() == Kind.UNBOUNDED_WILDCARD || orig.getKind() == Kind.SUPER_WILDCARD) { arguments.append(maker.Wildcard(maker.TypeBoundKind(BoundKind.UNBOUND), null)); } else if (orig.getKind() == Kind.EXTENDS_WILDCARD) { arguments.append(cloneType(maker, orig, source, context)); } else { arguments.append(maker.Wildcard(maker.TypeBoundKind(BoundKind.EXTENDS), cloneType(maker, orig, source, context))); } } if (--count == 0) break; } while (count-- > 0) { if (addExtends) { arguments.append(maker.Wildcard(maker.TypeBoundKind(BoundKind.UNBOUND), null)); } else { arguments.append(genJavaLangTypeRef(node, "Object")); } } return arguments.toList(); } /** Generates '<em>builderVariable</em>.<em>name</em>.size()' as an expression; if nullGuard is true, it's this.name == null ? 0 : this.name.size(). */ protected JCExpression getSize(JavacTreeMaker maker, JavacNode builderType, Name name, boolean nullGuard, boolean parens, String builderVariable) { Name thisName = builderType.toName(builderVariable); JCExpression fn = maker.Select(maker.Select(maker.Ident(thisName), name), builderType.toName("size")); JCExpression sizeInvoke = maker.Apply(List.<JCExpression>nil(), fn, List.<JCExpression>nil()); if (nullGuard) { JCExpression isNull = maker.Binary(CTC_EQUAL, maker.Select(maker.Ident(thisName), name), maker.Literal(CTC_BOT, 0)); JCExpression out = maker.Conditional(isNull, maker.Literal(CTC_INT, 0), sizeInvoke); if (parens) return maker.Parens(out); return out; } return sizeInvoke; } protected JCExpression cloneParamType(int index, JavacTreeMaker maker, List<JCExpression> typeArgs, JavacNode builderType, JCTree source) { if (typeArgs == null || typeArgs.size() <= index) { return genJavaLangTypeRef(builderType, "Object"); } else { JCExpression originalType = typeArgs.get(index); if (originalType.getKind() == Kind.UNBOUNDED_WILDCARD || originalType.getKind() == Kind.SUPER_WILDCARD) { return genJavaLangTypeRef(builderType, "Object"); } else if (originalType.getKind() == Kind.EXTENDS_WILDCARD) { try { return cloneType(maker, (JCExpression) ((JCWildcard) originalType).inner, source, builderType.getContext()); } catch (Exception e) { return genJavaLangTypeRef(builderType, "Object"); } } else { return cloneType(maker, originalType, source, builderType.getContext()); } } } protected abstract String getAddMethodName(); protected abstract int getTypeArgumentsCount(); protected abstract String getEmptyMaker(String target); } }
[fixes #2695] Create void literal properly
src/core/lombok/javac/handlers/JavacSingularsRecipes.java
[fixes #2695] Create void literal properly
Java
mit
560eac651e9b91ccd2448234763f3cbafaaa5f56
0
asascience-open/ncSOS
package com.asascience.ncsos.cdmclasses; import com.asascience.ncsos.getobs.SOSObservationOffering; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.joda.time.DateTime; import org.w3c.dom.Document; import ucar.nc2.ft.*; import ucar.nc2.units.DateFormatter; import ucar.unidata.geoloc.Station; /** * RPS - ASA * @author abird * @version * *handles TRAJECTORY CDM DATA TYPE * */ public class Trajectory extends baseCDMClass implements iStationData { private final ArrayList<String> eventTimes; private final String[] variableNames; private TrajectoryFeatureCollection trajectoryData; private ArrayList<TrajectoryFeature> trajList; public Trajectory(String[] stationName, String[] eventTime, String[] variableNames) { startDate = null; endDate = null; this.variableNames = variableNames; this.reqStationNames = new ArrayList<String>(); reqStationNames.addAll(Arrays.asList(stationName)); this.eventTimes = new ArrayList<String>(); eventTimes.addAll(Arrays.asList(eventTime)); upperAlt = Double.NEGATIVE_INFINITY; lowerAlt = Double.POSITIVE_INFINITY; } public void addAllTrajectoryData(PointFeatureIterator trajFeatureIterator, List<String> valueList, DateFormatter dateFormatter, StringBuilder builder) throws IOException { while (trajFeatureIterator.hasNext()) { PointFeature trajFeature = trajFeatureIterator.next(); valueList.clear(); addDataLine(valueList, dateFormatter, trajFeature, builder); } } public void addDataLine(List<String> valueList, DateFormatter dateFormatter, PointFeature trajFeature, StringBuilder builder) throws IOException { valueList.add("time=" + dateFormatter.toDateTimeStringISO(trajFeature.getObservationTimeAsDate())); for (int i = 0; i < variableNames.length; i++) { valueList.add(variableNames[i] + "=" + trajFeature.getData().getScalarObject(variableNames[i]).toString()); } for (String str : valueList) { builder.append(str).append(","); } builder.deleteCharAt(builder.length() - 1).append(";"); } @Override public void setData(Object featureCollection) throws IOException { this.trajectoryData = (TrajectoryFeatureCollection) featureCollection; trajList = new ArrayList<TrajectoryFeature>(); DateTime dtSearchStart = null; DateTime dtSearchEnd = null; boolean firstSet = true; //check first to see if the event times are not null if (eventTimes != null) { //turn event times in to dateTimes to compare if (eventTimes.size() >= 1) { dtSearchStart = new DateTime(df.getISODate(eventTimes.get(0)), chrono); } if (eventTimes.size() == 2) { dtSearchEnd = new DateTime(df.getISODate(eventTimes.get(1)), chrono); } //temp DateTime dtStart = null; DateTime dtEnd = null; //check DateTime dtStartt = null; DateTime dtEndt = null; while (trajectoryData.hasNext()) { TrajectoryFeature trajFeature = trajectoryData.next(); trajFeature.calcBounds(); String n = trajFeature.getName(); //scan through the stationname for a match of id for (Iterator<String> it = reqStationNames.iterator(); it.hasNext();) { String stName = it.next(); if (stName.equalsIgnoreCase(n)) { trajList.add(trajFeature); } } // get altitude for (trajFeature.resetIteration();trajFeature.hasNext();) { PointFeature point = trajFeature.next(); double altitude = point.getLocation().getAltitude(); if (altitude > upperAlt) upperAlt = altitude; if (altitude < lowerAlt) lowerAlt = altitude; } if (firstSet) { upperLat = trajFeature.getBoundingBox().getLatMax(); lowerLat = trajFeature.getBoundingBox().getLatMin(); upperLon = trajFeature.getBoundingBox().getLonMax(); lowerLon = trajFeature.getBoundingBox().getLonMin(); dtStart = new DateTime(trajFeature.getDateRange().getStart().getDate(), chrono); dtEnd = new DateTime(trajFeature.getDateRange().getEnd().getDate(), chrono); firstSet = false; } else { dtStartt = new DateTime(trajFeature.getDateRange().getStart().getDate(), chrono); dtEndt = new DateTime(trajFeature.getDateRange().getEnd().getDate(), chrono); if (dtStartt.isBefore(dtStart)) { dtStart = dtStartt; } if (dtEndt.isAfter(dtEnd)) { dtEnd = dtEndt; } if (trajFeature.getBoundingBox().getLatMax() > upperLat) { upperLat = trajFeature.getBoundingBox().getLatMax(); } if (trajFeature.getBoundingBox().getLatMin() < lowerLat) { lowerLat = trajFeature.getBoundingBox().getLatMin(); } //lon if (trajFeature.getBoundingBox().getLonMax() > upperLon) { upperLon = trajFeature.getBoundingBox().getLonMax(); } if (trajFeature.getBoundingBox().getLonMax() < lowerLon) { lowerLon = trajFeature.getBoundingBox().getLonMin(); } } } setStartDate(df.toDateTimeStringISO(dtStart.toDate())); setEndDate(df.toDateTimeStringISO(dtEnd.toDate())); if (reqStationNames != null) { setNumberOfStations(reqStationNames.size()); } } } @Override public void setInitialLatLonBounaries(List<Station> tsStationList) { throw new UnsupportedOperationException("Not supported yet."); } @Override public String getDataResponse(int stNum) { System.out.println("getDataResponse Trajectory"); try { if (trajectoryData != null) { return createTrajectoryFeature(stNum); } } catch (IOException ex) { Logger.getLogger(Trajectory.class.getName()).log(Level.SEVERE, null, ex); return DATA_RESPONSE_ERROR + Profile.class; } return DATA_RESPONSE_ERROR + Profile.class; } @Override public String getStationName(int idNum) { if (trajList != null) { return "TRAJECTORY_" + (trajList.get(idNum).getName()); } else { return Invalid_Station; } } @Override public double getLowerLat(int stNum) { if (trajList != null) { return (trajList.get(stNum).getBoundingBox().getLatMin()); } else { return Invalid_Value; } } @Override public double getLowerLon(int stNum) { if (trajList != null) { return (trajList.get(stNum).getBoundingBox().getLonMin()); } else { return Invalid_Value; } } @Override public double getUpperLat(int stNum) { if (trajList != null) { return (trajList.get(stNum).getBoundingBox().getLatMax()); } else { return Invalid_Value; } } @Override public double getUpperLon(int stNum) { if (trajList != null) { return (trajList.get(stNum).getBoundingBox().getLonMax()); } else { return Invalid_Value; } } @Override public double getLowerAltitude(int stNum) { try { if (trajList != null) { return trajList.get(stNum).next().getLocation().getAltitude(); } } catch (Exception e) {} finally { return Invalid_Value; } } @Override public double getUpperAltitude(int stNum) { try { if (trajList != null) { return trajList.get(stNum).next().getLocation().getAltitude(); } } catch (Exception e) {} finally { return Invalid_Value; } } @Override public String getTimeEnd(int stNum) { if (trajList != null) { return df.toDateTimeStringISO(trajList.get(stNum).getDateRange().getEnd().getDate()); } else { return ERROR_NULL_DATE; } } @Override public String getTimeBegin(int stNum) { if (trajList != null) { return df.toDateTimeStringISO(trajList.get(stNum).getDateRange().getStart().getDate()); } else { return ERROR_NULL_DATE; } } /** * gets the trajectory response for the getcaps request * @param dataset * @param document * @param featureOfInterest * @param GMLName * @param format * @param observedPropertyList * @return * @throws IOException */ public static Document getCapsResponse(FeatureCollection dataset, Document document, String featureOfInterest, String GMLName, List<String> observedPropertyList) throws IOException { //PointFeatureIterator trajIter; while (((TrajectoryFeatureCollection) dataset).hasNext()) { TrajectoryFeature tFeature = ((TrajectoryFeatureCollection) dataset).next(); tFeature.calcBounds(); //trajIter = tFeature.getPointFeatureIterator(-1); //attributes SOSObservationOffering newOffering = new SOSObservationOffering(); newOffering.setObservationStationLowerCorner(Double.toString(tFeature.getBoundingBox().getLatMin()), Double.toString(tFeature.getBoundingBox().getLonMin())); newOffering.setObservationStationUpperCorner(Double.toString(tFeature.getBoundingBox().getLatMax()), Double.toString(tFeature.getBoundingBox().getLonMax())); //check the data if (tFeature.getDateRange() != null) { newOffering.setObservationTimeBegin(tFeature.getDateRange().getStart().toDateTimeStringISO()); newOffering.setObservationTimeEnd(tFeature.getDateRange().getEnd().toDateTimeStringISO()); } //find the dates out! else { System.out.println("no dates yet"); } newOffering.setObservationStationDescription(tFeature.getCollectionFeatureType().toString()); newOffering.setObservationFeatureOfInterest(featureOfInterest + (tFeature.getName())); newOffering.setObservationName(GMLName + (tFeature.getName())); newOffering.setObservationStationID((tFeature.getName())); newOffering.setObservationProcedureLink(GMLName + ((tFeature.getName()))); newOffering.setObservationSrsName("EPSG:4326"); // TODO? newOffering.setObservationObserveredList(observedPropertyList); document = CDMUtils.addObsOfferingToDoc(newOffering, document); } return document; } @Override public String getDescription(int stNum) { throw new UnsupportedOperationException("Not supported yet."); } private String createTrajectoryFeature(int stNum) throws IOException { StringBuilder builder = new StringBuilder(); DateFormatter dateFormatter = new DateFormatter(); TrajectoryFeature trajFeature = trajList.get(stNum); addTrajectoryData(dateFormatter, builder, trajFeature, stNum); return builder.toString(); } private void addTrajectoryData(DateFormatter dateFormatter, StringBuilder builder, TrajectoryFeature traj, int stNum) throws IOException { List<String> valueList = new ArrayList<String>(); PointFeatureIterator trajFeatureIterator = traj.getPointFeatureIterator(-1); DateTime trajTime; DateTime dtStart; DateTime dtEnd; //if no times are specified if (eventTimes == null) { addAllTrajectoryData(trajFeatureIterator, valueList, dateFormatter, builder); } //if more than one date is specified else if (eventTimes.size() > 1) { //get the dates in iso format dtStart = new DateTime(df.getISODate(eventTimes.get(0)), chrono); dtEnd = new DateTime(df.getISODate(eventTimes.get(1)), chrono); while (trajFeatureIterator.hasNext()) { PointFeature trajFeature = trajFeatureIterator.next(); valueList.clear(); trajTime = new DateTime(trajFeature.getObservationTimeAsDate(), chrono); if (trajTime.isEqual(dtStart)) { addDataLine(valueList, dateFormatter, trajFeature, builder); } else if (trajTime.isEqual(dtEnd)) { addDataLine(valueList, dateFormatter, trajFeature, builder); } else if (trajTime.isAfter(dtStart) && (trajTime.isBefore(dtEnd))) { addDataLine(valueList, dateFormatter, trajFeature, builder); } } } //if start and end time were specified else if (eventTimes.size() == 1) { //get the single date in iso format dtStart = new DateTime(df.getISODate(eventTimes.get(0)), chrono); while (trajFeatureIterator.hasNext()) { PointFeature trajFeature = trajFeatureIterator.next(); valueList.clear(); trajTime = new DateTime(trajFeature.getObservationTimeAsDate(), chrono); if (trajTime.isEqual(dtStart)) { addDataLine(valueList, dateFormatter, trajFeature, builder); //if it matches return... break; } } } //times specified are weird, report all else { addAllTrajectoryData(trajFeatureIterator, valueList, dateFormatter, builder); } } }
src/main/java/com/asascience/ncsos/cdmclasses/Trajectory.java
package com.asascience.ncsos.cdmclasses; import com.asascience.ncsos.getobs.SOSObservationOffering; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.joda.time.DateTime; import org.w3c.dom.Document; import ucar.nc2.ft.*; import ucar.nc2.units.DateFormatter; import ucar.unidata.geoloc.Station; /** * RPS - ASA * @author abird * @version * *handles TRAJECTORY CDM DATA TYPE * */ public class Trajectory extends baseCDMClass implements iStationData { private final ArrayList<String> eventTimes; private final String[] variableNames; private TrajectoryFeatureCollection trajectoryData; private ArrayList<TrajectoryFeature> trajList; public Trajectory(String[] stationName, String[] eventTime, String[] variableNames) { startDate = null; endDate = null; this.variableNames = variableNames; this.reqStationNames = new ArrayList<String>(); reqStationNames.addAll(Arrays.asList(stationName)); this.eventTimes = new ArrayList<String>(); eventTimes.addAll(Arrays.asList(eventTime)); upperAlt = lowerAlt = 0; } public void addAllTrajectoryData(PointFeatureIterator trajFeatureIterator, List<String> valueList, DateFormatter dateFormatter, StringBuilder builder) throws IOException { while (trajFeatureIterator.hasNext()) { PointFeature trajFeature = trajFeatureIterator.next(); valueList.clear(); addDataLine(valueList, dateFormatter, trajFeature, builder); } } public void addDataLine(List<String> valueList, DateFormatter dateFormatter, PointFeature trajFeature, StringBuilder builder) throws IOException { valueList.add("time=" + dateFormatter.toDateTimeStringISO(trajFeature.getObservationTimeAsDate())); for (int i = 0; i < variableNames.length; i++) { valueList.add(variableNames[i] + "=" + trajFeature.getData().getScalarObject(variableNames[i]).toString()); builder.append(valueList.get(i)); if (i < variableNames.length - 1) { builder.append(","); } } builder.append(";"); } @Override public void setData(Object featureCollection) throws IOException { this.trajectoryData = (TrajectoryFeatureCollection) featureCollection; trajList = new ArrayList<TrajectoryFeature>(); DateTime dtSearchStart = null; DateTime dtSearchEnd = null; boolean firstSet = true; //check first to see if the event times are not null if (eventTimes != null) { //turn event times in to dateTimes to compare if (eventTimes.size() >= 1) { dtSearchStart = new DateTime(df.getISODate(eventTimes.get(0)), chrono); } if (eventTimes.size() == 2) { dtSearchEnd = new DateTime(df.getISODate(eventTimes.get(1)), chrono); } //temp DateTime dtStart = null; DateTime dtEnd = null; //check DateTime dtStartt = null; DateTime dtEndt = null; while (trajectoryData.hasNext()) { TrajectoryFeature trajFeature = trajectoryData.next(); trajFeature.calcBounds(); String n = trajFeature.getName(); //scan through the stationname for a match of id for (Iterator<String> it = reqStationNames.iterator(); it.hasNext();) { String stName = it.next(); if (stName.equalsIgnoreCase(n)) { trajList.add(trajFeature); } } if (firstSet) { upperLat = trajFeature.getBoundingBox().getLatMax(); lowerLat = trajFeature.getBoundingBox().getLatMin(); upperLon = trajFeature.getBoundingBox().getLonMax(); lowerLon = trajFeature.getBoundingBox().getLonMin(); dtStart = new DateTime(trajFeature.getDateRange().getStart().getDate(), chrono); dtEnd = new DateTime(trajFeature.getDateRange().getEnd().getDate(), chrono); firstSet = false; } else { dtStartt = new DateTime(trajFeature.getDateRange().getStart().getDate(), chrono); dtEndt = new DateTime(trajFeature.getDateRange().getEnd().getDate(), chrono); if (dtStartt.isBefore(dtStart)) { dtStart = dtStartt; } if (dtEndt.isAfter(dtEnd)) { dtEnd = dtEndt; } if (trajFeature.getBoundingBox().getLatMax() > upperLat) { upperLat = trajFeature.getBoundingBox().getLatMax(); } if (trajFeature.getBoundingBox().getLatMin() < lowerLat) { lowerLat = trajFeature.getBoundingBox().getLatMin(); } //lon if (trajFeature.getBoundingBox().getLonMax() > upperLon) { upperLon = trajFeature.getBoundingBox().getLonMax(); } if (trajFeature.getBoundingBox().getLonMax() < lowerLon) { lowerLon = trajFeature.getBoundingBox().getLonMin(); } } } setStartDate(df.toDateTimeStringISO(dtStart.toDate())); setEndDate(df.toDateTimeStringISO(dtEnd.toDate())); if (reqStationNames != null) { setNumberOfStations(reqStationNames.size()); } } } @Override public void setInitialLatLonBounaries(List<Station> tsStationList) { throw new UnsupportedOperationException("Not supported yet."); } @Override public String getDataResponse(int stNum) { System.out.println("getDataResponse Trajectory"); try { if (trajectoryData != null) { return createTrajectoryFeature(stNum); } } catch (IOException ex) { Logger.getLogger(Trajectory.class.getName()).log(Level.SEVERE, null, ex); return DATA_RESPONSE_ERROR + Profile.class; } return DATA_RESPONSE_ERROR + Profile.class; } @Override public String getStationName(int idNum) { if (trajList != null) { return "TRAJECTORY_" + (trajList.get(idNum).getName()); } else { return Invalid_Station; } } @Override public double getLowerLat(int stNum) { if (trajList != null) { return (trajList.get(stNum).getBoundingBox().getLatMin()); } else { return Invalid_Value; } } @Override public double getLowerLon(int stNum) { if (trajList != null) { return (trajList.get(stNum).getBoundingBox().getLonMin()); } else { return Invalid_Value; } } @Override public double getUpperLat(int stNum) { if (trajList != null) { return (trajList.get(stNum).getBoundingBox().getLatMax()); } else { return Invalid_Value; } } @Override public double getUpperLon(int stNum) { if (trajList != null) { return (trajList.get(stNum).getBoundingBox().getLonMax()); } else { return Invalid_Value; } } @Override public String getTimeEnd(int stNum) { if (trajList != null) { return df.toDateTimeStringISO(trajList.get(stNum).getDateRange().getEnd().getDate()); } else { return ERROR_NULL_DATE; } } @Override public String getTimeBegin(int stNum) { if (trajList != null) { return df.toDateTimeStringISO(trajList.get(stNum).getDateRange().getStart().getDate()); } else { return ERROR_NULL_DATE; } } /** * gets the trajectory response for the getcaps request * @param dataset * @param document * @param featureOfInterest * @param GMLName * @param format * @param observedPropertyList * @return * @throws IOException */ public static Document getCapsResponse(FeatureCollection dataset, Document document, String featureOfInterest, String GMLName, List<String> observedPropertyList) throws IOException { //PointFeatureIterator trajIter; while (((TrajectoryFeatureCollection) dataset).hasNext()) { TrajectoryFeature tFeature = ((TrajectoryFeatureCollection) dataset).next(); tFeature.calcBounds(); //trajIter = tFeature.getPointFeatureIterator(-1); //attributes SOSObservationOffering newOffering = new SOSObservationOffering(); newOffering.setObservationStationLowerCorner(Double.toString(tFeature.getBoundingBox().getLatMin()), Double.toString(tFeature.getBoundingBox().getLonMin())); newOffering.setObservationStationUpperCorner(Double.toString(tFeature.getBoundingBox().getLatMax()), Double.toString(tFeature.getBoundingBox().getLonMax())); //check the data if (tFeature.getDateRange() != null) { newOffering.setObservationTimeBegin(tFeature.getDateRange().getStart().toDateTimeStringISO()); newOffering.setObservationTimeEnd(tFeature.getDateRange().getEnd().toDateTimeStringISO()); } //find the dates out! else { System.out.println("no dates yet"); } newOffering.setObservationStationDescription(tFeature.getCollectionFeatureType().toString()); newOffering.setObservationFeatureOfInterest(featureOfInterest + (tFeature.getName())); newOffering.setObservationName(GMLName + (tFeature.getName())); newOffering.setObservationStationID((tFeature.getName())); newOffering.setObservationProcedureLink(GMLName + ((tFeature.getName()))); newOffering.setObservationSrsName("EPSG:4326"); // TODO? newOffering.setObservationObserveredList(observedPropertyList); document = CDMUtils.addObsOfferingToDoc(newOffering, document); } return document; } @Override public String getDescription(int stNum) { throw new UnsupportedOperationException("Not supported yet."); } private String createTrajectoryFeature(int stNum) throws IOException { StringBuilder builder = new StringBuilder(); DateFormatter dateFormatter = new DateFormatter(); TrajectoryFeature trajFeature = trajList.get(stNum); addTrajectoryData(dateFormatter, builder, trajFeature, stNum); return builder.toString(); } private void addTrajectoryData(DateFormatter dateFormatter, StringBuilder builder, TrajectoryFeature traj, int stNum) throws IOException { List<String> valueList = new ArrayList<String>(); PointFeatureIterator trajFeatureIterator = traj.getPointFeatureIterator(-1); DateTime trajTime; DateTime dtStart; DateTime dtEnd; //if no times are specified if (eventTimes == null) { addAllTrajectoryData(trajFeatureIterator, valueList, dateFormatter, builder); } //if more than one date is specified else if (eventTimes.size() > 1) { //get the dates in iso format dtStart = new DateTime(df.getISODate(eventTimes.get(0)), chrono); dtEnd = new DateTime(df.getISODate(eventTimes.get(1)), chrono); while (trajFeatureIterator.hasNext()) { PointFeature trajFeature = trajFeatureIterator.next(); valueList.clear(); trajTime = new DateTime(trajFeature.getObservationTimeAsDate(), chrono); if (trajTime.isEqual(dtStart)) { addDataLine(valueList, dateFormatter, trajFeature, builder); } else if (trajTime.isEqual(dtEnd)) { addDataLine(valueList, dateFormatter, trajFeature, builder); } else if (trajTime.isAfter(dtStart) && (trajTime.isBefore(dtEnd))) { addDataLine(valueList, dateFormatter, trajFeature, builder); } } } //if start and end time were specified else if (eventTimes.size() == 1) { //get the single date in iso format dtStart = new DateTime(df.getISODate(eventTimes.get(0)), chrono); while (trajFeatureIterator.hasNext()) { PointFeature trajFeature = trajFeatureIterator.next(); valueList.clear(); trajTime = new DateTime(trajFeature.getObservationTimeAsDate(), chrono); if (trajTime.isEqual(dtStart)) { addDataLine(valueList, dateFormatter, trajFeature, builder); //if it matches return... break; } } } //times specified are weird, report all else { addAllTrajectoryData(trajFeatureIterator, valueList, dateFormatter, builder); } } }
fixed not having depth in get observation
src/main/java/com/asascience/ncsos/cdmclasses/Trajectory.java
fixed not having depth in get observation
Java
mit
c3dc292960bd15431e31233620f5deed8fa5321a
0
ligoj/ligoj,ligoj/ligoj,ligoj/ligoj,ligoj/ligoj
/* * Licensed under MIT (https://github.com/ligoj/ligoj/blob/master/LICENSE) */ package org.ligoj.app.http.security; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.core.Authentication; /** * Test class of {@link SilentRequestHeaderAuthenticationFilter} */ public class SilentRequestHeaderAuthenticationFilterTest { @Test void doFilterWhitelist() throws IOException, ServletException { final var filter = newFilter(); final var request = Mockito.mock(HttpServletRequest.class); Mockito.doReturn("/path/to/500.html").when(request).getRequestURI(); final var response = Mockito.mock(HttpServletResponse.class); final var chain = Mockito.mock(FilterChain.class); filter.doFilter(request, response, chain); Mockito.verify(chain).doFilter(request, response); } @Test void doFilterRestNoPrincipal() throws IOException, ServletException { final var filter = new SilentRequestHeaderAuthenticationFilter(); final var request = Mockito.mock(HttpServletRequest.class); final var dis = Mockito.mock(RequestDispatcher.class); Mockito.doReturn("/context/rest/service").when(request).getRequestURI(); Mockito.doReturn("/rest/service").when(request).getServletPath(); Mockito.doReturn(dis).when(request).getRequestDispatcher("/401.html"); final var response = Mockito.mock(HttpServletResponse.class); final var chain = Mockito.mock(FilterChain.class); filter.doFilter(request, response, chain); Mockito.verify(dis).forward(request, response); } @Test void doFilterRestApiKey1() throws IOException, ServletException { final var filter = new SilentRequestHeaderAuthenticationFilter(); final var request = Mockito.mock(HttpServletRequest.class); final var dis = Mockito.mock(RequestDispatcher.class); Mockito.doReturn("/context/rest/service").when(request).getRequestURI(); Mockito.doReturn("SOME_API_KEY").when(request).getParameter("api-key"); Mockito.doReturn("/rest/service").when(request).getServletPath(); Mockito.doReturn(dis).when(request).getRequestDispatcher("/401.html"); final var response = Mockito.mock(HttpServletResponse.class); final var chain = Mockito.mock(FilterChain.class); filter.doFilter(request, response, chain); Mockito.verify(chain).doFilter(request, response); } @Test void doFilterRestApiKey2() throws IOException, ServletException { final var filter = new SilentRequestHeaderAuthenticationFilter(); final var request = Mockito.mock(HttpServletRequest.class); final var dis = Mockito.mock(RequestDispatcher.class); Mockito.doReturn("/context/rest/service").when(request).getRequestURI(); Mockito.doReturn("SOME_API_KEY").when(request).getHeader("x-api-key"); Mockito.doReturn("/rest/service").when(request).getServletPath(); Mockito.doReturn(dis).when(request).getRequestDispatcher("/401.html"); final var response = Mockito.mock(HttpServletResponse.class); final var chain = Mockito.mock(FilterChain.class); filter.doFilter(request, response, chain); Mockito.verify(chain).doFilter(request, response); } @Test void doFilterNoPrincipal() throws IOException, ServletException { final var filter = new SilentRequestHeaderAuthenticationFilter(); final var request = Mockito.mock(HttpServletRequest.class); final var dis = Mockito.mock(RequestDispatcher.class); Mockito.doReturn("/path/to").when(request).getRequestURI(); Mockito.doReturn("/").when(request).getServletPath(); Mockito.doReturn(dis).when(request).getRequestDispatcher("/401.html"); final var response = Mockito.mock(HttpServletResponse.class); final var chain = Mockito.mock(FilterChain.class); filter.doFilter(request, response, chain); Mockito.verify(dis).forward(request, response); } @Test void doFilterNoCredentials() throws IOException, ServletException { final var filter = newFilter(); final var request = Mockito.mock(HttpServletRequest.class); final RequestDispatcher dis = Mockito.mock(RequestDispatcher.class); Mockito.doReturn("/path/to").when(request).getRequestURI(); Mockito.doReturn("/").when(request).getServletPath(); Mockito.doReturn("PRINCIPAL").when(request).getHeader("MY_HEADER_P"); Mockito.doReturn(dis).when(request).getRequestDispatcher("/401.html"); final var response = Mockito.mock(HttpServletResponse.class); final var chain = Mockito.mock(FilterChain.class); filter.doFilter(request, response, chain); Mockito.verify(dis).forward(request, response); } @Test void doFilter() throws IOException, ServletException { final var request = Mockito.mock(HttpServletRequest.class); final var dis = Mockito.mock(RequestDispatcher.class); final var filter = newFilter(); Mockito.doReturn("/path/to/rest").when(request).getRequestURI(); Mockito.doReturn("/").when(request).getContextPath(); Mockito.doReturn("/").when(request).getServletPath(); Mockito.doReturn(dis).when(request).getRequestDispatcher("/401.html"); addHeaders(request); final var response = Mockito.mock(HttpServletResponse.class); final var chain = Mockito.mock(FilterChain.class); filter.doFilter(request, response, chain); } @Test void doFilterLogin() throws IOException, ServletException { final var request = Mockito.mock(HttpServletRequest.class); final var dis = Mockito.mock(RequestDispatcher.class); final var filter = newFilter(); Mockito.doReturn("/context/login.html").when(request).getRequestURI(); Mockito.doReturn("/context").when(request).getContextPath(); Mockito.doReturn("/").when(request).getServletPath(); Mockito.doReturn(dis).when(request).getRequestDispatcher("/401.html"); addHeaders(request); final var response = Mockito.mock(HttpServletResponse.class); final var chain = Mockito.mock(FilterChain.class); filter.doFilter(request, response, chain); Mockito.verify(response).sendRedirect("/context/"); } private SilentRequestHeaderAuthenticationFilter newFilter() { final var authenticationManager = Mockito.mock(AuthenticationManager.class); final var filter = new SilentRequestHeaderAuthenticationFilter() { @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) { // Nothing to do } }; filter.setPrincipalRequestHeader("MY_HEADER_P"); filter.setCredentialsRequestHeader("MY_HEADER_C"); filter.setAuthenticationManager(authenticationManager); return filter; } private void addHeaders(final HttpServletRequest request) { Mockito.doReturn("PRINCIPAL").when(request).getHeader("MY_HEADER_P"); Mockito.doReturn("CREDS").when(request).getHeader("MY_HEADER_C"); } }
app-ui/src/test/java/org/ligoj/app/http/security/SilentRequestHeaderAuthenticationFilterTest.java
/* * Licensed under MIT (https://github.com/ligoj/ligoj/blob/master/LICENSE) */ package org.ligoj.app.http.security; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.core.Authentication; /** * Test class of {@link SilentRequestHeaderAuthenticationFilter} */ public class SilentRequestHeaderAuthenticationFilterTest { @Test public void doFilterWhitelist() throws IOException, ServletException { final Filter filter = newFilter(); final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.doReturn("/path/to/500.html").when(request).getRequestURI(); final HttpServletResponse response = Mockito.mock(HttpServletResponse.class); final FilterChain chain = Mockito.mock(FilterChain.class); filter.doFilter(request, response, chain); Mockito.verify(chain).doFilter(request, response); } @Test public void doFilterNoPrincipal() throws IOException, ServletException { final Filter filter = new SilentRequestHeaderAuthenticationFilter(); final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); final RequestDispatcher dis = Mockito.mock(RequestDispatcher.class); Mockito.doReturn("/path/to/rest").when(request).getRequestURI(); Mockito.doReturn(dis).when(request).getRequestDispatcher("/401.html"); final HttpServletResponse response = Mockito.mock(HttpServletResponse.class); final FilterChain chain = Mockito.mock(FilterChain.class); filter.doFilter(request, response, chain); Mockito.verify(dis).forward(request, response); } @Test public void doFilterNoCredentials() throws IOException, ServletException { final Filter filter = newFilter(); final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); final RequestDispatcher dis = Mockito.mock(RequestDispatcher.class); Mockito.doReturn("/path/to/rest").when(request).getRequestURI(); Mockito.doReturn("PRINCIPAL").when(request).getHeader("MY_HEADER_P"); Mockito.doReturn(dis).when(request).getRequestDispatcher("/401.html"); final HttpServletResponse response = Mockito.mock(HttpServletResponse.class); final FilterChain chain = Mockito.mock(FilterChain.class); filter.doFilter(request, response, chain); Mockito.verify(dis).forward(request, response); } @Test public void doFilter() throws IOException, ServletException { final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); final RequestDispatcher dis = Mockito.mock(RequestDispatcher.class); final SilentRequestHeaderAuthenticationFilter filter = newFilter(); Mockito.doReturn("/path/to/rest").when(request).getRequestURI(); Mockito.doReturn("/").when(request).getContextPath(); addHeaders(request); Mockito.doReturn(dis).when(request).getRequestDispatcher("/401.html"); final HttpServletResponse response = Mockito.mock(HttpServletResponse.class); final FilterChain chain = Mockito.mock(FilterChain.class); filter.doFilter(request, response, chain); } @Test public void doFilterLogin() throws IOException, ServletException { final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); final RequestDispatcher dis = Mockito.mock(RequestDispatcher.class); final SilentRequestHeaderAuthenticationFilter filter = newFilter(); Mockito.doReturn("/context/login.html").when(request).getRequestURI(); Mockito.doReturn("/context").when(request).getContextPath(); addHeaders(request); Mockito.doReturn(dis).when(request).getRequestDispatcher("/401.html"); final HttpServletResponse response = Mockito.mock(HttpServletResponse.class); final FilterChain chain = Mockito.mock(FilterChain.class); filter.doFilter(request, response, chain); Mockito.verify(response).sendRedirect("/context"); } private SilentRequestHeaderAuthenticationFilter newFilter() { final AuthenticationManager authenticationManager = Mockito.mock(AuthenticationManager.class); final SilentRequestHeaderAuthenticationFilter filter = new SilentRequestHeaderAuthenticationFilter() { @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) { // Nothing to do } }; filter.setPrincipalRequestHeader("MY_HEADER_P"); filter.setCredentialsRequestHeader("MY_HEADER_C"); filter.setAuthenticationManager(authenticationManager); return filter; } private void addHeaders(final HttpServletRequest request) { Mockito.doReturn("PRINCIPAL").when(request).getHeader("MY_HEADER_P"); Mockito.doReturn("CREDS").when(request).getHeader("MY_HEADER_C"); } }
Lint coveralls
app-ui/src/test/java/org/ligoj/app/http/security/SilentRequestHeaderAuthenticationFilterTest.java
Lint coveralls
Java
epl-1.0
9376287abf39175edb2577be0ead6df838636f34
0
ESSICS/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio
/******************************************************************************* * Copyright (c) 2013 Oak Ridge National Laboratory. * 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 ******************************************************************************/ package org.csstudio.ui.util.widgets; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.events.FocusAdapter; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; /** * Combo-type widget that allows selecting multiple items. * * <p> * Takes a list of {@link Object}s as input. * * <p> * The <code>toString()</code> of each Object is displayed in a drop-down list. * Overriding the stringRepresention() method, the user can define an * alternative way to convert T to String. * * <p> * One or more items can be selected, they're also displayed in the text field. * * <p> * Items can be entered in the text field, comma-separated. If entered text does * not match a valid item, text is highlighted and tool-tip indicates error. * * <p> * Keyboard support: 'Down' key in text field opens drop-down. Inside drop-down, * single item can be selected via cursor key and 'RETURN' closes the drop-down. * * TODO Auto-completion while typing? * * @author Kay Kasemir, Kunal Shroff */ public class MultipleSelectionCombo<T> extends Composite { final private static String SEPARATOR = ", "; //$NON-NLS-1$ final private static String SEPERATOR_PATTERN = "\\s*,\\s*"; //$NON-NLS-1$ private final PropertyChangeSupport changeSupport = new PropertyChangeSupport( this); private Display display; private Text text; /** Pushing the drop_down button opens the popup */ private Button drop_down; private Shell popup; private org.eclipse.swt.widgets.List list; /** Items to show in list */ private List<T> items = new ArrayList<T>(); /** Selection indices */ private List<Integer> selectionIndex = new ArrayList<Integer>(); private String tool_tip = null; private Color text_color = null; /** * When list looses focus, the event time is noted here. This prevents the * drop-down button from re-opening the list right away. */ private long lost_focus = 0; private volatile boolean modify = false; /** * Initialize * * @param parent * @param style */ public MultipleSelectionCombo(final Composite parent, final int style) { super(parent, style); createComponents(parent); } /** * Create SWT components * * @param parent */ private void createComponents(final Composite parent) { display = parent.getDisplay(); final GridLayout layout = new GridLayout(); layout.numColumns = 2; layout.marginWidth = 0; setLayout(layout); addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { switch (e.getPropertyName()) { case "selection": if (modify) { break; } else { updateText(); break; } case "items": setSelection(Collections.<T> emptyList()); break; default: break; } } }); text = new Text(this, SWT.BORDER); GridData gd = new GridData(SWT.FILL, 0, true, false); text.setLayoutData(gd); text.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { // Analyze text, update selection final String items_text = text.getText(); modify = true; setSelection(items_text); modify = false; } }); text.addKeyListener(new KeyAdapter() { @Override public void keyPressed(final KeyEvent e) { switch (e.keyCode) { case SWT.ARROW_DOWN: drop(true); return; case SWT.ARROW_UP: drop(false); return; case SWT.CR: modify =false; updateText(); } } }); drop_down = new Button(this, SWT.ARROW | SWT.DOWN); gd = new GridData(SWT.FILL, SWT.FILL, false, false); gd.heightHint = text.getBounds().height; drop_down.setLayoutData(gd); drop_down.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e) { // Was list open, user clicked this button to close, // and list self-closed because is lost focus? // e.time is an unsigned integer and should be AND'ed with // 0xFFFFFFFFL so that it can be treated as a signed long. if ((e.time & 0xFFFFFFFFL) - lost_focus <= 300) return; // Done // If list is not open, open it if (!isDropped()) drop(true); } }); } /** {@inheritDoc} */ @Override public void setForeground(final Color color) { text_color = color; text.setForeground(color); } /** {@inheritDoc} */ @Override public void setToolTipText(final String tooltip) { tool_tip = tooltip; text.setToolTipText(tooltip); drop_down.setToolTipText(tooltip); } /** * Define items to be displayed in the list, and returned as the current * selection when selected. * * @param new_items * Items to display in the list */ public void setItems(final List<T> items) { List<T> oldValue = this.items; this.items = items; changeSupport.firePropertyChange("items", oldValue, this.items); } /** * Get the list of items * * @return list of selectable items */ public List<T> getItems() { return this.items; } /** * Set items that should be selected. * * <p> * Selected items must be on the list of items provided via * <code>setItems</code> * * @param sel_items * Items to select in the list */ public void setSelection(final List<T> selection) { List<Integer> oldValue = this.selectionIndex; List<Integer> newSelectionIndex = new ArrayList<Integer>( selection.size()); for (T t : selection) { int index = items.indexOf(t); if (index >= 0) { newSelectionIndex.add(items.indexOf(t)); } } this.selectionIndex = newSelectionIndex; changeSupport.firePropertyChange("selection", oldValue, this.selectionIndex); } /** * set the items to be selected, the selection is specified as a string with * values separated by {@value MultipleSelectionCombo.SEPARATOR} * * @param selection_text * Items to select in the list as comma-separated string */ public void setSelection(final String selection) { setSelection("".equals(selection) ? new String[0] : selection .split(SEPERATOR_PATTERN)); } /** * Set the items to be selected * * @param selections */ public void setSelection(final String[] selections) { List<Integer> oldValue = this.selectionIndex; List<Integer> newSelectionIndex; if (selections.length > 0) { newSelectionIndex = new ArrayList<Integer>(selections.length); // Locate index for each item for (String item : selections) { int index = getIndex(item); if (index >= 0 && index < items.size()) { newSelectionIndex.add(getIndex(item)); text.setForeground(text_color); text.setToolTipText(tool_tip); } else { text.setForeground(display.getSystemColor(SWT.COLOR_RED)); text.setToolTipText("Text contains invalid items"); } } } else { newSelectionIndex = Collections.emptyList(); } this.selectionIndex = newSelectionIndex; changeSupport.firePropertyChange("selection", oldValue, this.selectionIndex); } /** * return the index of the object in items with the string representation * _string_ * * @param string * @return */ private Integer getIndex(String string) { for (T item : items) { if (stringRepresention(item).equals(string)) { return items.indexOf(item); } } return -1; } /** * get the list of items currently selected. Note: this does not return the * list in the order of selection. * * @return the list of selected items */ public List<T> getSelection() { List<T> selection = new ArrayList<T>(this.selectionIndex.size()); for (int index : this.selectionIndex) { selection.add(items.get(index)); } return Collections.unmodifiableList(selection); } /** Update <code>selection</code> from <code>list</code> */ private void updateSelectionFromList() { setSelection(list.getSelection()); } /** Update <code>text</code> to reflect <code>selection</code> */ private void updateText() { final StringBuilder buf = new StringBuilder(); for (Integer index : selectionIndex) { if (buf.length() > 0) buf.append(SEPARATOR); buf.append(stringRepresention(items.get(index))); } text.setText(buf.toString()); text.setSelection(buf.length()); } /** @return <code>true</code> if drop-down is visible */ private boolean isDropped() { return popup != null; } /** * @param drop * Display drop-down? */ private void drop(boolean drop) { if (drop == isDropped()) return; if (drop) createPopup(); else hidePopup(); } /** Create shell that simulates drop-down */ private void createPopup() { popup = new Shell(getShell(), SWT.NO_TRIM | SWT.ON_TOP); popup.setLayout(new FillLayout()); list = new org.eclipse.swt.widgets.List(popup, SWT.MULTI | SWT.V_SCROLL); list.setToolTipText(tool_tip); // Position popup under the text box Rectangle bounds = text.getBounds(); bounds.y += bounds.height; // As high as necessary for items bounds.height = 5 + 2 * list.getBorderWidth() + list.getItemHeight() * items.size(); // ..with limitation bounds.height = Math.min(bounds.height, display.getBounds().height / 2); // Map to screen coordinates bounds = display.map(text, null, bounds); popup.setBounds(bounds); popup.open(); // Update text from changed list selection list.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { updateSelectionFromList(); updateText(); } @Override public void widgetDefaultSelected(SelectionEvent e) { updateSelectionFromList(); updateText(); hidePopup(); } }); String[] stringItems = new String[items.size()]; for (int i = 0; i < items.size(); i++) { stringItems[i] = stringRepresention(items.get(i)); } list.setItems(stringItems); int[] intSelectionIndex = new int[selectionIndex.size()]; for (int i = 0; i < intSelectionIndex.length; i++) { intSelectionIndex[i] = selectionIndex.get(i); } list.setSelection(intSelectionIndex); list.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { if (e.keyCode == SWT.CR) { hidePopup(); } } }); // Hide popup when loosing focus list.addFocusListener(new FocusAdapter() { @Override public void focusLost(final FocusEvent e) { // This field is an unsigned integer and should be AND'ed with // 0xFFFFFFFFL so that it can be treated as a signed long. lost_focus = e.time & 0xFFFFFFFFL; hidePopup(); } }); list.setFocus(); } /** Hide popup shell */ private void hidePopup() { if (popup != null) { popup.close(); popup.dispose(); popup = null; } text.setFocus(); } /** * Register a PropertyChangeListener on this widget. the listener will be * notified when the items or the selection is changed. * * @param listener */ public void addPropertyChangeListener(PropertyChangeListener listener) { changeSupport.addPropertyChangeListener(listener); } /** * remove the PropertyChangeListner * * @param listener */ public void removePropertyChangeListener(PropertyChangeListener listener) { changeSupport.removePropertyChangeListener(listener); } /** * Override this method to define the how the object should be represented * as a string. * * @param object * @return the string representation of the object */ public String stringRepresention(T object) { return object.toString(); } }
core/plugins/org.csstudio.ui.util/src/org/csstudio/ui/util/widgets/MultipleSelectionCombo.java
/******************************************************************************* * Copyright (c) 2013 Oak Ridge National Laboratory. * 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 ******************************************************************************/ package org.csstudio.ui.util.widgets; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.events.FocusAdapter; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; /** * Combo-type widget that allows selecting multiple items. * * <p> * Takes a list of {@link Object}s as input. * * <p> * The <code>toString()</code> of each Object is displayed in a drop-down list. * Overriding the stringRepresention() method, the user can define an * alternative way to convert T to String. * * <p> * One or more items can be selected, they're also displayed in the text field. * * <p> * Items can be entered in the text field, comma-separated. If entered text does * not match a valid item, text is highlighted and tool-tip indicates error. * * <p> * Keyboard support: 'Down' key in text field opens drop-down. Inside drop-down, * single item can be selected via cursor key and 'RETURN' closes the drop-down. * * TODO Auto-completion while typing? * * @author Kay Kasemir, Kunal Shroff */ public class MultipleSelectionCombo<T> extends Composite { final private static String SEPARATOR = ", "; //$NON-NLS-1$ final private static String SEPERATOR_PATTERN = "\\s*,\\s*"; //$NON-NLS-1$ private final PropertyChangeSupport changeSupport = new PropertyChangeSupport( this); private Display display; private Text text; /** Pushing the drop_down button opens the popup */ private Button drop_down; private Shell popup; private org.eclipse.swt.widgets.List list; /** Items to show in list */ private List<T> items = new ArrayList<T>(); /** Selection indices */ private List<Integer> selectionIndex = new ArrayList<Integer>(); private String tool_tip = null; private Color text_color = null; /** * When list looses focus, the event time is noted here. This prevents the * drop-down button from re-opening the list right away. */ private long lost_focus = 0; private volatile boolean modify = false; /** * Initialize * * @param parent * @param style */ public MultipleSelectionCombo(final Composite parent, final int style) { super(parent, style); createComponents(parent); } /** * Create SWT components * * @param parent */ private void createComponents(final Composite parent) { display = parent.getDisplay(); final GridLayout layout = new GridLayout(); layout.numColumns = 2; layout.marginWidth = 0; setLayout(layout); addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { switch (e.getPropertyName()) { case "selection": if (modify) { break; } else { updateText(); break; } case "items": setSelection(Collections.<T> emptyList()); break; default: break; } } }); text = new Text(this, SWT.BORDER); GridData gd = new GridData(SWT.FILL, 0, true, false); text.setLayoutData(gd); text.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { // Analyze text, update selection final String items_text = text.getText(); modify = true; setSelection(items_text); modify = false; } }); text.addKeyListener(new KeyAdapter() { @Override public void keyPressed(final KeyEvent e) { switch (e.keyCode) { case SWT.ARROW_DOWN: drop(true); return; case SWT.ARROW_UP: drop(false); return; case SWT.CR: modify =false; updateText(); } } }); drop_down = new Button(this, SWT.ARROW | SWT.DOWN); gd = new GridData(SWT.FILL, SWT.FILL, false, false); gd.heightHint = text.getBounds().height; drop_down.setLayoutData(gd); drop_down.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e) { // Was list open, user clicked this button to close, // and list self-closed because is lost focus? // e.time is an unsigned integer and should be AND'ed with // 0xFFFFFFFFL so that it can be treated as a signed long. if ((e.time & 0xFFFFFFFFL) - lost_focus <= 300) return; // Done // If list is not open, open it if (!isDropped()) drop(true); } }); } /** {@inheritDoc} */ @Override public void setForeground(final Color color) { text_color = color; text.setForeground(color); } /** {@inheritDoc} */ @Override public void setToolTipText(final String tooltip) { tool_tip = tooltip; text.setToolTipText(tooltip); drop_down.setToolTipText(tooltip); } /** * Define items to be displayed in the list, and returned as the current * selection when selected. * * @param new_items * Items to display in the list */ public void setItems(final List<T> items) { List<T> oldValue = this.items; this.items = items; changeSupport.firePropertyChange("items", oldValue, this.items); } /** * Get the list of items * * @return list of selectable items */ public List<T> getItems() { return this.items; } /** * Set items that should be selected. * * <p> * Selected items must be on the list of items provided via * <code>setItems</code> * * @param sel_items * Items to select in the list */ public void setSelection(final List<T> selection) { List<Integer> oldValue = this.selectionIndex; List<Integer> newSelectionIndex = new ArrayList<Integer>( selection.size()); for (T t : selection) { newSelectionIndex.add(items.indexOf(t)); } this.selectionIndex = newSelectionIndex; changeSupport.firePropertyChange("selection", oldValue, this.selectionIndex); } /** * set the items to be selected, the selection is specified as a string with * values separated by {@value MultipleSelectionCombo.SEPARATOR} * * @param selection_text * Items to select in the list as comma-separated string */ public void setSelection(final String selection) { setSelection("".equals(selection) ? new String[0] : selection .split(SEPERATOR_PATTERN)); } /** * Set the items to be selected * * @param selections */ public void setSelection(final String[] selections) { List<Integer> oldValue = this.selectionIndex; List<Integer> newSelectionIndex; if (selections.length > 0) { newSelectionIndex = new ArrayList<Integer>(selections.length); // Locate index for each item for (String item : selections) { int index = getIndex(item); if (index >= 0 && index < items.size()) { newSelectionIndex.add(getIndex(item)); text.setForeground(text_color); text.setToolTipText(tool_tip); } else { text.setForeground(display.getSystemColor(SWT.COLOR_RED)); text.setToolTipText("Text contains invalid items"); } } } else { newSelectionIndex = Collections.emptyList(); } this.selectionIndex = newSelectionIndex; changeSupport.firePropertyChange("selection", oldValue, this.selectionIndex); } /** * return the index of the object in items with the string representation * _string_ * * @param string * @return */ private Integer getIndex(String string) { for (T item : items) { if (stringRepresention(item).equals(string)) { return items.indexOf(item); } } return -1; } /** * get the list of items currently selected. Note: this does not return the * list in the order of selection. * * @return the list of selected items */ public List<T> getSelection() { List<T> selection = new ArrayList<T>(this.selectionIndex.size()); for (int index : this.selectionIndex) { selection.add(items.get(index)); } return Collections.unmodifiableList(selection); } /** Update <code>selection</code> from <code>list</code> */ private void updateSelectionFromList() { setSelection(list.getSelection()); } /** Update <code>text</code> to reflect <code>selection</code> */ private void updateText() { final StringBuilder buf = new StringBuilder(); for (Integer index : selectionIndex) { if (buf.length() > 0) buf.append(SEPARATOR); buf.append(stringRepresention(items.get(index))); } text.setText(buf.toString()); text.setSelection(buf.length()); } /** @return <code>true</code> if drop-down is visible */ private boolean isDropped() { return popup != null; } /** * @param drop * Display drop-down? */ private void drop(boolean drop) { if (drop == isDropped()) return; if (drop) createPopup(); else hidePopup(); } /** Create shell that simulates drop-down */ private void createPopup() { popup = new Shell(getShell(), SWT.NO_TRIM | SWT.ON_TOP); popup.setLayout(new FillLayout()); list = new org.eclipse.swt.widgets.List(popup, SWT.MULTI | SWT.V_SCROLL); list.setToolTipText(tool_tip); // Position popup under the text box Rectangle bounds = text.getBounds(); bounds.y += bounds.height; // As high as necessary for items bounds.height = 5 + 2 * list.getBorderWidth() + list.getItemHeight() * items.size(); // ..with limitation bounds.height = Math.min(bounds.height, display.getBounds().height / 2); // Map to screen coordinates bounds = display.map(text, null, bounds); popup.setBounds(bounds); popup.open(); // Update text from changed list selection list.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { updateSelectionFromList(); updateText(); } @Override public void widgetDefaultSelected(SelectionEvent e) { updateSelectionFromList(); updateText(); hidePopup(); } }); String[] stringItems = new String[items.size()]; for (int i = 0; i < items.size(); i++) { stringItems[i] = stringRepresention(items.get(i)); } list.setItems(stringItems); int[] intSelectionIndex = new int[selectionIndex.size()]; for (int i = 0; i < intSelectionIndex.length; i++) { intSelectionIndex[i] = selectionIndex.get(i); } list.setSelection(intSelectionIndex); list.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { if (e.keyCode == SWT.CR) { hidePopup(); } } }); // Hide popup when loosing focus list.addFocusListener(new FocusAdapter() { @Override public void focusLost(final FocusEvent e) { // This field is an unsigned integer and should be AND'ed with // 0xFFFFFFFFL so that it can be treated as a signed long. lost_focus = e.time & 0xFFFFFFFFL; hidePopup(); } }); list.setFocus(); } /** Hide popup shell */ private void hidePopup() { if (popup != null) { popup.close(); popup.dispose(); popup = null; } text.setFocus(); } /** * Register a PropertyChangeListener on this widget. the listener will be * notified when the items or the selection is changed. * * @param listener */ public void addPropertyChangeListener(PropertyChangeListener listener) { changeSupport.addPropertyChangeListener(listener); } /** * remove the PropertyChangeListner * * @param listener */ public void removePropertyChangeListener(PropertyChangeListener listener) { changeSupport.removePropertyChangeListener(listener); } /** * Override this method to define the how the object should be represented * as a string. * * @param object * @return the string representation of the object */ public String stringRepresention(T object) { return object.toString(); } }
MultipleSelectionCombo: Fix ArrayOutOfBoundException in case of given selection not match with available values.
core/plugins/org.csstudio.ui.util/src/org/csstudio/ui/util/widgets/MultipleSelectionCombo.java
MultipleSelectionCombo: Fix ArrayOutOfBoundException in case of given selection not match with available values.
Java
epl-1.0
69a8d71e6540970a4e14fb4aa0e138321c8a2ba3
0
parzonka/prm4j
/* * Copyright (c) 2012 Mateusz Parzonka, Eric Bodden * 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 * * Contributors: * Mateusz Parzonka - initial API and implementation */ package prm4j.indexing.realtime; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import prm4j.api.fsm.FSMSpec; import prm4j.spec.FiniteSpec; public class DefaultParametricMonitor2Test extends AbstractDefaultParametricMonitorTest { FSM_a_ab_a_b fsm; final String a = "a"; final String b = "b"; final String c = "c"; @Before public void init() { fsm = new FSM_a_ab_a_b(); FiniteSpec finiteSpec = new FSMSpec(fsm.fsm); createDefaultParametricMonitorWithAwareComponents(finiteSpec); } // firstEvent_a ////////////////////////////////////////////////////////////////// @Test public void firstEvent_a_createsOnlyOneMonitor() throws Exception { // exercise pm.processEvent(fsm.e1.createEvent(a)); // verify popNextCreatedMonitor(); assertNoMoreCreatedMonitors(); } @Test public void firstEvent_a_updatesOnlyOneMonitor() throws Exception { // exercise pm.processEvent(fsm.e1.createEvent(a)); // verify popNextUpdatedMonitor(); assertNoMoreUpdatedMonitors(); } @Test public void firstEvent_a_createsMonitorWithCreationTime0() throws Exception { // exercise pm.processEvent(fsm.e1.createEvent(a)); // verify assertEquals(0L, popNextUpdatedMonitor().getCreationTime()); } @Test public void firstEvent_a_createsCorrectTrace() throws Exception { // exercise pm.processEvent(fsm.e1.createEvent(a)); // verify assertTrace(popNextUpdatedMonitor(), fsm.e1); } @Test public void firstEvent_a_monitorBindsAllItsParameters() throws Exception { // exercise pm.processEvent(fsm.e1.createEvent(a)); // verify assertBoundObjects(popNextUpdatedMonitor(), a); } @Test public void firstEvent_a_noMatchDetected() throws Exception { // exercise pm.processEvent(fsm.e1.createEvent(a)); // verify assertTrue(fsm.matchHandler.getHandledMatches().isEmpty()); } @Test public void firstEvent_a_onlyOneNodeIsRetrieved() throws Exception { // exercise pm.processEvent(fsm.e1.createEvent(a)); // verify assertNotNull(popNextRetrievedNode()); assertNoMoreRetrievedNodes(); } @Test public void firstEvent_a_nodeHasOneMonitorSet() throws Exception { // exercise pm.processEvent(fsm.e1.createEvent(a)); // verify assertArrayEquals(new MonitorSet[1], popNextRetrievedNode().getMonitorSets()); } @Test public void firstEvent_a_metaNodeHasCorrectParameterSet() throws Exception { // exercise pm.processEvent(fsm.e1.createEvent(a)); // verify assertEquals(asSet(fsm.p1), popNextRetrievedNode().getMetaNode().getNodeParameterSet()); } // firstEvent_ab ////////////////////////////////////////////////////////////////// // monitors are not created because of ab is no creation event @Test public void firstEvent_ab_doesNotCreateMonitor() throws Exception { // exercise pm.processEvent(fsm.e2.createEvent(a, b)); // verify assertNoMoreCreatedMonitors(); } @Test public void firstEvent_ab_doesNotUpdateMonitor() throws Exception { // exercise pm.processEvent(fsm.e2.createEvent(a, b)); // verify assertNoMoreUpdatedMonitors(); } @Test public void firstEvent_ab_noMatchDetected() throws Exception { // exercise pm.processEvent(fsm.e2.createEvent(a, b)); // verify assertTrue(fsm.matchHandler.getHandledMatches().isEmpty()); } // twoEvent_a_b = a followed by b //////////////////////////////// @Test public void twoEvents_a_b_secondEventDoesCreateASingleNewMonitor() throws Exception { // exercise pm.processEvent(fsm.e1.createEvent(a)); popNextCreatedMonitor(); pm.processEvent(fsm.e1.createEvent(b)); // verify popNextCreatedMonitor(); assertNoMoreCreatedMonitors(); } @Test public void twoEvents_a_b_createdMonitorsAreDifferent() throws Exception { // exercise pm.processEvent(fsm.e1.createEvent(a)); pm.processEvent(fsm.e1.createEvent(b)); // verify assertNotSame(popNextCreatedMonitor(), popNextCreatedMonitor()); } @Test public void twoEvents_a_b_updatedMonitorsAreDifferent() throws Exception { // exercise pm.processEvent(fsm.e1.createEvent(a)); pm.processEvent(fsm.e1.createEvent(b)); // verify assertNotSame(popNextUpdatedMonitor(), popNextUpdatedMonitor()); assertNoMoreUpdatedMonitors(); } @Test public void twoEvents_a_b_bothTracesAreCorrect() throws Exception { // exercise pm.processEvent(fsm.e1.createEvent(a)); pm.processEvent(fsm.e1.createEvent(b)); // verify assertTrace(popNextUpdatedMonitor(), fsm.e1); assertTrace(popNextUpdatedMonitor(), fsm.e1); } @Test public void twoEvents_a_b_timestampsAreCorrect() throws Exception { // exercise pm.processEvent(fsm.e1.createEvent(a)); pm.processEvent(fsm.e1.createEvent(b)); // verify assertEquals(0L, popNextCreatedMonitor().getCreationTime()); assertEquals(1L, popNextCreatedMonitor().getCreationTime()); } @Test public void twoEvents_a_b_boundObjectsAreCorrect() throws Exception { // exercise pm.processEvent(fsm.e1.createEvent(a)); pm.processEvent(fsm.e1.createEvent(b)); // verify assertBoundObjects(popNextCreatedMonitor(), a); assertBoundObjects(popNextCreatedMonitor(), b); } }
src/test/java/prm4j/indexing/realtime/DefaultParametricMonitor2Test.java
/* * Copyright (c) 2012 Mateusz Parzonka, Eric Bodden * 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 * * Contributors: * Mateusz Parzonka - initial API and implementation */ package prm4j.indexing.realtime; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import prm4j.api.fsm.FSMSpec; import prm4j.spec.FiniteSpec; public class DefaultParametricMonitor2Test extends AbstractDefaultParametricMonitorTest { FSM_a_ab_a_b fsm; final String a = "a"; final String b = "b"; final String c = "c"; @Before public void init() { fsm = new FSM_a_ab_a_b(); FiniteSpec finiteSpec = new FSMSpec(fsm.fsm); createDefaultParametricMonitorWithAwareComponents(finiteSpec); } // firstEvent_a ////////////////////////////////////////////////////////////////// @Test public void firstEvent_a_createsOnlyOneMonitor() throws Exception { // exercise pm.processEvent(fsm.e1.createEvent(a)); // verify popNextCreatedMonitor(); assertNoMoreCreatedMonitors(); } @Test public void firstEvent_a_updatesOnlyOneMonitor() throws Exception { // exercise pm.processEvent(fsm.e1.createEvent(a)); // verify popNextUpdatedMonitor(); assertNoMoreUpdatedMonitors(); } @Test public void firstEvent_a_createsMonitorWithCreationTime0() throws Exception { // exercise pm.processEvent(fsm.e1.createEvent(a)); // verify assertEquals(0L, popNextUpdatedMonitor().getCreationTime()); } @Test public void firstEvent_a_createsCorrectTrace() throws Exception { // exercise pm.processEvent(fsm.e1.createEvent(a)); // verify assertTrace(popNextUpdatedMonitor(), fsm.e1); } @Test public void firstEvent_a_monitorBindsAllItsParameters() throws Exception { // exercise pm.processEvent(fsm.e1.createEvent(a)); // verify assertBoundObjects(popNextUpdatedMonitor(), a); } @Test public void firstEvent_a_noMatchDetected() throws Exception { // exercise pm.processEvent(fsm.e1.createEvent(a)); // verify assertTrue(fsm.matchHandler.getHandledMatches().isEmpty()); } @Test public void firstEvent_a_onlyOneNodeIsRetrieved() throws Exception { // exercise pm.processEvent(fsm.e1.createEvent(a)); // verify assertNotNull(popNextRetrievedNode()); assertNoMoreRetrievedNodes(); } @Test public void firstEvent_a_nodeHasOneMonitorSet() throws Exception { // exercise pm.processEvent(fsm.e1.createEvent(a)); // verify assertArrayEquals(new MonitorSet[1], popNextRetrievedNode().getMonitorSets()); } @Test public void firstEvent_a_metaNodeHasCorrectParameterSet() throws Exception { // exercise pm.processEvent(fsm.e1.createEvent(a)); // verify assertEquals(asSet(fsm.p1), popNextRetrievedNode().getMetaNode().getNodeParameterSet()); } // firstEvent_ab ////////////////////////////////////////////////////////////////// @Test public void firstEvent_ab_doesNotCreateMonitor() throws Exception { // exercise pm.processEvent(fsm.e2.createEvent(a, b)); // verify assertNoMoreCreatedMonitors(); } @Test public void firstEvent_ab_doesNotUpdateMonitor() throws Exception { // exercise pm.processEvent(fsm.e2.createEvent(a, b)); // verify assertNoMoreUpdatedMonitors(); } @Test public void firstEvent_ab_noMatchDetected() throws Exception { // exercise pm.processEvent(fsm.e2.createEvent(a, b)); // verify assertTrue(fsm.matchHandler.getHandledMatches().isEmpty()); } }
Add tests for a, b sequence of base events
src/test/java/prm4j/indexing/realtime/DefaultParametricMonitor2Test.java
Add tests for a, b sequence of base events
Java
mpl-2.0
e46b396ae54d4a85d5c2afc9ec417b1f67ae389f
0
anthonycr/Lightning-Browser,anthonycr/Lightning-Browser,anthonycr/Lightning-Browser,anthonycr/Lightning-Browser,t61p/Lightning-Browser
/* * Copyright 2014 A.C.R. Development */ package acr.browser.lightning; public class HomepageVariables { public static final String HEAD = "<!DOCTYPE html><html xmlns=\"http://www.w3.org/1999/xhtml\">" + "<head>" + "<meta content=\"en-us\" http-equiv=\"Content-Language\" />" + "<meta content=\"text/html; charset=utf-8\" http-equiv=\"Content-Type\" />" + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">" + "<title>" + BrowserApp.getAppContext().getString(R.string.home) + "</title>" + "</head>" + "<style>body{background:#f2f2f2;text-align:center;margin:0px;}#search_input{height:35px; " + "width:100%;outline:none;border:none;font-size: 16px;background-color:transparent;}" + "span { display: block; overflow: hidden; padding-left:5px;vertical-align:middle;}" + ".search_bar{display:table;vertical-align:middle;width:90%;height:35px;max-width:500px;margin:0 auto;background-color:#fff;box-shadow: 0px 3px rgba( 0, 0, 0, 0.1 );" + "font-family: Arial;color: #444;-moz-border-radius: 2px;-webkit-border-radius: 2px;border-radius: 2px;}" + "#search_submit{outline:none;height:37px;float:right;color:#404040;font-size:16px;font-weight:bold;border:none;" + "background-color:transparent;}.outer { display: table; position: absolute; height: 100%; width: 100%;}" + ".middle { display: table-cell; vertical-align: middle;}.inner { margin-left: auto; margin-right: auto; " + "margin-bottom:10%; <!-->maybe bad for small screens</!--> width: 100%;}img.smaller{width:50%;max-width:300px;}" + ".box { vertical-align:middle;position:relative; display: block; margin: 10px;padding-left:10px;padding-right:10px;padding-top:5px;padding-bottom:5px;" + " background-color:#fff;box-shadow: 0px 3px rgba( 0, 0, 0, 0.1 );font-family: Arial;color: #444;" + "font-size: 12px;-moz-border-radius: 2px;-webkit-border-radius: 2px;" + "border-radius: 2px;}</style><body> <div class=\"outer\"><div class=\"middle\"><div class=\"inner\"><img class=\"smaller\" src=\""; public static final String MIDDLE = "\" ></br></br><form onsubmit=\"return search()\" class=\"search_bar\">" + "<input type=\"submit\" id=\"search_submit\" value=\"Search\" ><span><input class=\"search\" type=\"text\" value=\"\" id=\"search_input\" >" + "</span></form></br></br></div></div></div><script type=\"text/javascript\">function search(){if(document.getElementById(\"search_input\").value != \"\"){window.location.href = \""; public static final String END = "\" + document.getElementById(\"search_input\").value;document.getElementById(\"search_input\").value = \"\";}return false;}</script></body></html>"; }
src/acr/browser/lightning/HomepageVariables.java
/* * Copyright 2014 A.C.R. Development */ package acr.browser.lightning; public class HomepageVariables { public static final String HEAD = "<!DOCTYPE html><html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta content=\"en-us\" http-equiv=\"Content-Language\" /><meta content=\"text/html; charset=utf-8\" http-equiv=\"Content-Type\" /><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=0\"><title>" + BrowserApp.getAppContext().getString(R.string.home) + "</title></head>" + "<style>body{background:#f2f2f2;text-align:center;}#search_input{height:35px; width:100%;outline:none;border:none;font-size: 16px;background-color:transparent;}span { display: block; overflow: hidden; padding-left:5px;vertical-align:middle;}.search_bar{display:table;vertical-align:middle;width:90%;height:35px;max-width:500px;margin:0 auto;background-color:#fff;box-shadow: 0px 3px rgba( 0, 0, 0, 0.1 );font-family: Arial;color: #444;-moz-border-radius: 2px;-webkit-border-radius: 2px;border-radius: 2px;}#search_submit{outline:none;height:37px;float:right;color:#404040;font-size:16px;font-weight:bold;border:none;background-color:transparent;}div.center{vertical-align:middle;height:100%;width:100%;max-height:300px; position: absolute; top:0; bottom: 0; left: 0; right: 0; margin: auto;}img.smaller{width:50%;max-width:300px;}.box { vertical-align:middle;position:relative; display: block; margin: 10px;padding-left:10px;padding-right:10px;padding-top:5px;padding-bottom:5px; background-color:#fff;box-shadow: 0px 3px rgba( 0, 0, 0, 0.1 );font-family: Arial;color: #444;font-size: 12px;-moz-border-radius: 2px;-webkit-border-radius: 2px;border-radius: 2px;}</style><body>" + "<div class=\"center\"><img class=\"smaller\" src=\""; public static final String MIDDLE = "\" ></br></br><form onsubmit=\"return search()\" class=\"search_bar\"><input " + "type=\"submit\" id=\"search_submit\" value=\"Search\" ><span><input class=\"search\" type=\"text\" value=\"\" id=\"search_input\" ></span></form> </div>" + "<script type=\"text/javascript\">function " + "search(){if(document.getElementById(\"search_input\").value != \"\"){window.location.href = \""; public static final String END = "\" + document.getElementById(\"search_input\").value;document.getElementById(\"search_input\").value = \"\";}return false;}</script></body></html>"; }
Changed homepage centering to be better
src/acr/browser/lightning/HomepageVariables.java
Changed homepage centering to be better
Java
lgpl-2.1
f80436399076a2a1b002b6b699a7b401f5375d49
0
hungerburg/exist,jessealama/exist,MjAbuz/exist,joewiz/exist,ambs/exist,windauer/exist,opax/exist,patczar/exist,RemiKoutcherawy/exist,wshager/exist,eXist-db/exist,joewiz/exist,RemiKoutcherawy/exist,RemiKoutcherawy/exist,olvidalo/exist,zwobit/exist,kohsah/exist,kohsah/exist,wolfgangmm/exist,kohsah/exist,dizzzz/exist,lcahlander/exist,dizzzz/exist,jensopetersen/exist,MjAbuz/exist,kohsah/exist,shabanovd/exist,ambs/exist,lcahlander/exist,jessealama/exist,wolfgangmm/exist,jensopetersen/exist,wshager/exist,shabanovd/exist,shabanovd/exist,olvidalo/exist,olvidalo/exist,wolfgangmm/exist,RemiKoutcherawy/exist,RemiKoutcherawy/exist,eXist-db/exist,lcahlander/exist,joewiz/exist,jensopetersen/exist,olvidalo/exist,opax/exist,wshager/exist,shabanovd/exist,jessealama/exist,dizzzz/exist,shabanovd/exist,jessealama/exist,ljo/exist,kohsah/exist,joewiz/exist,MjAbuz/exist,zwobit/exist,zwobit/exist,lcahlander/exist,windauer/exist,RemiKoutcherawy/exist,wolfgangmm/exist,adamretter/exist,ljo/exist,ambs/exist,wolfgangmm/exist,adamretter/exist,ambs/exist,zwobit/exist,eXist-db/exist,opax/exist,wolfgangmm/exist,patczar/exist,jessealama/exist,zwobit/exist,patczar/exist,ljo/exist,ambs/exist,hungerburg/exist,windauer/exist,eXist-db/exist,joewiz/exist,ambs/exist,lcahlander/exist,hungerburg/exist,windauer/exist,patczar/exist,jensopetersen/exist,eXist-db/exist,eXist-db/exist,zwobit/exist,joewiz/exist,patczar/exist,wshager/exist,ljo/exist,opax/exist,adamretter/exist,wshager/exist,jensopetersen/exist,adamretter/exist,kohsah/exist,dizzzz/exist,hungerburg/exist,adamretter/exist,opax/exist,wshager/exist,olvidalo/exist,windauer/exist,MjAbuz/exist,adamretter/exist,jessealama/exist,dizzzz/exist,ljo/exist,ljo/exist,MjAbuz/exist,hungerburg/exist,patczar/exist,shabanovd/exist,lcahlander/exist,MjAbuz/exist,jensopetersen/exist,windauer/exist,dizzzz/exist
/* * eXist Open Source Native XML Database * Copyright (C) 2003-2007 The eXist Project * http://exist-db.org * * 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 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU 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, write to the Free Software Foundation * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * $Id$ */ package org.exist.xmldb; import java.io.File; import java.io.IOException; import java.io.StringWriter; import java.util.Date; import java.util.Properties; import javax.xml.transform.TransformerException; import org.exist.EXistException; import org.exist.dom.DocumentImpl; import org.exist.dom.NodeProxy; import org.exist.dom.XMLUtil; import org.exist.memtree.AttributeImpl; import org.exist.memtree.NodeImpl; import org.exist.numbering.NodeId; import org.exist.security.Permission; import org.exist.security.User; import org.exist.storage.BrokerPool; import org.exist.storage.DBBroker; import org.exist.storage.lock.Lock; import org.exist.storage.serializers.Serializer; import org.exist.storage.txn.TransactionManager; import org.exist.storage.txn.Txn; import org.exist.util.LockException; import org.exist.util.MimeType; import org.exist.util.serializer.DOMSerializer; import org.exist.util.serializer.DOMStreamer; import org.exist.util.serializer.SAXSerializer; import org.exist.util.serializer.SerializerPool; import org.exist.xquery.XPathException; import org.exist.xquery.value.AtomicValue; import org.exist.xquery.value.NodeValue; import org.exist.xquery.value.StringValue; import org.exist.xquery.value.Type; import org.w3c.dom.DocumentType; import org.w3c.dom.Node; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.ext.LexicalHandler; import org.xmldb.api.base.Collection; import org.xmldb.api.base.ErrorCodes; import org.xmldb.api.base.XMLDBException; import org.xmldb.api.modules.XMLResource; /** * Local implementation of XMLResource. */ public class LocalXMLResource extends AbstractEXistResource implements XMLResource { //protected DocumentImpl document = null; protected NodeProxy proxy = null; protected Properties outputProperties = null; protected LexicalHandler lexicalHandler = null; // those are the different types of content this resource // may have to deal with protected String content = null; protected File file = null; protected Node root = null; protected AtomicValue value = null; protected Date datecreated= null; protected Date datemodified= null; public LocalXMLResource(User user, BrokerPool pool, LocalCollection parent, XmldbURI did) throws XMLDBException { super(user, pool, parent, did, MimeType.XML_TYPE.getName()); } public LocalXMLResource(User user, BrokerPool pool, LocalCollection parent, NodeProxy p) throws XMLDBException { this(user, pool, parent, p.getDocument().getFileURI()); this.proxy = p; } public Object getContent() throws XMLDBException { if (content != null) { System.out.println("LocaXML string 0 " + content); return content; } // Case 1: content is an external DOM node else if (root != null && !(root instanceof NodeValue)) { StringWriter writer = new StringWriter(); DOMSerializer serializer = new DOMSerializer(writer, getProperties()); try { serializer.serialize(root); content = writer.toString(); } catch (TransformerException e) { throw new XMLDBException(ErrorCodes.INVALID_RESOURCE, e .getMessage(), e); } return content; // Case 2: content is an atomic value } else if (value != null) { try { if (Type.subTypeOf(value.getType(),Type.STRING)) { return ((StringValue)value).getStringValue(true); } else { return value.getStringValue(); } } catch (XPathException e) { throw new XMLDBException(ErrorCodes.INVALID_RESOURCE, e .getMessage(), e); } // Case 3: content is a file } else if (file != null) { try { content = XMLUtil.readFile(file); return content; } catch (IOException e) { throw new XMLDBException(ErrorCodes.VENDOR_ERROR, "error while reading resource contents", e); } // Case 4: content is a document or internal node } else { DocumentImpl document = null; DBBroker broker = null; try { broker = pool.get(user); Serializer serializer = broker.getSerializer(); serializer.setUser(user); serializer.setProperties(getProperties()); if (root != null) { content = serializer.serialize((NodeValue) root); } else if (proxy != null) { content = serializer.serialize(proxy); } else { document = openDocument(broker, Lock.READ_LOCK); if (!document.getPermissions().validate(user, Permission.READ)) throw new XMLDBException(ErrorCodes.PERMISSION_DENIED, "permission denied to read resource"); content = serializer.serialize(document); } return content; } catch (SAXException saxe) { saxe.printStackTrace(); throw new XMLDBException(ErrorCodes.VENDOR_ERROR, saxe .getMessage(), saxe); } catch (EXistException e) { throw new XMLDBException(ErrorCodes.VENDOR_ERROR, e .getMessage(), e); } catch (Exception e) { e.printStackTrace(); throw new XMLDBException(ErrorCodes.VENDOR_ERROR, e .getMessage(), e); } finally { closeDocument(document, Lock.READ_LOCK); pool.release(broker); } } } public Node getContentAsDOM() throws XMLDBException { if (root != null) { if(root instanceof NodeImpl) { ((NodeImpl)root).expand(); } return root; } else if (value != null) { throw new XMLDBException(ErrorCodes.VENDOR_ERROR, "cannot return an atomic value as DOM node"); } else { DocumentImpl document = null; DBBroker broker = null; try { broker = pool.get(user); document = getDocument(broker, Lock.READ_LOCK); if (!document.getPermissions().validate(user, Permission.READ)) throw new XMLDBException(ErrorCodes.PERMISSION_DENIED, "permission denied to read resource"); if (proxy != null) return document.getNode(proxy); // <[email protected]> return a full to get root PI and comments return document; } catch (EXistException e) { throw new XMLDBException(ErrorCodes.VENDOR_ERROR, e .getMessage(), e); } finally { parent.getCollection().releaseDocument(document, Lock.READ_LOCK); pool.release(broker); } } } public void getContentAsSAX(ContentHandler handler) throws XMLDBException { DBBroker broker = null; // case 1: content is an external DOM node if (root != null && !(root instanceof NodeValue)) { try { String option = parent.properties.getProperty( Serializer.GENERATE_DOC_EVENTS, "false"); DOMStreamer streamer = (DOMStreamer) SerializerPool.getInstance().borrowObject(DOMStreamer.class); streamer.setContentHandler(handler); streamer.setLexicalHandler(lexicalHandler); streamer.serialize(root, option.equalsIgnoreCase("true")); SerializerPool.getInstance().returnObject(streamer); } catch (Exception e) { throw new XMLDBException(ErrorCodes.INVALID_RESOURCE, e .getMessage(), e); } // case 2: content is an atomic value } else if (value != null) { try { broker = pool.get(user); value.toSAX(broker, handler, getProperties()); } catch (EXistException e) { throw new XMLDBException(ErrorCodes.VENDOR_ERROR, e .getMessage(), e); } catch (SAXException e) { throw new XMLDBException(ErrorCodes.VENDOR_ERROR, e .getMessage(), e); } finally { pool.release(broker); } // case 3: content is an internal node or a document } else { try { broker = pool.get(user); Serializer serializer = broker.getSerializer(); serializer.setUser(user); serializer.setProperties(getProperties()); serializer.setSAXHandlers(handler, lexicalHandler); if (root != null) { serializer.toSAX((NodeValue) root); } else if (proxy != null) { serializer.toSAX(proxy); } else { DocumentImpl document = null; try { document = openDocument(broker, Lock.READ_LOCK); if (!document.getPermissions().validate(user, Permission.READ)) throw new XMLDBException(ErrorCodes.PERMISSION_DENIED, "permission denied to read resource"); serializer.toSAX(document); } finally { closeDocument(document, Lock.READ_LOCK); } } } catch (EXistException e) { throw new XMLDBException(ErrorCodes.VENDOR_ERROR, e .getMessage(), e); } catch (SAXException e) { throw new XMLDBException(ErrorCodes.VENDOR_ERROR, e .getMessage(), e); } finally { pool.release(broker); } } } //TODO: use xmldbURI? public String getDocumentId() throws XMLDBException { return docId.toString(); } //TODO: use xmldbURI? public String getId() throws XMLDBException { return docId.toString(); } public Collection getParentCollection() throws XMLDBException { if (parent == null) throw new XMLDBException(ErrorCodes.VENDOR_ERROR, "collection parent is null"); return parent; } public String getResourceType() throws XMLDBException { return "XMLResource"; } public Date getCreationTime() throws XMLDBException { DBBroker broker = null; try { broker = pool.get(user); DocumentImpl document = getDocument(broker, Lock.NO_LOCK); if (!document.getPermissions().validate(user, Permission.READ)) throw new XMLDBException(ErrorCodes.PERMISSION_DENIED, "permission denied to read resource"); return new Date(document.getMetadata().getCreated()); } catch (EXistException e) { throw new XMLDBException(ErrorCodes.UNKNOWN_ERROR, e.getMessage(), e); } finally { pool.release(broker); } } public Date getLastModificationTime() throws XMLDBException { DBBroker broker = null; try { broker = pool.get(user); DocumentImpl document = getDocument(broker, Lock.NO_LOCK); if (!document.getPermissions().validate(user, Permission.READ)) throw new XMLDBException(ErrorCodes.PERMISSION_DENIED, "permission denied to read resource"); return new Date(document.getMetadata().getLastModified()); } catch (EXistException e) { throw new XMLDBException(ErrorCodes.UNKNOWN_ERROR, e.getMessage(), e); } finally { pool.release(broker); } } /* (non-Javadoc) * @see org.exist.xmldb.EXistResource#getContentLength() */ public int getContentLength() throws XMLDBException { DBBroker broker = null; try { broker = pool.get(user); DocumentImpl document = getDocument(broker, Lock.NO_LOCK); if (!document.getPermissions().validate(user, Permission.READ)) throw new XMLDBException(ErrorCodes.PERMISSION_DENIED, "permission denied to read resource"); return document.getContentLength(); } catch (EXistException e) { throw new XMLDBException(ErrorCodes.UNKNOWN_ERROR, e.getMessage(), e); } finally { pool.release(broker); } } /** * Sets the content for this resource. If value is of type File, it is * directly passed to the parser when Collection.storeResource is called. * Otherwise the method tries to convert the value to String. * * Passing a File object should be preferred if the document is large. The * file's content will not be loaded into memory but directly passed to a * SAX parser. * * @param obj * the content value to set for the resource. * @exception XMLDBException * with expected error codes. <br /><code>ErrorCodes.VENDOR_ERROR</code> * for any vendor specific errors that occur. <br /> */ public void setContent(Object obj) throws XMLDBException { content = null; if (obj instanceof File) file = (File) obj; else if (obj instanceof AtomicValue) value = (AtomicValue) obj; else { content = obj.toString(); } } public void setContentAsDOM(Node root) throws XMLDBException { if (root instanceof AttributeImpl) throw new XMLDBException(ErrorCodes.WRONG_CONTENT_TYPE, "SENR0001: can not serialize a standalone attribute"); this.root = root; } public ContentHandler setContentAsSAX() throws XMLDBException { return new InternalXMLSerializer(); } private class InternalXMLSerializer extends SAXSerializer { public InternalXMLSerializer() { super(new StringWriter(), null); } /** * @see org.xml.sax.DocumentHandler#endDocument() */ public void endDocument() throws SAXException { super.endDocument(); content = getWriter().toString(); } } public boolean getSAXFeature(String arg0) throws SAXNotRecognizedException, SAXNotSupportedException { return false; } public void setSAXFeature(String arg0, boolean arg1) throws SAXNotRecognizedException, SAXNotSupportedException { } /* * (non-Javadoc) * * @see org.exist.xmldb.EXistResource#getPermissions() */ public Permission getPermissions() throws XMLDBException { DBBroker broker = null; try { broker = pool.get(user); DocumentImpl document = getDocument(broker, Lock.NO_LOCK); return document != null ? document.getPermissions() : null; } catch (EXistException e) { throw new XMLDBException(ErrorCodes.INVALID_RESOURCE, e.getMessage(), e); } finally { pool.release(broker); } } /* (non-Javadoc) * @see org.exist.xmldb.EXistResource#setLexicalHandler(org.xml.sax.ext.LexicalHandler) */ public void setLexicalHandler(LexicalHandler handler) { lexicalHandler = handler; } protected void setProperties(Properties properties) { this.outputProperties = properties; } private Properties getProperties() { return outputProperties == null ? parent.properties : outputProperties; } protected DocumentImpl getDocument(DBBroker broker, int lock) throws XMLDBException { DocumentImpl document = null; if(lock != Lock.NO_LOCK) { try { document = parent.getCollection().getDocumentWithLock(broker, docId, lock); } catch (LockException e) { throw new XMLDBException(ErrorCodes.PERMISSION_DENIED, "Failed to acquire lock on document " + docId); } } else { document = parent.getCollection().getDocument(broker, docId); } if (document == null) { throw new XMLDBException(ErrorCodes.INVALID_RESOURCE); } return document; } public NodeProxy getNode() throws XMLDBException { if(proxy != null) return proxy; DBBroker broker = null; try { broker = pool.get(user); DocumentImpl document = getDocument(broker, Lock.NO_LOCK); // this XMLResource represents a document return new NodeProxy(document, NodeId.DOCUMENT_NODE); } catch (EXistException e) { throw new XMLDBException(ErrorCodes.INVALID_RESOURCE, e.getMessage(), e); } finally { pool.release(broker); } } public DocumentType getDocType() throws XMLDBException { DBBroker broker = null; try { broker = pool.get(user); DocumentImpl document = getDocument(broker, Lock.NO_LOCK); if (!document.getPermissions().validate(user, Permission.READ)) throw new XMLDBException(ErrorCodes.PERMISSION_DENIED, "permission denied to read resource"); return document.getDoctype(); } catch (EXistException e) { throw new XMLDBException(ErrorCodes.UNKNOWN_ERROR, e.getMessage(), e); } finally { pool.release(broker); } } public void setDocType(DocumentType doctype) throws XMLDBException { DBBroker broker = null; DocumentImpl document = null; TransactionManager transact = pool.getTransactionManager(); Txn transaction = transact.beginTransaction(); try { broker = pool.get(user); document = openDocument(broker, Lock.WRITE_LOCK); if (document == null) { throw new EXistException("Resource " + document.getFileURI() + " not found"); } if (!document.getPermissions().validate(user, Permission.UPDATE)) throw new XMLDBException(ErrorCodes.PERMISSION_DENIED, "User is not allowed to lock resource " + document.getFileURI()); document.setDocumentType(doctype); broker.storeXMLResource(transaction, document); transact.commit(transaction); } catch (EXistException e) { transact.abort(transaction); throw new XMLDBException(ErrorCodes.UNKNOWN_ERROR, e.getMessage(), e); } finally { closeDocument(document, Lock.WRITE_LOCK); pool.release(broker); } } }
src/org/exist/xmldb/LocalXMLResource.java
/* * eXist Open Source Native XML Database * Copyright (C) 2003-2007 The eXist Project * http://exist-db.org * * 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 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU 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, write to the Free Software Foundation * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * $Id$ */ package org.exist.xmldb; import java.io.File; import java.io.IOException; import java.io.StringWriter; import java.util.Date; import java.util.Properties; import javax.xml.transform.TransformerException; import org.exist.EXistException; import org.exist.dom.DocumentImpl; import org.exist.dom.NodeProxy; import org.exist.dom.XMLUtil; import org.exist.memtree.AttributeImpl; import org.exist.memtree.NodeImpl; import org.exist.numbering.NodeId; import org.exist.security.Permission; import org.exist.security.User; import org.exist.storage.BrokerPool; import org.exist.storage.DBBroker; import org.exist.storage.lock.Lock; import org.exist.storage.serializers.Serializer; import org.exist.storage.txn.TransactionManager; import org.exist.storage.txn.Txn; import org.exist.util.LockException; import org.exist.util.MimeType; import org.exist.util.serializer.DOMSerializer; import org.exist.util.serializer.DOMStreamer; import org.exist.util.serializer.SAXSerializer; import org.exist.util.serializer.SerializerPool; import org.exist.xquery.XPathException; import org.exist.xquery.value.AtomicValue; import org.exist.xquery.value.NodeValue; import org.exist.xquery.value.StringValue; import org.w3c.dom.DocumentType; import org.w3c.dom.Node; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.ext.LexicalHandler; import org.xmldb.api.base.Collection; import org.xmldb.api.base.ErrorCodes; import org.xmldb.api.base.XMLDBException; import org.xmldb.api.modules.XMLResource; /** * Local implementation of XMLResource. */ public class LocalXMLResource extends AbstractEXistResource implements XMLResource { //protected DocumentImpl document = null; protected NodeProxy proxy = null; protected Properties outputProperties = null; protected LexicalHandler lexicalHandler = null; // those are the different types of content this resource // may have to deal with protected String content = null; protected File file = null; protected Node root = null; protected AtomicValue value = null; protected Date datecreated= null; protected Date datemodified= null; public LocalXMLResource(User user, BrokerPool pool, LocalCollection parent, XmldbURI did) throws XMLDBException { super(user, pool, parent, did, MimeType.XML_TYPE.getName()); } public LocalXMLResource(User user, BrokerPool pool, LocalCollection parent, NodeProxy p) throws XMLDBException { this(user, pool, parent, p.getDocument().getFileURI()); this.proxy = p; } public Object getContent() throws XMLDBException { if (content != null) { System.out.println("LocaXML string 0 " + content); return content; } // Case 1: content is an external DOM node else if (root != null && !(root instanceof NodeValue)) { StringWriter writer = new StringWriter(); DOMSerializer serializer = new DOMSerializer(writer, getProperties()); try { serializer.serialize(root); content = writer.toString(); } catch (TransformerException e) { throw new XMLDBException(ErrorCodes.INVALID_RESOURCE, e .getMessage(), e); } return content; // Case 2: content is an atomic value } else if (value != null) { try { if (value instanceof StringValue) { return ((StringValue)value).getStringValue(true); } else { return value.getStringValue(); } } catch (XPathException e) { throw new XMLDBException(ErrorCodes.INVALID_RESOURCE, e .getMessage(), e); } // Case 3: content is a file } else if (file != null) { try { content = XMLUtil.readFile(file); return content; } catch (IOException e) { throw new XMLDBException(ErrorCodes.VENDOR_ERROR, "error while reading resource contents", e); } // Case 4: content is a document or internal node } else { DocumentImpl document = null; DBBroker broker = null; try { broker = pool.get(user); Serializer serializer = broker.getSerializer(); serializer.setUser(user); serializer.setProperties(getProperties()); if (root != null) { content = serializer.serialize((NodeValue) root); } else if (proxy != null) { content = serializer.serialize(proxy); } else { document = openDocument(broker, Lock.READ_LOCK); if (!document.getPermissions().validate(user, Permission.READ)) throw new XMLDBException(ErrorCodes.PERMISSION_DENIED, "permission denied to read resource"); content = serializer.serialize(document); } return content; } catch (SAXException saxe) { saxe.printStackTrace(); throw new XMLDBException(ErrorCodes.VENDOR_ERROR, saxe .getMessage(), saxe); } catch (EXistException e) { throw new XMLDBException(ErrorCodes.VENDOR_ERROR, e .getMessage(), e); } catch (Exception e) { e.printStackTrace(); throw new XMLDBException(ErrorCodes.VENDOR_ERROR, e .getMessage(), e); } finally { closeDocument(document, Lock.READ_LOCK); pool.release(broker); } } } public Node getContentAsDOM() throws XMLDBException { if (root != null) { if(root instanceof NodeImpl) { ((NodeImpl)root).expand(); } return root; } else if (value != null) { throw new XMLDBException(ErrorCodes.VENDOR_ERROR, "cannot return an atomic value as DOM node"); } else { DocumentImpl document = null; DBBroker broker = null; try { broker = pool.get(user); document = getDocument(broker, Lock.READ_LOCK); if (!document.getPermissions().validate(user, Permission.READ)) throw new XMLDBException(ErrorCodes.PERMISSION_DENIED, "permission denied to read resource"); if (proxy != null) return document.getNode(proxy); // <[email protected]> return a full to get root PI and comments return document; } catch (EXistException e) { throw new XMLDBException(ErrorCodes.VENDOR_ERROR, e .getMessage(), e); } finally { parent.getCollection().releaseDocument(document, Lock.READ_LOCK); pool.release(broker); } } } public void getContentAsSAX(ContentHandler handler) throws XMLDBException { DBBroker broker = null; // case 1: content is an external DOM node if (root != null && !(root instanceof NodeValue)) { try { String option = parent.properties.getProperty( Serializer.GENERATE_DOC_EVENTS, "false"); DOMStreamer streamer = (DOMStreamer) SerializerPool.getInstance().borrowObject(DOMStreamer.class); streamer.setContentHandler(handler); streamer.setLexicalHandler(lexicalHandler); streamer.serialize(root, option.equalsIgnoreCase("true")); SerializerPool.getInstance().returnObject(streamer); } catch (Exception e) { throw new XMLDBException(ErrorCodes.INVALID_RESOURCE, e .getMessage(), e); } // case 2: content is an atomic value } else if (value != null) { try { broker = pool.get(user); value.toSAX(broker, handler, getProperties()); } catch (EXistException e) { throw new XMLDBException(ErrorCodes.VENDOR_ERROR, e .getMessage(), e); } catch (SAXException e) { throw new XMLDBException(ErrorCodes.VENDOR_ERROR, e .getMessage(), e); } finally { pool.release(broker); } // case 3: content is an internal node or a document } else { try { broker = pool.get(user); Serializer serializer = broker.getSerializer(); serializer.setUser(user); serializer.setProperties(getProperties()); serializer.setSAXHandlers(handler, lexicalHandler); if (root != null) { serializer.toSAX((NodeValue) root); } else if (proxy != null) { serializer.toSAX(proxy); } else { DocumentImpl document = null; try { document = openDocument(broker, Lock.READ_LOCK); if (!document.getPermissions().validate(user, Permission.READ)) throw new XMLDBException(ErrorCodes.PERMISSION_DENIED, "permission denied to read resource"); serializer.toSAX(document); } finally { closeDocument(document, Lock.READ_LOCK); } } } catch (EXistException e) { throw new XMLDBException(ErrorCodes.VENDOR_ERROR, e .getMessage(), e); } catch (SAXException e) { throw new XMLDBException(ErrorCodes.VENDOR_ERROR, e .getMessage(), e); } finally { pool.release(broker); } } } //TODO: use xmldbURI? public String getDocumentId() throws XMLDBException { return docId.toString(); } //TODO: use xmldbURI? public String getId() throws XMLDBException { return docId.toString(); } public Collection getParentCollection() throws XMLDBException { if (parent == null) throw new XMLDBException(ErrorCodes.VENDOR_ERROR, "collection parent is null"); return parent; } public String getResourceType() throws XMLDBException { return "XMLResource"; } public Date getCreationTime() throws XMLDBException { DBBroker broker = null; try { broker = pool.get(user); DocumentImpl document = getDocument(broker, Lock.NO_LOCK); if (!document.getPermissions().validate(user, Permission.READ)) throw new XMLDBException(ErrorCodes.PERMISSION_DENIED, "permission denied to read resource"); return new Date(document.getMetadata().getCreated()); } catch (EXistException e) { throw new XMLDBException(ErrorCodes.UNKNOWN_ERROR, e.getMessage(), e); } finally { pool.release(broker); } } public Date getLastModificationTime() throws XMLDBException { DBBroker broker = null; try { broker = pool.get(user); DocumentImpl document = getDocument(broker, Lock.NO_LOCK); if (!document.getPermissions().validate(user, Permission.READ)) throw new XMLDBException(ErrorCodes.PERMISSION_DENIED, "permission denied to read resource"); return new Date(document.getMetadata().getLastModified()); } catch (EXistException e) { throw new XMLDBException(ErrorCodes.UNKNOWN_ERROR, e.getMessage(), e); } finally { pool.release(broker); } } /* (non-Javadoc) * @see org.exist.xmldb.EXistResource#getContentLength() */ public int getContentLength() throws XMLDBException { DBBroker broker = null; try { broker = pool.get(user); DocumentImpl document = getDocument(broker, Lock.NO_LOCK); if (!document.getPermissions().validate(user, Permission.READ)) throw new XMLDBException(ErrorCodes.PERMISSION_DENIED, "permission denied to read resource"); return document.getContentLength(); } catch (EXistException e) { throw new XMLDBException(ErrorCodes.UNKNOWN_ERROR, e.getMessage(), e); } finally { pool.release(broker); } } /** * Sets the content for this resource. If value is of type File, it is * directly passed to the parser when Collection.storeResource is called. * Otherwise the method tries to convert the value to String. * * Passing a File object should be preferred if the document is large. The * file's content will not be loaded into memory but directly passed to a * SAX parser. * * @param obj * the content value to set for the resource. * @exception XMLDBException * with expected error codes. <br /><code>ErrorCodes.VENDOR_ERROR</code> * for any vendor specific errors that occur. <br /> */ public void setContent(Object obj) throws XMLDBException { content = null; if (obj instanceof File) file = (File) obj; else if (obj instanceof AtomicValue) value = (AtomicValue) obj; else { content = obj.toString(); } } public void setContentAsDOM(Node root) throws XMLDBException { if (root instanceof AttributeImpl) throw new XMLDBException(ErrorCodes.WRONG_CONTENT_TYPE, "SENR0001: can not serialize a standalone attribute"); this.root = root; } public ContentHandler setContentAsSAX() throws XMLDBException { return new InternalXMLSerializer(); } private class InternalXMLSerializer extends SAXSerializer { public InternalXMLSerializer() { super(new StringWriter(), null); } /** * @see org.xml.sax.DocumentHandler#endDocument() */ public void endDocument() throws SAXException { super.endDocument(); content = getWriter().toString(); } } public boolean getSAXFeature(String arg0) throws SAXNotRecognizedException, SAXNotSupportedException { return false; } public void setSAXFeature(String arg0, boolean arg1) throws SAXNotRecognizedException, SAXNotSupportedException { } /* * (non-Javadoc) * * @see org.exist.xmldb.EXistResource#getPermissions() */ public Permission getPermissions() throws XMLDBException { DBBroker broker = null; try { broker = pool.get(user); DocumentImpl document = getDocument(broker, Lock.NO_LOCK); return document != null ? document.getPermissions() : null; } catch (EXistException e) { throw new XMLDBException(ErrorCodes.INVALID_RESOURCE, e.getMessage(), e); } finally { pool.release(broker); } } /* (non-Javadoc) * @see org.exist.xmldb.EXistResource#setLexicalHandler(org.xml.sax.ext.LexicalHandler) */ public void setLexicalHandler(LexicalHandler handler) { lexicalHandler = handler; } protected void setProperties(Properties properties) { this.outputProperties = properties; } private Properties getProperties() { return outputProperties == null ? parent.properties : outputProperties; } protected DocumentImpl getDocument(DBBroker broker, int lock) throws XMLDBException { DocumentImpl document = null; if(lock != Lock.NO_LOCK) { try { document = parent.getCollection().getDocumentWithLock(broker, docId, lock); } catch (LockException e) { throw new XMLDBException(ErrorCodes.PERMISSION_DENIED, "Failed to acquire lock on document " + docId); } } else { document = parent.getCollection().getDocument(broker, docId); } if (document == null) { throw new XMLDBException(ErrorCodes.INVALID_RESOURCE); } return document; } public NodeProxy getNode() throws XMLDBException { if(proxy != null) return proxy; DBBroker broker = null; try { broker = pool.get(user); DocumentImpl document = getDocument(broker, Lock.NO_LOCK); // this XMLResource represents a document return new NodeProxy(document, NodeId.DOCUMENT_NODE); } catch (EXistException e) { throw new XMLDBException(ErrorCodes.INVALID_RESOURCE, e.getMessage(), e); } finally { pool.release(broker); } } public DocumentType getDocType() throws XMLDBException { DBBroker broker = null; try { broker = pool.get(user); DocumentImpl document = getDocument(broker, Lock.NO_LOCK); if (!document.getPermissions().validate(user, Permission.READ)) throw new XMLDBException(ErrorCodes.PERMISSION_DENIED, "permission denied to read resource"); return document.getDoctype(); } catch (EXistException e) { throw new XMLDBException(ErrorCodes.UNKNOWN_ERROR, e.getMessage(), e); } finally { pool.release(broker); } } public void setDocType(DocumentType doctype) throws XMLDBException { DBBroker broker = null; DocumentImpl document = null; TransactionManager transact = pool.getTransactionManager(); Txn transaction = transact.beginTransaction(); try { broker = pool.get(user); document = openDocument(broker, Lock.WRITE_LOCK); if (document == null) { throw new EXistException("Resource " + document.getFileURI() + " not found"); } if (!document.getPermissions().validate(user, Permission.UPDATE)) throw new XMLDBException(ErrorCodes.PERMISSION_DENIED, "User is not allowed to lock resource " + document.getFileURI()); document.setDocumentType(doctype); broker.storeXMLResource(transaction, document); transact.commit(transaction); } catch (EXistException e) { transact.abort(transaction); throw new XMLDBException(ErrorCodes.UNKNOWN_ERROR, e.getMessage(), e); } finally { closeDocument(document, Lock.WRITE_LOCK); pool.release(broker); } } }
Missed to replace use of 'instanceof StringValue' in LocalXMLResource. svn path=/trunk/eXist/; revision=6404
src/org/exist/xmldb/LocalXMLResource.java
Missed to replace use of 'instanceof StringValue' in LocalXMLResource.
Java
lgpl-2.1
a9160d5abd767f0c1b6c1dd77b94f1853346ded6
0
KengoTODA/spotbugs,KengoTODA/spotbugs,sewe/spotbugs,sewe/spotbugs,spotbugs/spotbugs,johnscancella/spotbugs,johnscancella/spotbugs,spotbugs/spotbugs,KengoTODA/spotbugs,johnscancella/spotbugs,spotbugs/spotbugs,sewe/spotbugs,sewe/spotbugs,KengoTODA/spotbugs,spotbugs/spotbugs,johnscancella/spotbugs,spotbugs/spotbugs
/* * FindBugs - Find bugs in Java programs * Copyright (C) 2004 Dave Brosius <[email protected]> * Copyright (C) 2003-2006 University of Maryland * * This library 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 2.1 of the License, or (at your option) any later version. * * This library 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 library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.findbugs; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.bcel.Repository; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.CodeException; import org.apache.bcel.classfile.Constant; import org.apache.bcel.classfile.ConstantClass; import org.apache.bcel.classfile.ConstantDouble; import org.apache.bcel.classfile.ConstantFloat; import org.apache.bcel.classfile.ConstantInteger; import org.apache.bcel.classfile.ConstantLong; import org.apache.bcel.classfile.ConstantString; import org.apache.bcel.classfile.ConstantUtf8; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.LocalVariable; import org.apache.bcel.classfile.LocalVariableTable; import org.apache.bcel.classfile.Method; import org.apache.bcel.generic.BasicType; import org.apache.bcel.generic.Type; import sun.tools.tree.NewInstanceExpression; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.AnalysisFeatures; import edu.umd.cs.findbugs.ba.ClassMember; import edu.umd.cs.findbugs.ba.FieldSummary; import edu.umd.cs.findbugs.ba.XFactory; import edu.umd.cs.findbugs.ba.XField; import edu.umd.cs.findbugs.ba.XMethod; import edu.umd.cs.findbugs.classfile.CheckedAnalysisException; import edu.umd.cs.findbugs.classfile.Global; import edu.umd.cs.findbugs.classfile.IAnalysisCache; import edu.umd.cs.findbugs.classfile.MethodDescriptor; import edu.umd.cs.findbugs.classfile.engine.bcel.AnalysisFactory; import edu.umd.cs.findbugs.internalAnnotations.SlashedClassName; import edu.umd.cs.findbugs.util.ClassName; import edu.umd.cs.findbugs.util.Util; import edu.umd.cs.findbugs.visitclass.Constants2; import edu.umd.cs.findbugs.visitclass.DismantleBytecode; import edu.umd.cs.findbugs.visitclass.LVTHelper; import edu.umd.cs.findbugs.visitclass.PreorderVisitor; /** * tracks the types and numbers of objects that are currently on the operand stack * throughout the execution of method. To use, a detector should instantiate one for * each method, and call <p>stack.sawOpcode(this,seen);</p> at the bottom of their sawOpcode method. * at any point you can then inspect the stack and see what the types of objects are on * the stack, including constant values if they were pushed. The types described are of * course, only the static types. * There are some outstanding opcodes that have yet to be implemented, I couldn't * find any code that actually generated these, so i didn't put them in because * I couldn't test them: * <ul> * <li>dup2_x2</li> * <li>jsr_w</li> * <li>wide</li> * </ul> */ public class OpcodeStack implements Constants2 { private static final boolean DEBUG = SystemProperties.getBoolean("ocstack.debug"); private static final boolean DEBUG2 = DEBUG; private List<Item> stack; private List<Item> lvValues; private List<Integer> lastUpdate; private boolean top; static class HttpParameterInjection { HttpParameterInjection(String parameterName, int pc) { this.parameterName = parameterName; this.pc = pc; } String parameterName; int pc; } private boolean seenTransferOfControl = false; private boolean useIterativeAnalysis = AnalysisContext.currentAnalysisContext().getBoolProperty(AnalysisFeatures.INTERATIVE_OPCODE_STACK_ANALYSIS); public static class Item { public static final int SIGNED_BYTE = 1; public static final int RANDOM_INT = 2; public static final int LOW_8_BITS_CLEAR = 3; public static final int HASHCODE_INT = 4; public static final int INTEGER_SUM = 5; public static final int AVERAGE_COMPUTED_USING_DIVISION = 6; public static final int FLOAT_MATH = 7; public static final int RANDOM_INT_REMAINDER = 8; public static final int HASHCODE_INT_REMAINDER = 9; public static final int FILE_SEPARATOR_STRING = 10; public static final int MATH_ABS = 11; public static final int NON_NEGATIVE = 12; public static final int NASTY_FLOAT_MATH = 13; public static final int FILE_OPENED_IN_APPEND_MODE = 14; public static final int SERVLET_REQUEST_TAINTED = 15; public static final int NEWLY_ALLOCATED = 16; public static final int ZERO_MEANS_NULL = 17; public static final int NONZERO_MEANS_NULL = 18; private static final int IS_INITIAL_PARAMETER_FLAG=1; private static final int COULD_BE_ZERO_FLAG = 2; private static final int IS_NULL_FLAG = 4; public static final Object UNKNOWN = null; private int specialKind; private String signature; private Object constValue = UNKNOWN; private @CheckForNull ClassMember source; private int pc = -1; private int flags; private int registerNumber = -1; private Object userValue = null; private HttpParameterInjection injection = null; private int fieldLoadedFromRegister = -1; public int getSize() { if (signature.equals("J") || signature.equals("D")) return 2; return 1; } public int getPC() { return pc; } public void setPC(int pc) { this.pc = pc; } public boolean isWide() { return getSize() == 2; } @Override public int hashCode() { int r = 42 + specialKind; if (signature != null) r+= signature.hashCode(); r *= 31; if (constValue != null) r+= constValue.hashCode(); r *= 31; if (source != null) r+= source.hashCode(); r *= 31; r += flags; r *= 31; r += registerNumber; return r; } @Override public boolean equals(Object o) { if (!(o instanceof Item)) return false; Item that = (Item) o; return Util.nullSafeEquals(this.signature, that.signature) && Util.nullSafeEquals(this.constValue, that.constValue) && Util.nullSafeEquals(this.source, that.source) && Util.nullSafeEquals(this.userValue, that.userValue) && Util.nullSafeEquals(this.injection, that.injection) && this.specialKind == that.specialKind && this.registerNumber == that.registerNumber && this.flags == that.flags && this.fieldLoadedFromRegister == that.fieldLoadedFromRegister; } @Override public String toString() { StringBuffer buf = new StringBuffer("< "); buf.append(signature); switch(specialKind) { case SIGNED_BYTE: buf.append(", byte_array_load"); break; case RANDOM_INT: buf.append(", random_int"); break; case LOW_8_BITS_CLEAR: buf.append(", low8clear"); break; case HASHCODE_INT: buf.append(", hashcode_int"); break; case INTEGER_SUM: buf.append(", int_sum"); break; case AVERAGE_COMPUTED_USING_DIVISION: buf.append(", averageComputingUsingDivision"); break; case FLOAT_MATH: buf.append(", floatMath"); break; case NASTY_FLOAT_MATH: buf.append(", nastyFloatMath"); break; case HASHCODE_INT_REMAINDER: buf.append(", hashcode_int_rem"); break; case RANDOM_INT_REMAINDER: buf.append(", random_int_rem"); break; case FILE_SEPARATOR_STRING: buf.append(", file_separator_string"); break; case MATH_ABS: buf.append(", Math.abs"); break; case NON_NEGATIVE: buf.append(", non_negative"); break; case FILE_OPENED_IN_APPEND_MODE: buf.append(", file opened in append mode"); break; case SERVLET_REQUEST_TAINTED: buf.append(", servlet request tainted"); break; case NEWLY_ALLOCATED: buf.append(", new"); break; case ZERO_MEANS_NULL: buf.append(", zero means null"); break; case NONZERO_MEANS_NULL: buf.append(", nonzero means null"); break; case 0 : break; default: buf.append(", #" + specialKind); break; } if (constValue != UNKNOWN) { if (constValue instanceof String) { buf.append(", \""); buf.append(constValue); buf.append("\""); } else { buf.append(", "); buf.append(constValue); } } if (source instanceof XField) { buf.append(", "); if (fieldLoadedFromRegister != -1) buf.append(fieldLoadedFromRegister).append(':'); buf.append(source); } if (source instanceof XMethod) { buf.append(", return value from "); buf.append(source); } if (isInitialParameter()) { buf.append(", IP"); } if (isNull()) { buf.append(", isNull"); } if (registerNumber != -1) { buf.append(", r"); buf.append(registerNumber); } if (isCouldBeZero()) buf.append(", cbz"); buf.append(" >"); return buf.toString(); } public static Item merge(Item i1, Item i2) { if (i1 == null) return i2; if (i2 == null) return i1; if (i1.equals(i2)) return i1; Item m = new Item(); m.flags = i1.flags & i2.flags; m.setCouldBeZero(i1.isCouldBeZero() || i2.isCouldBeZero()); if (i1.pc == i2.pc) m.pc = i1.pc; if (Util.nullSafeEquals(i1.signature, i2.signature)) m.signature = i1.signature; else if (i1.isNull()) m.signature = i2.signature; else if (i2.isNull()) m.signature = i1.signature; if (Util.nullSafeEquals(i1.constValue, i2.constValue)) m.constValue = i1.constValue; if (Util.nullSafeEquals(i1.source, i2.source)) { m.source = i1.source; } else if ("".equals(i1.constValue)) m.source = i2.source; else if ("".equals(i2.constValue)) m.source = i1.source; if (Util.nullSafeEquals(i1.userValue, i2.userValue)) m.userValue = i1.userValue; if (i1.registerNumber == i2.registerNumber) m.registerNumber = i1.registerNumber; if (i1.fieldLoadedFromRegister == i2.fieldLoadedFromRegister) m.fieldLoadedFromRegister = i1.fieldLoadedFromRegister; if (i1.specialKind == SERVLET_REQUEST_TAINTED) { m.specialKind = SERVLET_REQUEST_TAINTED; m.injection = i1.injection; } else if (i2.specialKind == SERVLET_REQUEST_TAINTED) { m.specialKind = SERVLET_REQUEST_TAINTED; m.injection = i2.injection; } else if (i1.specialKind == i2.specialKind) m.specialKind = i1.specialKind; else if (i1.specialKind == NASTY_FLOAT_MATH || i2.specialKind == NASTY_FLOAT_MATH) m.specialKind = NASTY_FLOAT_MATH; else if (i1.specialKind == FLOAT_MATH || i2.specialKind == FLOAT_MATH) m.specialKind = FLOAT_MATH; if (DEBUG) System.out.println("Merge " + i1 + " and " + i2 + " gives " + m); return m; } public Item(String signature, int constValue) { this(signature, (Object)(Integer)constValue); } public Item(String signature) { this(signature, UNKNOWN); } public Item(Item it) { this.signature = it.signature; this.constValue = it.constValue; this.source = it.source; this.registerNumber = it.registerNumber; this.userValue = it.userValue; this.injection = it.injection; this.flags = it.flags; this.specialKind = it.specialKind; this.pc = it.pc; } public Item(Item it, int reg) { this(it); this.registerNumber = reg; } public Item(String signature, FieldAnnotation f) { this.signature = signature; if (f != null) source = XFactory.createXField(f); fieldLoadedFromRegister = -1; } public Item(String signature, FieldAnnotation f, int fieldLoadedFromRegister) { this.signature = signature; if (f != null) source = XFactory.createXField(f); this.fieldLoadedFromRegister = fieldLoadedFromRegister; } public int getFieldLoadedFromRegister() { return fieldLoadedFromRegister; } public void setLoadedFromField(XField f, int fieldLoadedFromRegister) { source = f; this.fieldLoadedFromRegister = fieldLoadedFromRegister; this.registerNumber = -1; } public @CheckForNull String getHttpParameterName() { if (!isServletParameterTainted()) throw new IllegalStateException(); if (injection == null) return null; return injection.parameterName; } public int getInjectionPC() { if (!isServletParameterTainted()) throw new IllegalStateException(); if (injection == null) return -1; return injection.pc; } public Item(String signature, Object constantValue) { this.signature = signature; constValue = constantValue; if (constantValue instanceof Integer) { int value = (Integer) constantValue; if (value != 0 && (value & 0xff) == 0) specialKind = LOW_8_BITS_CLEAR; if (value == 0) setCouldBeZero(true); } else if (constantValue instanceof Long) { long value = (Long) constantValue; if (value != 0 && (value & 0xff) == 0) specialKind = LOW_8_BITS_CLEAR; if (value == 0) setCouldBeZero(true); } } public Item() { signature = "Ljava/lang/Object;"; constValue = null; setNull(true); } public static Item nullItem(String signature) { Item item = new Item(signature); item.constValue = null; item.setNull(true); return item; } /** Returns null for primitive and arrays */ public @CheckForNull JavaClass getJavaClass() throws ClassNotFoundException { String baseSig; try { if (isPrimitive() || isArray()) return null; baseSig = signature; if (baseSig.length() == 0) return null; baseSig = baseSig.substring(1, baseSig.length() - 1); baseSig = baseSig.replace('/', '.'); return Repository.lookupClass(baseSig); } catch (RuntimeException e) { e.printStackTrace(); throw e; } } public boolean isArray() { return signature.startsWith("["); } public String getElementSignature() { if (!isArray()) return signature; else { int pos = 0; int len = signature.length(); while (pos < len) { if (signature.charAt(pos) != '[') break; pos++; } return signature.substring(pos); } } public boolean isNonNegative() { if (specialKind == NON_NEGATIVE) return true; if (constValue instanceof Number) { double value = ((Number) constValue).doubleValue(); return value >= 0; } return false; } public boolean isPrimitive() { return !signature.startsWith("L") && !signature.startsWith("["); } public int getRegisterNumber() { return registerNumber; } public String getSignature() { return signature; } /** * Returns a constant value for this Item, if known. * NOTE: if the value is a constant Class object, the constant value returned is the name of the class. */ public Object getConstant() { return constValue; } /** Use getXField instead */ @Deprecated public FieldAnnotation getFieldAnnotation() { return FieldAnnotation.fromXField(getXField()); } public XField getXField() { if (source instanceof XField) return (XField) source; return null; } /** * @param specialKind The specialKind to set. */ public void setSpecialKind(int specialKind) { this.specialKind = specialKind; } /** * @return Returns the specialKind. */ public int getSpecialKind() { return specialKind; } /** * @return Returns the specialKind. */ public boolean isBooleanNullnessValue() { return specialKind == ZERO_MEANS_NULL || specialKind == NONZERO_MEANS_NULL; } /** * attaches a detector specified value to this item * * @param value the custom value to set */ public void setUserValue(Object value) { userValue = value; } /** * * @return if this value is the return value of a method, give the method * invoked */ public @CheckForNull XMethod getReturnValueOf() { if (source instanceof XMethod) return (XMethod) source; return null; } public boolean couldBeZero() { return isCouldBeZero(); } public boolean mustBeZero() { Object value = getConstant(); return value instanceof Number && ((Number)value).intValue() == 0; } /** * gets the detector specified value for this item * * @return the custom value */ public Object getUserValue() { return userValue; } public boolean isServletParameterTainted() { return getSpecialKind() == Item.SERVLET_REQUEST_TAINTED; } public void setServletParameterTainted() { setSpecialKind(Item.SERVLET_REQUEST_TAINTED); } public boolean valueCouldBeNegative() { return !isNonNegative() && (getSpecialKind() == Item.RANDOM_INT || getSpecialKind() == Item.SIGNED_BYTE || getSpecialKind() == Item.HASHCODE_INT || getSpecialKind() == Item.RANDOM_INT_REMAINDER || getSpecialKind() == Item.HASHCODE_INT_REMAINDER); } /** * @param isInitialParameter The isInitialParameter to set. */ private void setInitialParameter(boolean isInitialParameter) { setFlag(isInitialParameter, IS_INITIAL_PARAMETER_FLAG); } /** * @return Returns the isInitialParameter. */ public boolean isInitialParameter() { return (flags & IS_INITIAL_PARAMETER_FLAG) != 0; } /** * @param couldBeZero The couldBeZero to set. */ private void setCouldBeZero(boolean couldBeZero) { setFlag(couldBeZero, COULD_BE_ZERO_FLAG); } /** * @return Returns the couldBeZero. */ private boolean isCouldBeZero() { return (flags & COULD_BE_ZERO_FLAG) != 0; } /** * @param isNull The isNull to set. */ private void setNull(boolean isNull) { setFlag(isNull, IS_NULL_FLAG); } private void setFlag(boolean value, int flagBit) { if (value) flags |= flagBit; else flags &= ~flagBit; } /** * @return Returns the isNull. */ public boolean isNull() { return (flags & IS_NULL_FLAG) != 0; } } @Override public String toString() { if (isTop()) return "TOP"; return stack.toString() + "::" + lvValues.toString(); } public OpcodeStack() { stack = new ArrayList<Item>(); lvValues = new ArrayList<Item>(); lastUpdate = new ArrayList<Integer>(); } boolean needToMerge = true; private boolean reachOnlyByBranch = false; public static String getExceptionSig(DismantleBytecode dbc, CodeException e) { if (e.getCatchType() == 0) return "Ljava/lang/Throwable;"; Constant c = dbc.getConstantPool().getConstant(e.getCatchType()); if (c instanceof ConstantClass) return "L"+((ConstantClass)c).getBytes(dbc.getConstantPool())+";"; return "Ljava/lang/Throwable;"; } public void mergeJumps(DismantleBytecode dbc) { if (!needToMerge) return; needToMerge = false; boolean stackUpdated = false; if (!isTop() && (convertJumpToOneZeroState == 3 || convertJumpToZeroOneState == 3)) { pop(); Item top = new Item("I"); top.setCouldBeZero(true); push(top); convertJumpToOneZeroState = convertJumpToZeroOneState = 0; stackUpdated = true; } List<Item> jumpEntry = null; if (jumpEntryLocations.get(dbc.getPC())) jumpEntry = jumpEntries.get(dbc.getPC()); if (jumpEntry != null) { setReachOnlyByBranch(false); List<Item> jumpStackEntry = jumpStackEntries.get(dbc.getPC()); if (DEBUG2) { System.out.println("XXXXXXX " + isReachOnlyByBranch()); System.out.println("merging lvValues at jump target " + dbc.getPC() + " -> " + Integer.toString(System.identityHashCode(jumpEntry),16) + " " + jumpEntry); System.out.println(" current lvValues " + lvValues); System.out.println(" merging stack entry " + jumpStackEntry); System.out.println(" current stack values " + stack); } if (isTop()) { lvValues = new ArrayList<Item>(jumpEntry); if (jumpStackEntry != null) stack = new ArrayList<Item>(jumpStackEntry); else stack.clear(); setTop(false); return; } if (isReachOnlyByBranch()) { setTop(false); lvValues = new ArrayList<Item>(jumpEntry); if (!stackUpdated) { if (jumpStackEntry != null) stack = new ArrayList<Item>(jumpStackEntry); else stack.clear(); } } else { setTop(false); mergeLists(lvValues, jumpEntry, false); if (!stackUpdated && jumpStackEntry != null) mergeLists(stack, jumpStackEntry, false); } if (DEBUG) System.out.println(" merged lvValues " + lvValues); } else if (isReachOnlyByBranch() && !stackUpdated) { stack.clear(); for(CodeException e : dbc.getCode().getExceptionTable()) { if (e.getHandlerPC() == dbc.getPC()) { push(new Item(getExceptionSig(dbc, e))); setReachOnlyByBranch(false); setTop(false); return; } } setTop(true); } } int convertJumpToOneZeroState = 0; int convertJumpToZeroOneState = 0; private void setLastUpdate(int reg, int pc) { while (lastUpdate.size() <= reg) lastUpdate.add(0); lastUpdate.set(reg, pc); } public int getLastUpdate(int reg) { if (lastUpdate.size() <= reg) return 0; return lastUpdate.get(reg); } public int getNumLastUpdates() { return lastUpdate.size(); } boolean zeroOneComing = false; boolean oneMeansNull; public void sawOpcode(DismantleBytecode dbc, int seen) { int register; String signature; Item it, it2, it3; Constant cons; if (dbc.isRegisterStore()) setLastUpdate(dbc.getRegisterOperand(), dbc.getPC()); if (zeroOneComing) { top = false; OpcodeStack.Item item = new Item("I"); if (oneMeansNull) item.setSpecialKind(Item.NONZERO_MEANS_NULL); else item.setSpecialKind(Item.ZERO_MEANS_NULL); item.setPC(dbc.getPC() - 7); item.setCouldBeZero(true); jumpEntries.remove(dbc.getPC()+1); jumpStackEntries.remove(dbc.getPC()+1); push(item); convertJumpToOneZeroState = convertJumpToZeroOneState = 0; zeroOneComing= false; if (DEBUG) System.out.println("Updated to " + this); return; } mergeJumps(dbc); needToMerge = true; try { if (isTop()) { encountedTop = true; return; } if (seen == GOTO) { int nextPC = dbc.getPC() + 3; if (nextPC <= dbc.getMaxPC()) { int prevOpcode1 = dbc.getPrevOpcode(1); int prevOpcode2 = dbc.getPrevOpcode(2); try { int nextOpcode = dbc.getCodeByte(dbc.getPC() + 3); if ((prevOpcode1 == ICONST_0 || prevOpcode1 == ICONST_1) && (prevOpcode2 == IFNULL || prevOpcode2 == IFNONNULL) && (nextOpcode == ICONST_0 || nextOpcode == ICONST_1) && prevOpcode1 != nextOpcode) { oneMeansNull = prevOpcode1 == ICONST_0; if (prevOpcode2 != IFNULL) oneMeansNull = !oneMeansNull; zeroOneComing = true; } } catch(ArrayIndexOutOfBoundsException e) { throw e; // throw new ArrayIndexOutOfBoundsException(nextPC + " " + dbc.getMaxPC()); } } } switch (seen) { case ICONST_1: convertJumpToOneZeroState = 1; break; case GOTO: if (convertJumpToOneZeroState == 1 && dbc.getBranchOffset() == 4) convertJumpToOneZeroState = 2; else convertJumpToOneZeroState = 0; break; case ICONST_0: if (convertJumpToOneZeroState == 2) convertJumpToOneZeroState = 3; else convertJumpToOneZeroState = 0; break; default:convertJumpToOneZeroState = 0; } switch (seen) { case ICONST_0: convertJumpToZeroOneState = 1; break; case GOTO: if (convertJumpToZeroOneState == 1 && dbc.getBranchOffset() == 4) convertJumpToZeroOneState = 2; else convertJumpToZeroOneState = 0; break; case ICONST_1: if (convertJumpToZeroOneState == 2) convertJumpToZeroOneState = 3; else convertJumpToZeroOneState = 0; break; default:convertJumpToZeroOneState = 0; } switch (seen) { case ALOAD: pushByLocalObjectLoad(dbc, dbc.getRegisterOperand()); break; case ALOAD_0: case ALOAD_1: case ALOAD_2: case ALOAD_3: pushByLocalObjectLoad(dbc, seen - ALOAD_0); break; case DLOAD: pushByLocalLoad("D", dbc.getRegisterOperand()); break; case DLOAD_0: case DLOAD_1: case DLOAD_2: case DLOAD_3: pushByLocalLoad("D", seen - DLOAD_0); break; case FLOAD: pushByLocalLoad("F", dbc.getRegisterOperand()); break; case FLOAD_0: case FLOAD_1: case FLOAD_2: case FLOAD_3: pushByLocalLoad("F", seen - FLOAD_0); break; case ILOAD: pushByLocalLoad("I", dbc.getRegisterOperand()); break; case ILOAD_0: case ILOAD_1: case ILOAD_2: case ILOAD_3: pushByLocalLoad("I", seen - ILOAD_0); break; case LLOAD: pushByLocalLoad("J", dbc.getRegisterOperand()); break; case LLOAD_0: case LLOAD_1: case LLOAD_2: case LLOAD_3: pushByLocalLoad("J", seen - LLOAD_0); break; case GETSTATIC: { FieldSummary fieldSummary = AnalysisContext.currentAnalysisContext().getFieldSummary(); XField fieldOperand = dbc.getXFieldOperand(); if (fieldOperand != null && fieldSummary.isComplete() && !fieldOperand.isPublic()) { OpcodeStack.Item item = fieldSummary.getSummary(fieldOperand); if (item != null) { Item itm = new Item(item); itm.setLoadedFromField(fieldOperand, Integer.MAX_VALUE); push(itm); break; } } FieldAnnotation field = FieldAnnotation.fromReferencedField(dbc); Item i = new Item(dbc.getSigConstantOperand(), field, Integer.MAX_VALUE); if (field.getFieldName().equals("separator") && field.getClassName().equals("java.io.File")) { i.setSpecialKind(Item.FILE_SEPARATOR_STRING); } push(i); break; } case LDC: case LDC_W: case LDC2_W: cons = dbc.getConstantRefOperand(); pushByConstant(dbc, cons); break; case INSTANCEOF: pop(); push(new Item("I")); break; case IFEQ: case IFNE: case IFLT: case IFLE: case IFGT: case IFGE: case IFNONNULL: case IFNULL: seenTransferOfControl = true; { Item top = pop(); // if we see a test comparing a special negative value with 0, // reset all other such values on the opcode stack if (top.valueCouldBeNegative() && (seen == IFLT || seen == IFLE || seen == IFGT || seen == IFGE)) { int specialKind = top.getSpecialKind(); for(Item item : stack) if (item != null && item.getSpecialKind() == specialKind) item.setSpecialKind(0); for(Item item : lvValues) if (item != null && item.getSpecialKind() == specialKind) item.setSpecialKind(0); } } addJumpValue(dbc.getPC(), dbc.getBranchTarget()); break; case LOOKUPSWITCH: case TABLESWITCH: seenTransferOfControl = true; setReachOnlyByBranch(true); pop(); addJumpValue(dbc.getPC(), dbc.getBranchTarget()); int pc = dbc.getBranchTarget() - dbc.getBranchOffset(); for(int offset : dbc.getSwitchOffsets()) addJumpValue(dbc.getPC(), offset+pc); break; case ARETURN: case DRETURN: case FRETURN: case IRETURN: case LRETURN: seenTransferOfControl = true; setReachOnlyByBranch(true); pop(); break; case MONITORENTER: case MONITOREXIT: case POP: case PUTSTATIC: pop(); break; case IF_ACMPEQ: case IF_ACMPNE: case IF_ICMPEQ: case IF_ICMPNE: case IF_ICMPLT: case IF_ICMPLE: case IF_ICMPGT: case IF_ICMPGE: { seenTransferOfControl = true; pop(2); int branchTarget = dbc.getBranchTarget(); addJumpValue(dbc.getPC(), branchTarget); break; } case POP2: it = pop(); if (it.getSize() == 1) pop(); break; case PUTFIELD: pop(2); break; case IALOAD: case SALOAD: pop(2); push(new Item("I")); break; case DUP: handleDup(); break; case DUP2: handleDup2(); break; case DUP_X1: handleDupX1(); break; case DUP_X2: handleDupX2(); break; case DUP2_X1: handleDup2X1(); break; case DUP2_X2: handleDup2X2(); break; case IINC: register = dbc.getRegisterOperand(); it = getLVValue( register ); it2 = new Item("I", dbc.getIntConstant()); pushByIntMath(dbc, IADD, it2, it); pushByLocalStore(register); break; case ATHROW: pop(); seenTransferOfControl = true; setReachOnlyByBranch(true); setTop(true); break; case CHECKCAST: { String castTo = dbc.getClassConstantOperand(); if (castTo.charAt(0) != '[') castTo = "L" + castTo + ";"; it = new Item(pop()); it.signature = castTo; push(it); break; } case NOP: break; case RET: case RETURN: seenTransferOfControl = true; setReachOnlyByBranch(true); break; case GOTO: case GOTO_W: seenTransferOfControl = true; setReachOnlyByBranch(true); addJumpValue(dbc.getPC(), dbc.getBranchTarget()); stack.clear(); setTop(true); break; case SWAP: handleSwap(); break; case ICONST_M1: case ICONST_0: case ICONST_1: case ICONST_2: case ICONST_3: case ICONST_4: case ICONST_5: push(new Item("I", (seen-ICONST_0))); break; case LCONST_0: case LCONST_1: push(new Item("J", (long)(seen-LCONST_0))); break; case DCONST_0: case DCONST_1: push(new Item("D", (double)(seen-DCONST_0))); break; case FCONST_0: case FCONST_1: case FCONST_2: push(new Item("F", (float)(seen-FCONST_0))); break; case ACONST_NULL: push(new Item()); break; case ASTORE: case DSTORE: case FSTORE: case ISTORE: case LSTORE: pushByLocalStore(dbc.getRegisterOperand()); break; case ASTORE_0: case ASTORE_1: case ASTORE_2: case ASTORE_3: pushByLocalStore(seen - ASTORE_0); break; case DSTORE_0: case DSTORE_1: case DSTORE_2: case DSTORE_3: pushByLocalStore(seen - DSTORE_0); break; case FSTORE_0: case FSTORE_1: case FSTORE_2: case FSTORE_3: pushByLocalStore(seen - FSTORE_0); break; case ISTORE_0: case ISTORE_1: case ISTORE_2: case ISTORE_3: pushByLocalStore(seen - ISTORE_0); break; case LSTORE_0: case LSTORE_1: case LSTORE_2: case LSTORE_3: pushByLocalStore(seen - LSTORE_0); break; case GETFIELD: { FieldSummary fieldSummary = AnalysisContext.currentAnalysisContext().getFieldSummary(); XField fieldOperand = dbc.getXFieldOperand(); if (fieldOperand != null && fieldSummary.isComplete() && !fieldOperand.isPublic()) { OpcodeStack.Item item = fieldSummary.getSummary(fieldOperand); if (item != null) { Item addr = pop(); Item itm = new Item(item); itm.setLoadedFromField(fieldOperand, addr.getRegisterNumber()); push(itm); break; } } Item item = pop(); int reg = item.getRegisterNumber(); push(new Item(dbc.getSigConstantOperand(), FieldAnnotation.fromReferencedField(dbc), reg)); } break; case ARRAYLENGTH: { pop(); Item v = new Item("I"); v.setSpecialKind(Item.NON_NEGATIVE); push(v); } break; case BALOAD: { pop(2); Item v = new Item("I"); v.setSpecialKind(Item.SIGNED_BYTE); push(v); break; } case CALOAD: pop(2); push(new Item("I")); break; case DALOAD: pop(2); push(new Item("D")); break; case FALOAD: pop(2); push(new Item("F")); break; case LALOAD: pop(2); push(new Item("J")); break; case AASTORE: case BASTORE: case CASTORE: case DASTORE: case FASTORE: case IASTORE: case LASTORE: case SASTORE: pop(3); break; case BIPUSH: case SIPUSH: push(new Item("I", (Integer)dbc.getIntConstant())); break; case IADD: case ISUB: case IMUL: case IDIV: case IAND: case IOR: case IXOR: case ISHL: case ISHR: case IREM: case IUSHR: it = pop(); it2 = pop(); pushByIntMath(dbc, seen, it2, it); break; case INEG: it = pop(); if (it.getConstant() instanceof Integer) { push(new Item("I", ( Integer)(-(Integer) it.getConstant()))); } else { push(new Item("I")); } break; case LNEG: it = pop(); if (it.getConstant() instanceof Long) { push(new Item("J", ( Long)(-(Long) it.getConstant()))); } else { push(new Item("J")); } break; case FNEG: it = pop(); if (it.getConstant() instanceof Float) { push(new Item("F", ( Float)(-(Float) it.getConstant()))); } else { push(new Item("F")); } break; case DNEG: it = pop(); if (it.getConstant() instanceof Double) { push(new Item("D", ( Double)(-(Double) it.getConstant()))); } else { push(new Item("D")); } break; case LADD: case LSUB: case LMUL: case LDIV: case LAND: case LOR: case LXOR: case LSHL: case LSHR: case LREM: case LUSHR: it = pop(); it2 = pop(); pushByLongMath(seen, it2, it); break; case LCMP: handleLcmp(); break; case FCMPG: case FCMPL: handleFcmp(seen); break; case DCMPG: case DCMPL: handleDcmp(seen); break; case FADD: case FSUB: case FMUL: case FDIV: case FREM: it = pop(); it2 = pop(); pushByFloatMath(seen, it, it2); break; case DADD: case DSUB: case DMUL: case DDIV: case DREM: it = pop(); it2 = pop(); pushByDoubleMath(seen, it, it2); break; case I2B: it = pop(); if (it.getConstant() != null) { it =new Item("I", (byte)constantToInt(it)); } else { it = new Item("I"); } it.setSpecialKind(Item.SIGNED_BYTE); push(it); break; case I2C: it = pop(); if (it.getConstant() != null) { it = new Item("I", (char)constantToInt(it)); } else { it = new Item("I"); } it.setSpecialKind(Item.NON_NEGATIVE); push(it); break; case I2L: case D2L: case F2L:{ it = pop(); Item newValue; if (it.getConstant() != null) { newValue = new Item("J", constantToLong(it)); } else { newValue = new Item("J"); } newValue.setSpecialKind(it.getSpecialKind()); push(newValue); } break; case I2S: it = pop(); if (it.getConstant() != null) { push(new Item("I", (short)constantToInt(it))); } else { push(new Item("I")); } break; case L2I: case D2I: case F2I: it = pop(); if (it.getConstant() != null) { push(new Item("I",constantToInt(it))); } else { push(new Item("I")); } break; case L2F: case D2F: case I2F: it = pop(); if (it.getConstant() != null) { push(new Item("F", (Float)(constantToFloat(it)))); } else { push(new Item("F")); } break; case F2D: case I2D: case L2D: it = pop(); if (it.getConstant() != null) { push(new Item("D", constantToDouble(it))); } else { push(new Item("D")); } break; case NEW: { Item item = new Item("L" + dbc.getClassConstantOperand() + ";", (Object) null); item.specialKind = Item.NEWLY_ALLOCATED; push(item); } break; case NEWARRAY: pop(); signature = "[" + BasicType.getType((byte)dbc.getIntConstant()).getSignature(); pushBySignature(signature, dbc); break; // According to the VM Spec 4.4.1, anewarray and multianewarray // can refer to normal class/interface types (encoded in // "internal form"), or array classes (encoded as signatures // beginning with "["). case ANEWARRAY: pop(); signature = dbc.getClassConstantOperand(); if (!signature.startsWith("[")) { signature = "[L" + signature + ";"; } pushBySignature(signature, dbc); break; case MULTIANEWARRAY: int dims = dbc.getIntConstant(); while ((dims--) > 0) { pop(); } signature = dbc.getClassConstantOperand(); if (!signature.startsWith("[")) { dims = dbc.getIntConstant(); signature = Util.repeat("[", dims) +"L" + signature + ";"; } pushBySignature(signature, dbc); break; case AALOAD: pop(); it = pop(); pushBySignature(it.getElementSignature(), dbc); break; case JSR: seenTransferOfControl = true; setReachOnlyByBranch(false); push(new Item("")); // push return address on stack addJumpValue(dbc.getPC(), dbc.getBranchTarget()); pop(); if (dbc.getBranchOffset() < 0) { // OK, backwards JSRs are weird; reset the stack. int stackSize = stack.size(); stack.clear(); for(int i = 0; i < stackSize; i++) stack.add(new Item()); } setTop(false); break; case INVOKEINTERFACE: case INVOKESPECIAL: case INVOKESTATIC: case INVOKEVIRTUAL: processMethodCall(dbc, seen); break; default: throw new UnsupportedOperationException("OpCode " + OPCODE_NAMES[seen] + " not supported " ); } } catch (RuntimeException e) { //If an error occurs, we clear the stack and locals. one of two things will occur. //Either the client will expect more stack items than really exist, and so they're condition check will fail, //or the stack will resync with the code. But hopefully not false positives String msg = "Error processing opcode " + OPCODE_NAMES[seen] + " @ " + dbc.getPC() + " in " + dbc.getFullyQualifiedMethodName(); AnalysisContext.logError(msg , e); if (DEBUG) e.printStackTrace(); clear(); } finally { if (DEBUG) { System.out.println(dbc.getNextPC() + "pc : " + OPCODE_NAMES[seen] + " stack depth: " + getStackDepth()); System.out.println(this); } } } /** * @param it * @return */ private int constantToInt(Item it) { return ((Number)it.getConstant()).intValue(); } /** * @param it * @return */ private float constantToFloat(Item it) { return ((Number)it.getConstant()).floatValue(); } /** * @param it * @return */ private double constantToDouble(Item it) { return ((Number)it.getConstant()).doubleValue(); } /** * @param it * @return */ private long constantToLong(Item it) { return ((Number)it.getConstant()).longValue(); } /** * handle dcmp * */ private void handleDcmp(int opcode) { Item it; Item it2; it = pop(); it2 = pop(); if ((it.getConstant() != null) && it2.getConstant() != null) { double d = (Double) it.getConstant(); double d2 = (Double) it.getConstant(); if (Double.isNaN(d) || Double.isNaN(d2)) { if (opcode == DCMPG) push(new Item("I", (Integer)(1))); else push(new Item("I", (Integer)(-1))); } if (d2 < d) push(new Item("I", (Integer) (-1) )); else if (d2 > d) push(new Item("I", (Integer)1)); else push(new Item("I", (Integer)0)); } else { push(new Item("I")); } } /** * handle fcmp * */ private void handleFcmp(int opcode) { Item it; Item it2; it = pop(); it2 = pop(); if ((it.getConstant() != null) && it2.getConstant() != null) { float f = (Float) it.getConstant(); float f2 = (Float) it.getConstant(); if (Float.isNaN(f) || Float.isNaN(f2)) { if (opcode == FCMPG) push(new Item("I", (Integer)(1))); else push(new Item("I", (Integer)(-1))); } if (f2 < f) push(new Item("I", (Integer)(-1))); else if (f2 > f) push(new Item("I", (Integer)(1))); else push(new Item("I", (Integer)(0))); } else { push(new Item("I")); } } /** * handle lcmp */ private void handleLcmp() { Item it; Item it2; it = pop(); it2 = pop(); if ((it.getConstant() != null) && it2.getConstant() != null) { long l = (Long) it.getConstant(); long l2 = (Long) it.getConstant(); if (l2 < l) push(new Item("I", (Integer)(-1))); else if (l2 > l) push(new Item("I", (Integer)(1))); else push(new Item("I", (Integer)(0))); } else { push(new Item("I")); } } /** * handle swap */ private void handleSwap() { Item i1 = pop(); Item i2 = pop(); push(i1); push(i2); } /** * handleDup */ private void handleDup() { Item it; it = pop(); push(it); push(it); } /** * handle dupX1 */ private void handleDupX1() { Item it; Item it2; it = pop(); it2 = pop(); push(it); push(it2); push(it); } /** * handle dup2 */ private void handleDup2() { Item it, it2; it = pop(); if (it.getSize() == 2) { push(it); push(it); } else { it2 = pop(); push(it2); push(it); push(it2); push(it); } } /** * handle Dup2x1 */ private void handleDup2X1() { String signature; Item it; Item it2; Item it3; it = pop(); it2 = pop(); signature = it.getSignature(); if (signature.equals("J") || signature.equals("D")) { push(it); push(it2); push(it); } else { it3 = pop(); push(it2); push(it); push(it3); push(it2); push(it); } } private void handleDup2X2() { String signature; Item it = pop(); Item it2 = pop(); if (it.isWide()) { if (it2.isWide()) { push(it); push(it2); push(it); } else { Item it3 = pop(); push(it); push(it3); push(it2); push(it); } } else { Item it3 = pop(); if (it3.isWide()) { push(it2); push(it); push(it3); push(it2); push(it); } else { Item it4 = pop(); push(it2); push(it); push(it4); push(it3); push(it2); push(it); } } } /** * Handle DupX2 */ private void handleDupX2() { String signature; Item it; Item it2; Item it3; it = pop(); it2 = pop(); signature = it2.getSignature(); if (signature.equals("J") || signature.equals("D")) { push(it); push(it2); push(it); } else { it3 = pop(); push(it); push(it3); push(it2); push(it); } } private void processMethodCall(DismantleBytecode dbc, int seen) { String clsName = dbc.getClassConstantOperand(); String methodName = dbc.getNameConstantOperand(); String signature = dbc.getSigConstantOperand(); String appenderValue = null; boolean servletRequestParameterTainted = false; boolean sawUnknownAppend = false; Item sbItem = null; boolean topIsTainted = getStackDepth() > 0 && getStackItem(0).isServletParameterTainted(); Item topItem = null; if (getStackDepth() > 0) topItem = getStackItem(0); //TODO: stack merging for trinaries kills the constant.. would be nice to maintain. if ("java/lang/StringBuffer".equals(clsName) || "java/lang/StringBuilder".equals(clsName)) { if ("<init>".equals(methodName)) { if ("(Ljava/lang/String;)V".equals(signature)) { Item i = getStackItem(0); appenderValue = (String)i.getConstant(); if (i.isServletParameterTainted()) servletRequestParameterTainted = true; } else if ("()V".equals(signature)) { appenderValue = ""; } } else if ("toString".equals(methodName) && getStackDepth() >= 1) { Item i = getStackItem(0); appenderValue = (String)i.getConstant(); if (i.isServletParameterTainted()) servletRequestParameterTainted = true; } else if ("append".equals(methodName)) { if (signature.indexOf("II)") == -1 && getStackDepth() >= 2) { sbItem = getStackItem(1); Item i = getStackItem(0); if (i.isServletParameterTainted() || sbItem.isServletParameterTainted()) servletRequestParameterTainted = true; Object sbVal = sbItem.getConstant(); Object sVal = i.getConstant(); if ((sbVal != null) && (sVal != null)) { appenderValue = sbVal + sVal.toString(); } else if (sbItem.registerNumber >= 0) { OpcodeStack.Item item = getLVValue(sbItem.registerNumber); if (item != null) item.constValue = null; } } else if (signature.startsWith("([CII)")) { sawUnknownAppend = true; sbItem = getStackItem(3); if (sbItem.registerNumber >= 0) { OpcodeStack.Item item = getLVValue(sbItem.registerNumber); if (item != null) item.constValue = null; } } else { sawUnknownAppend = true; } } } else if (seen == INVOKESPECIAL && clsName.equals("java/io/FileOutputStream") && methodName.equals("<init>") && (signature.equals("(Ljava/io/File;Z)V") || signature.equals("(Ljava/lang/String;Z)V"))) { OpcodeStack.Item item = getStackItem(0); Object value = item.getConstant(); if ( value instanceof Integer && ((Integer)value).intValue() == 1) { pop(3); Item top = getStackItem(0); if (top.signature.equals("Ljava/io/FileOutputStream;")) { top.setSpecialKind(Item.FILE_OPENED_IN_APPEND_MODE); top.source = XFactory.createReferencedXMethod(dbc); top.setPC(dbc.getPC()); } return; } } else if (seen == INVOKESPECIAL && clsName.equals("java/io/BufferedOutputStream") && methodName.equals("<init>") && signature.equals("(Ljava/io/OutputStream;)V")) { OpcodeStack.Item item = getStackItem(0); if (getStackItem(0).getSpecialKind() == Item.FILE_OPENED_IN_APPEND_MODE && getStackItem(2).signature.equals("Ljava/io/BufferedOutputStream;")) { pop(2); Item top = getStackItem(0); top.setSpecialKind(Item.FILE_OPENED_IN_APPEND_MODE); top.source = XFactory.createReferencedXMethod(dbc); top.setPC(dbc.getPC()); return; } } else if (seen == INVOKEINTERFACE && methodName.equals("getParameter") && clsName.equals("javax/servlet/http/HttpServletRequest") || clsName.equals("javax/servlet/http/ServletRequest")) { Item requestParameter = pop(); pop(); Item result = new Item("Ljava/lang/String;"); result.setServletParameterTainted(); result.source = XFactory.createReferencedXMethod(dbc); String parameterName = null; if (requestParameter.getConstant() instanceof String) parameterName = (String) requestParameter.getConstant(); result.injection = new HttpParameterInjection(parameterName, dbc.getPC()); result.setPC(dbc.getPC()); push(result); return; } else if (seen == INVOKEINTERFACE && methodName.equals("getQueryString") && clsName.equals("javax/servlet/http/HttpServletRequest") || clsName.equals("javax/servlet/http/ServletRequest")) { pop(); Item result = new Item("Ljava/lang/String;"); result.setServletParameterTainted(); result.source = XFactory.createReferencedXMethod(dbc); result.setPC(dbc.getPC()); push(result); return; } else if (seen == INVOKEINTERFACE && methodName.equals("getHeader") && clsName.equals("javax/servlet/http/HttpServletRequest") || clsName.equals("javax/servlet/http/ServletRequest")) { Item requestParameter = pop(); pop(); Item result = new Item("Ljava/lang/String;"); result.setServletParameterTainted(); result.source = XFactory.createReferencedXMethod(dbc); result.setPC(dbc.getPC()); push(result); return; } pushByInvoke(dbc, seen != INVOKESTATIC); if ((sawUnknownAppend || appenderValue != null || servletRequestParameterTainted) && getStackDepth() > 0) { Item i = this.getStackItem(0); i.constValue = appenderValue; if (!sawUnknownAppend && servletRequestParameterTainted) { i.injection = topItem.injection; i.setServletParameterTainted(); } if (sbItem != null) { i.registerNumber = sbItem.registerNumber; i.source = sbItem.source; if (i.injection == null) i.injection = sbItem.injection; if (sbItem.registerNumber >= 0) setLVValue(sbItem.registerNumber, i ); } return; } if ((clsName.equals("java/util/Random") || clsName.equals("java/security/SecureRandom")) && methodName.equals("nextInt") && signature.equals("()I")) { Item i = pop(); i.setSpecialKind(Item.RANDOM_INT); push(i); } else if (clsName.equals("java/lang/Math") && methodName.equals("abs")) { Item i = pop(); i.setSpecialKind(Item.MATH_ABS); push(i); } else if (seen == INVOKEVIRTUAL && methodName.equals("hashCode") && signature.equals("()I") || seen == INVOKESTATIC && clsName.equals("java/lang/System") && methodName.equals("identityHashCode") && signature.equals("(Ljava/lang/Object;)I")) { Item i = pop(); i.setSpecialKind(Item.HASHCODE_INT); push(i); } else if (topIsTainted && ( methodName.startsWith("encode") && clsName.equals("javax/servlet/http/HttpServletResponse") || methodName.equals("trim") && clsName.equals("java/lang/String")) ) { Item i = pop(); i.setSpecialKind(Item.SERVLET_REQUEST_TAINTED); push(i); } if (!signature.endsWith(")V")) { Item i = pop(); i.source = XFactory.createReferencedXMethod(dbc); push(i); } } private void mergeLists(List<Item> mergeInto, List<Item> mergeFrom, boolean errorIfSizesDoNotMatch) { // merge stacks int intoSize = mergeInto.size(); int fromSize = mergeFrom.size(); if (errorIfSizesDoNotMatch && intoSize != fromSize) { if (DEBUG2) { System.out.println("Bad merging items"); System.out.println("current items: " + mergeInto); System.out.println("jump items: " + mergeFrom); } } else { if (DEBUG2) { if (intoSize == fromSize) System.out.println("Merging items"); else System.out.println("Bad merging items"); System.out.println("current items: " + mergeInto); System.out.println("jump items: " + mergeFrom); } for (int i = 0; i < Math.min(intoSize, fromSize); i++) mergeInto.set(i, Item.merge(mergeInto.get(i), mergeFrom.get(i))); if (DEBUG2) { System.out.println("merged items: " + mergeInto); } } } public void clear() { stack.clear(); lvValues.clear(); } boolean encountedTop; boolean backwardsBranch; BitSet exceptionHandlers = new BitSet(); private Map<Integer, List<Item>> jumpEntries = new HashMap<Integer, List<Item>>(); private Map<Integer, List<Item>> jumpStackEntries = new HashMap<Integer, List<Item>>(); private BitSet jumpEntryLocations = new BitSet(); static class JumpInfo { final Map<Integer, List<Item>> jumpEntries; final Map<Integer, List<Item>> jumpStackEntries; final BitSet jumpEntryLocations; JumpInfo(Map<Integer, List<Item>> jumpEntries, Map<Integer, List<Item>> jumpStackEntries, BitSet jumpEntryLocations) { this.jumpEntries = jumpEntries; this.jumpStackEntries = jumpStackEntries; this.jumpEntryLocations = jumpEntryLocations; } } public static class JumpInfoFactory extends AnalysisFactory<JumpInfo> { public JumpInfoFactory() { super("Jump info for opcode stack", JumpInfo.class); } public JumpInfo analyze(IAnalysisCache analysisCache, MethodDescriptor descriptor) throws CheckedAnalysisException { Method method = analysisCache.getMethodAnalysis(Method.class, descriptor); JavaClass jclass = getJavaClass(analysisCache, descriptor.getClassDescriptor()); Code code = method.getCode(); final OpcodeStack stack = new OpcodeStack(); if (code == null) { return null; } DismantleBytecode branchAnalysis = new DismantleBytecode() { @Override public void sawOpcode(int seen) { stack.sawOpcode(this, seen); } }; branchAnalysis.setupVisitorForClass(jclass); int oldCount = 0; while (true) { stack.resetForMethodEntry0(ClassName.toSlashedClassName(jclass.getClassName()), method); branchAnalysis.doVisitMethod(method); int newCount = stack.jumpEntries.size(); if (newCount == oldCount || !stack.encountedTop || !stack.backwardsBranch) break; oldCount = newCount; } return new JumpInfo(stack.jumpEntries, stack.jumpStackEntries, stack.jumpEntryLocations); }} private void addJumpValue(int from, int target) { if (DEBUG) System.out.println("Set jump entry at " + methodName + ":" + target + "pc to " + stack + " : " + lvValues ); if (from >= target) backwardsBranch = true; List<Item> atTarget = jumpEntries.get(target); if (atTarget == null) { if (DEBUG) System.out.println("Was null"); jumpEntries.put(target, new ArrayList<Item>(lvValues)); jumpEntryLocations.set(target); if (stack.size() > 0) { jumpStackEntries.put(target, new ArrayList<Item>(stack)); } return; } mergeLists(atTarget, lvValues, false); List<Item> stackAtTarget = jumpStackEntries.get(target); if (stack.size() > 0 && stackAtTarget != null) mergeLists(stackAtTarget, stack, false); if (DEBUG) System.out.println("merge target for " + methodName + ":" + target + "pc is " + atTarget); } private String methodName; DismantleBytecode v; public void learnFrom(JumpInfo info) { jumpEntries = new HashMap<Integer, List<Item>>(info.jumpEntries); jumpStackEntries = new HashMap<Integer, List<Item>>(info.jumpStackEntries); jumpEntryLocations = (BitSet) info.jumpEntryLocations.clone(); } public void initialize() { setTop(false); jumpEntries.clear(); jumpStackEntries.clear(); jumpEntryLocations.clear(); encountedTop = false; backwardsBranch = false; lastUpdate.clear(); convertJumpToOneZeroState = convertJumpToZeroOneState = 0; zeroOneComing = false; setReachOnlyByBranch(false); } public int resetForMethodEntry(final DismantleBytecode v) { this.v = v; initialize(); int result = resetForMethodEntry0(v); Code code = v.getMethod().getCode(); if (code == null) return result; if (useIterativeAnalysis) { IAnalysisCache analysisCache = Global.getAnalysisCache(); XMethod xMethod = XFactory.createXMethod(v.getThisClass(), v.getMethod()); try { JumpInfo jump = analysisCache.getMethodAnalysis(JumpInfo.class, xMethod.getMethodDescriptor()); if (jump != null) { learnFrom(jump); } } catch (CheckedAnalysisException e) { AnalysisContext.logError("Error getting jump information", e); } } return result; } private int resetForMethodEntry0(PreorderVisitor v) { return resetForMethodEntry0(v.getClassName(), v.getMethod()); } private int resetForMethodEntry0(@SlashedClassName String className, Method m) { methodName = m.getName(); if (DEBUG) System.out.println(" --- "); String signature = m.getSignature(); stack.clear(); lvValues.clear(); top = false; encountedTop = false; backwardsBranch = false; setReachOnlyByBranch(false); seenTransferOfControl = false; exceptionHandlers.clear(); Code code = m.getCode(); if (code != null) { CodeException[] exceptionTable = code.getExceptionTable(); if (exceptionTable != null) for(CodeException ex : exceptionTable) exceptionHandlers.set(ex.getHandlerPC()); } if (DEBUG) System.out.println(" --- " + className + " " + m.getName() + " " + signature); Type[] argTypes = Type.getArgumentTypes(signature); int reg = 0; if (!m.isStatic()) { Item it = new Item("L" + className+";"); it.setInitialParameter(true); it.registerNumber = reg; setLVValue( reg, it); reg += it.getSize(); } for (Type argType : argTypes) { Item it = new Item(argType.getSignature()); it.registerNumber = reg; it.setInitialParameter(true); setLVValue(reg, it); reg += it.getSize(); } return reg; } public int getStackDepth() { return stack.size(); } public Item getStackItem(int stackOffset) { if (stackOffset < 0 || stackOffset >= stack.size()) { AnalysisContext.logError("Can't get stack offset " + stackOffset + " from " + stack.toString() +" @ " + v.getPC() + " in " + v.getFullyQualifiedMethodName(), new IllegalArgumentException()); return new Item("Lfindbugs/OpcodeStackError;"); } int tos = stack.size() - 1; int pos = tos - stackOffset; try { return stack.get(pos); } catch (ArrayIndexOutOfBoundsException e) { throw new ArrayIndexOutOfBoundsException( "Requested item at offset " + stackOffset + " in a stack of size " + stack.size() +", made request for position " + pos); } } private Item pop() { return stack.remove(stack.size()-1); } public void replaceTop(Item newTop) { pop(); push(newTop); } private void pop(int count) { while ((count--) > 0) pop(); } private void push(Item i) { stack.add(i); } private void pushByConstant(DismantleBytecode dbc, Constant c) { if (c instanceof ConstantClass) push(new Item("Ljava/lang/Class;", ((ConstantClass)c).getConstantValue(dbc.getConstantPool()))); else if (c instanceof ConstantInteger) push(new Item("I", (Integer)(((ConstantInteger) c).getBytes()))); else if (c instanceof ConstantString) { int s = ((ConstantString) c).getStringIndex(); push(new Item("Ljava/lang/String;", getStringFromIndex(dbc, s))); } else if (c instanceof ConstantFloat) push(new Item("F", (Float)(((ConstantFloat) c).getBytes()))); else if (c instanceof ConstantDouble) push(new Item("D", (Double)(((ConstantDouble) c).getBytes()))); else if (c instanceof ConstantLong) push(new Item("J", (Long)(((ConstantLong) c).getBytes()))); else throw new UnsupportedOperationException("Constant type not expected" ); } private void pushByLocalObjectLoad(DismantleBytecode dbc, int register) { Method m = dbc.getMethod(); LocalVariableTable lvt = m.getLocalVariableTable(); if (lvt != null) { LocalVariable lv = LVTHelper.getLocalVariableAtPC(lvt, register, dbc.getPC()); if (lv != null) { String signature = lv.getSignature(); pushByLocalLoad(signature, register); return; } } pushByLocalLoad("", register); } private void pushByIntMath(DismantleBytecode dbc, int seen, Item lhs, Item rhs) { Item newValue = new Item("I"); if (lhs == null || rhs == null) { push(newValue); return; } try { if (DEBUG) System.out.println("pushByIntMath: " + rhs.getConstant() + " " + lhs.getConstant() ); if ((rhs.getConstant() != null) && lhs.getConstant() != null) { Integer lhsValue = (Integer) lhs.getConstant(); Integer rhsValue = (Integer) rhs.getConstant(); if (seen == IADD) newValue = new Item("I",lhsValue + rhsValue); else if (seen == ISUB) newValue = new Item("I",lhsValue - rhsValue); else if (seen == IMUL) newValue = new Item("I", lhsValue * rhsValue); else if (seen == IDIV) newValue = new Item("I", lhsValue / rhsValue); else if (seen == IAND) { newValue = new Item("I", lhsValue & rhsValue); if ((rhsValue&0xff) == 0 && rhsValue != 0 || (lhsValue&0xff) == 0 && lhsValue != 0 ) newValue.specialKind = Item.LOW_8_BITS_CLEAR; } else if (seen == IOR) newValue = new Item("I",lhsValue | rhsValue); else if (seen == IXOR) newValue = new Item("I",lhsValue ^ rhsValue); else if (seen == ISHL) { newValue = new Item("I",lhsValue << rhsValue); if (rhsValue >= 8) newValue.specialKind = Item.LOW_8_BITS_CLEAR; } else if (seen == ISHR) newValue = new Item("I",lhsValue >> rhsValue); else if (seen == IREM) newValue = new Item("I", lhsValue % rhsValue); else if (seen == IUSHR) newValue = new Item("I", lhsValue >>> rhsValue); } else if (rhs.getConstant() != null && seen == ISHL && (Integer) rhs.getConstant() >= 8) newValue.specialKind = Item.LOW_8_BITS_CLEAR; else if (lhs.getConstant() != null && seen == IAND) { int value = (Integer) lhs.getConstant(); if (value == 0) newValue = new Item("I", 0); else if ((value & 0xff) == 0) newValue.specialKind = Item.LOW_8_BITS_CLEAR; else if (value >= 0) newValue.specialKind = Item.NON_NEGATIVE; } else if (rhs.getConstant() != null && seen == IAND) { int value = (Integer) rhs.getConstant(); if (value == 0) newValue = new Item("I", 0); else if ((value & 0xff) == 0) newValue.specialKind = Item.LOW_8_BITS_CLEAR; else if (value >= 0) newValue.specialKind = Item.NON_NEGATIVE; } else if (seen == IAND && lhs.getSpecialKind() == Item.ZERO_MEANS_NULL) { newValue.setSpecialKind(Item.ZERO_MEANS_NULL); newValue.setPC(lhs.getPC()); } else if (seen == IAND && rhs.getSpecialKind() == Item.ZERO_MEANS_NULL) { newValue.setSpecialKind(Item.ZERO_MEANS_NULL); newValue.setPC(rhs.getPC()); } else if (seen == IOR && lhs.getSpecialKind() == Item.NONZERO_MEANS_NULL) { newValue.setSpecialKind(Item.NONZERO_MEANS_NULL); newValue.setPC(lhs.getPC()); } else if (seen == IOR && rhs.getSpecialKind() == Item.NONZERO_MEANS_NULL) { newValue.setSpecialKind(Item.NONZERO_MEANS_NULL); newValue.setPC(rhs.getPC()); } } catch (ArithmeticException e) { assert true; // ignore it } catch (RuntimeException e) { String msg = "Error processing2 " + lhs + OPCODE_NAMES[seen] + rhs + " @ " + dbc.getPC() + " in " + dbc.getFullyQualifiedMethodName(); AnalysisContext.logError(msg , e); } if (lhs.specialKind == Item.INTEGER_SUM && rhs.getConstant() != null ) { int rhsValue = (Integer) rhs.getConstant(); if (seen == IDIV && rhsValue ==2 || seen == ISHR && rhsValue == 1) newValue.specialKind = Item.AVERAGE_COMPUTED_USING_DIVISION; } if (seen == IADD && newValue.specialKind == 0 && lhs.getConstant() == null && rhs.getConstant() == null ) newValue.specialKind = Item.INTEGER_SUM; if (seen == IREM && lhs.specialKind == Item.HASHCODE_INT) newValue.specialKind = Item.HASHCODE_INT_REMAINDER; if (seen == IREM && lhs.specialKind == Item.RANDOM_INT) newValue.specialKind = Item.RANDOM_INT_REMAINDER; if (DEBUG) System.out.println("push: " + newValue); newValue.setPC(dbc.getPC()); push(newValue); } private void pushByLongMath(int seen, Item lhs, Item rhs) { Item newValue = new Item("J"); try { if ((rhs.getConstant() != null) && lhs.getConstant() != null) { Long lhsValue = ((Long) lhs.getConstant()); if (seen == LSHL) { newValue =new Item("J", lhsValue << ((Number) rhs.getConstant()).intValue()); if (((Number) rhs.getConstant()).intValue() >= 8) newValue.specialKind = Item.LOW_8_BITS_CLEAR; } else if (seen == LSHR) newValue =new Item("J", lhsValue >> ((Number) rhs.getConstant()).intValue()); else if (seen == LUSHR) newValue =new Item("J", lhsValue >>> ((Number) rhs.getConstant()).intValue()); else { Long rhsValue = ((Long) rhs.getConstant()); if (seen == LADD) newValue = new Item("J", lhsValue + rhsValue); else if (seen == LSUB) newValue = new Item("J", lhsValue - rhsValue); else if (seen == LMUL) newValue = new Item("J", lhsValue * rhsValue); else if (seen == LDIV) newValue =new Item("J", lhsValue / rhsValue); else if (seen == LAND) { newValue = new Item("J", lhsValue & rhsValue); if ((rhsValue&0xff) == 0 && rhsValue != 0 || (lhsValue&0xff) == 0 && lhsValue != 0 ) newValue.specialKind = Item.LOW_8_BITS_CLEAR; } else if (seen == LOR) newValue = new Item("J", lhsValue | rhsValue); else if (seen == LXOR) newValue =new Item("J", lhsValue ^ rhsValue); else if (seen == LREM) newValue =new Item("J", lhsValue % rhsValue); } } else if (rhs.getConstant() != null && seen == LSHL && ((Integer) rhs.getConstant()) >= 8) newValue.specialKind = Item.LOW_8_BITS_CLEAR; else if (lhs.getConstant() != null && seen == LAND && (((Long) lhs.getConstant()) & 0xff) == 0) newValue.specialKind = Item.LOW_8_BITS_CLEAR; else if (rhs.getConstant() != null && seen == LAND && (((Long) rhs.getConstant()) & 0xff) == 0) newValue.specialKind = Item.LOW_8_BITS_CLEAR; } catch (RuntimeException e) { // ignore it } push(newValue); } private void pushByFloatMath(int seen, Item it, Item it2) { Item result; int specialKind = Item.FLOAT_MATH; if ((it.getConstant() instanceof Float) && it2.getConstant() instanceof Float) { if (seen == FADD) result =new Item("F", ((Float) it2.getConstant()) + ((Float) it.getConstant())); else if (seen == FSUB) result =new Item("F", ((Float) it2.getConstant()) - ((Float) it.getConstant())); else if (seen == FMUL) result =new Item("F", ((Float) it2.getConstant()) * ((Float) it.getConstant())); else if (seen == FDIV) result =new Item("F", ((Float) it2.getConstant()) / ((Float) it.getConstant())); else if (seen == FREM) result =new Item("F", ((Float) it2.getConstant()) % ((Float) it.getConstant())); else result =new Item("F"); } else { result =new Item("F"); if (seen == DDIV) specialKind = Item.NASTY_FLOAT_MATH; } result.setSpecialKind(specialKind); push(result); } private void pushByDoubleMath(int seen, Item it, Item it2) { Item result; int specialKind = Item.FLOAT_MATH; if ((it.getConstant() instanceof Double) && it2.getConstant() instanceof Double) { if (seen == DADD) result = new Item("D", ((Double) it2.getConstant()) + ((Double) it.getConstant())); else if (seen == DSUB) result = new Item("D", ((Double) it2.getConstant()) - ((Double) it.getConstant())); else if (seen == DMUL) result = new Item("D", ((Double) it2.getConstant()) * ((Double) it.getConstant())); else if (seen == DDIV) result = new Item("D", ((Double) it2.getConstant()) / ((Double) it.getConstant())); else if (seen == DREM) result = new Item("D", ((Double) it2.getConstant()) % ((Double) it.getConstant())); else result = new Item("D"); //? } else { result = new Item("D"); if (seen == DDIV) specialKind = Item.NASTY_FLOAT_MATH; } result.setSpecialKind(specialKind); push(result); } private void pushByInvoke(DismantleBytecode dbc, boolean popThis) { String signature = dbc.getSigConstantOperand(); if (dbc.getNameConstantOperand().equals("<init>") && signature.endsWith(")V") && popThis) { pop(PreorderVisitor.getNumberArguments(signature)); Item constructed = pop(); if (getStackDepth() > 0) { Item next = getStackItem(0); if (constructed.equals(next)) next.source = XFactory.createReferencedXMethod(dbc); } return; } pop(PreorderVisitor.getNumberArguments(signature)+(popThis ? 1 : 0)); pushBySignature(Type.getReturnType(signature).getSignature(), dbc); } private String getStringFromIndex(DismantleBytecode dbc, int i) { ConstantUtf8 name = (ConstantUtf8) dbc.getConstantPool().getConstant(i); return name.getBytes(); } private void pushBySignature(String s, DismantleBytecode dbc) { if ("V".equals(s)) return; Item item = new Item(s, (Object) null); if (dbc != null) item.setPC(dbc.getPC()); push(item); } private void pushByLocalStore(int register) { Item it = pop(); if (it.getRegisterNumber() != register) { for(Item i : lvValues) if (i != null) { if (i.registerNumber == register) i.registerNumber = -1; if (i.fieldLoadedFromRegister == register) i.fieldLoadedFromRegister = -1; } for(Item i : stack) if (i != null) { if (i.registerNumber == register) i.registerNumber = -1; if (i.fieldLoadedFromRegister == register) i.fieldLoadedFromRegister = -1; } } setLVValue( register, it ); } private void pushByLocalLoad(String signature, int register) { Item it = getLVValue(register); if (it == null) { Item item = new Item(signature); item.registerNumber = register; push(item); } else if (it.getRegisterNumber() >= 0) push(it); else { push(new Item(it, register)); } } private void setLVValue(int index, Item value ) { int addCount = index - lvValues.size() + 1; while ((addCount--) > 0) lvValues.add(null); if (!useIterativeAnalysis && seenTransferOfControl) value = Item.merge(value, lvValues.get(index) ); lvValues.set(index, value); } private Item getLVValue(int index) { if (index >= lvValues.size()) return new Item(); return lvValues.get(index); } /** * @param top The top to set. */ private void setTop(boolean top) { if (top) { if (!this.top) this.top = true; } else if (this.top) this.top = false; } /** * @return Returns the top. */ public boolean isTop() { if (top) return true; return false; } /** * @param reachOnlyByBranch The reachOnlyByBranch to set. */ void setReachOnlyByBranch(boolean reachOnlyByBranch) { if (reachOnlyByBranch) setTop(true); this.reachOnlyByBranch = reachOnlyByBranch; } /** * @return Returns the reachOnlyByBranch. */ boolean isReachOnlyByBranch() { return reachOnlyByBranch; } } // vim:ts=4
findbugs/src/java/edu/umd/cs/findbugs/OpcodeStack.java
/* * FindBugs - Find bugs in Java programs * Copyright (C) 2004 Dave Brosius <[email protected]> * Copyright (C) 2003-2006 University of Maryland * * This library 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 2.1 of the License, or (at your option) any later version. * * This library 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 library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.findbugs; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.bcel.Repository; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.CodeException; import org.apache.bcel.classfile.Constant; import org.apache.bcel.classfile.ConstantClass; import org.apache.bcel.classfile.ConstantDouble; import org.apache.bcel.classfile.ConstantFloat; import org.apache.bcel.classfile.ConstantInteger; import org.apache.bcel.classfile.ConstantLong; import org.apache.bcel.classfile.ConstantString; import org.apache.bcel.classfile.ConstantUtf8; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.LocalVariable; import org.apache.bcel.classfile.LocalVariableTable; import org.apache.bcel.classfile.Method; import org.apache.bcel.generic.BasicType; import org.apache.bcel.generic.Type; import sun.tools.tree.NewInstanceExpression; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.AnalysisFeatures; import edu.umd.cs.findbugs.ba.ClassMember; import edu.umd.cs.findbugs.ba.FieldSummary; import edu.umd.cs.findbugs.ba.XFactory; import edu.umd.cs.findbugs.ba.XField; import edu.umd.cs.findbugs.ba.XMethod; import edu.umd.cs.findbugs.classfile.CheckedAnalysisException; import edu.umd.cs.findbugs.classfile.Global; import edu.umd.cs.findbugs.classfile.IAnalysisCache; import edu.umd.cs.findbugs.classfile.MethodDescriptor; import edu.umd.cs.findbugs.classfile.engine.bcel.AnalysisFactory; import edu.umd.cs.findbugs.internalAnnotations.SlashedClassName; import edu.umd.cs.findbugs.util.ClassName; import edu.umd.cs.findbugs.util.Util; import edu.umd.cs.findbugs.visitclass.Constants2; import edu.umd.cs.findbugs.visitclass.DismantleBytecode; import edu.umd.cs.findbugs.visitclass.LVTHelper; import edu.umd.cs.findbugs.visitclass.PreorderVisitor; /** * tracks the types and numbers of objects that are currently on the operand stack * throughout the execution of method. To use, a detector should instantiate one for * each method, and call <p>stack.sawOpcode(this,seen);</p> at the bottom of their sawOpcode method. * at any point you can then inspect the stack and see what the types of objects are on * the stack, including constant values if they were pushed. The types described are of * course, only the static types. * There are some outstanding opcodes that have yet to be implemented, I couldn't * find any code that actually generated these, so i didn't put them in because * I couldn't test them: * <ul> * <li>dup2_x2</li> * <li>jsr_w</li> * <li>wide</li> * </ul> */ public class OpcodeStack implements Constants2 { private static final boolean DEBUG = SystemProperties.getBoolean("ocstack.debug"); private static final boolean DEBUG2 = DEBUG; private List<Item> stack; private List<Item> lvValues; private List<Integer> lastUpdate; private boolean top; static class HttpParameterInjection { HttpParameterInjection(String parameterName, int pc) { this.parameterName = parameterName; this.pc = pc; } String parameterName; int pc; } private boolean seenTransferOfControl = false; private boolean useIterativeAnalysis = AnalysisContext.currentAnalysisContext().getBoolProperty(AnalysisFeatures.INTERATIVE_OPCODE_STACK_ANALYSIS); public static class Item { public static final int SIGNED_BYTE = 1; public static final int RANDOM_INT = 2; public static final int LOW_8_BITS_CLEAR = 3; public static final int HASHCODE_INT = 4; public static final int INTEGER_SUM = 5; public static final int AVERAGE_COMPUTED_USING_DIVISION = 6; public static final int FLOAT_MATH = 7; public static final int RANDOM_INT_REMAINDER = 8; public static final int HASHCODE_INT_REMAINDER = 9; public static final int FILE_SEPARATOR_STRING = 10; public static final int MATH_ABS = 11; public static final int NON_NEGATIVE = 12; public static final int NASTY_FLOAT_MATH = 13; public static final int FILE_OPENED_IN_APPEND_MODE = 14; public static final int SERVLET_REQUEST_TAINTED = 15; public static final int NEWLY_ALLOCATED = 16; public static final int ZERO_MEANS_NULL = 17; public static final int NONZERO_MEANS_NULL = 18; private static final int IS_INITIAL_PARAMETER_FLAG=1; private static final int COULD_BE_ZERO_FLAG = 2; private static final int IS_NULL_FLAG = 4; public static final Object UNKNOWN = null; private int specialKind; private String signature; private Object constValue = UNKNOWN; private @CheckForNull ClassMember source; private int pc = -1; private int flags; private int registerNumber = -1; private Object userValue = null; private HttpParameterInjection injection = null; private int fieldLoadedFromRegister = -1; public int getSize() { if (signature.equals("J") || signature.equals("D")) return 2; return 1; } public int getPC() { return pc; } public void setPC(int pc) { this.pc = pc; } public boolean isWide() { return getSize() == 2; } @Override public int hashCode() { int r = 42 + specialKind; if (signature != null) r+= signature.hashCode(); r *= 31; if (constValue != null) r+= constValue.hashCode(); r *= 31; if (source != null) r+= source.hashCode(); r *= 31; r += flags; r *= 31; r += registerNumber; return r; } @Override public boolean equals(Object o) { if (!(o instanceof Item)) return false; Item that = (Item) o; return Util.nullSafeEquals(this.signature, that.signature) && Util.nullSafeEquals(this.constValue, that.constValue) && Util.nullSafeEquals(this.source, that.source) && Util.nullSafeEquals(this.userValue, that.userValue) && Util.nullSafeEquals(this.injection, that.injection) && this.specialKind == that.specialKind && this.registerNumber == that.registerNumber && this.flags == that.flags && this.fieldLoadedFromRegister == that.fieldLoadedFromRegister; } @Override public String toString() { StringBuffer buf = new StringBuffer("< "); buf.append(signature); switch(specialKind) { case SIGNED_BYTE: buf.append(", byte_array_load"); break; case RANDOM_INT: buf.append(", random_int"); break; case LOW_8_BITS_CLEAR: buf.append(", low8clear"); break; case HASHCODE_INT: buf.append(", hashcode_int"); break; case INTEGER_SUM: buf.append(", int_sum"); break; case AVERAGE_COMPUTED_USING_DIVISION: buf.append(", averageComputingUsingDivision"); break; case FLOAT_MATH: buf.append(", floatMath"); break; case NASTY_FLOAT_MATH: buf.append(", nastyFloatMath"); break; case HASHCODE_INT_REMAINDER: buf.append(", hashcode_int_rem"); break; case RANDOM_INT_REMAINDER: buf.append(", random_int_rem"); break; case FILE_SEPARATOR_STRING: buf.append(", file_separator_string"); break; case MATH_ABS: buf.append(", Math.abs"); break; case NON_NEGATIVE: buf.append(", non_negative"); break; case FILE_OPENED_IN_APPEND_MODE: buf.append(", file opened in append mode"); break; case SERVLET_REQUEST_TAINTED: buf.append(", servlet request tainted"); break; case NEWLY_ALLOCATED: buf.append(", new"); break; case ZERO_MEANS_NULL: buf.append(", zero means null"); break; case NONZERO_MEANS_NULL: buf.append(", nonzero means null"); break; case 0 : break; default: buf.append(", #" + specialKind); break; } if (constValue != UNKNOWN) { if (constValue instanceof String) { buf.append(", \""); buf.append(constValue); buf.append("\""); } else { buf.append(", "); buf.append(constValue); } } if (source instanceof XField) { buf.append(", "); if (fieldLoadedFromRegister != -1) buf.append(fieldLoadedFromRegister).append(':'); buf.append(source); } if (source instanceof XMethod) { buf.append(", return value from "); buf.append(source); } if (isInitialParameter()) { buf.append(", IP"); } if (isNull()) { buf.append(", isNull"); } if (registerNumber != -1) { buf.append(", r"); buf.append(registerNumber); } if (isCouldBeZero()) buf.append(", cbz"); buf.append(" >"); return buf.toString(); } public static Item merge(Item i1, Item i2) { if (i1 == null) return i2; if (i2 == null) return i1; if (i1.getSpecialKind() == Item.ZERO_MEANS_NULL || i2.getSpecialKind() == Item.ZERO_MEANS_NULL || i1.getSpecialKind() == Item.NONZERO_MEANS_NULL || i2.getSpecialKind() == Item.NONZERO_MEANS_NULL ) System.out.println("Found it"); if (i1.equals(i2)) return i1; Item m = new Item(); m.flags = i1.flags & i2.flags; m.setCouldBeZero(i1.isCouldBeZero() || i2.isCouldBeZero()); if (i1.pc == i2.pc) m.pc = i1.pc; if (Util.nullSafeEquals(i1.signature, i2.signature)) m.signature = i1.signature; else if (i1.isNull()) m.signature = i2.signature; else if (i2.isNull()) m.signature = i1.signature; if (Util.nullSafeEquals(i1.constValue, i2.constValue)) m.constValue = i1.constValue; if (Util.nullSafeEquals(i1.source, i2.source)) { m.source = i1.source; } else if ("".equals(i1.constValue)) m.source = i2.source; else if ("".equals(i2.constValue)) m.source = i1.source; if (Util.nullSafeEquals(i1.userValue, i2.userValue)) m.userValue = i1.userValue; if (i1.registerNumber == i2.registerNumber) m.registerNumber = i1.registerNumber; if (i1.fieldLoadedFromRegister == i2.fieldLoadedFromRegister) m.fieldLoadedFromRegister = i1.fieldLoadedFromRegister; if (i1.specialKind == SERVLET_REQUEST_TAINTED) { m.specialKind = SERVLET_REQUEST_TAINTED; m.injection = i1.injection; } else if (i2.specialKind == SERVLET_REQUEST_TAINTED) { m.specialKind = SERVLET_REQUEST_TAINTED; m.injection = i2.injection; } else if (i1.specialKind == i2.specialKind) m.specialKind = i1.specialKind; else if (i1.specialKind == NASTY_FLOAT_MATH || i2.specialKind == NASTY_FLOAT_MATH) m.specialKind = NASTY_FLOAT_MATH; else if (i1.specialKind == FLOAT_MATH || i2.specialKind == FLOAT_MATH) m.specialKind = FLOAT_MATH; if (DEBUG) System.out.println("Merge " + i1 + " and " + i2 + " gives " + m); return m; } public Item(String signature, int constValue) { this(signature, (Object)(Integer)constValue); } public Item(String signature) { this(signature, UNKNOWN); } public Item(Item it) { this.signature = it.signature; this.constValue = it.constValue; this.source = it.source; this.registerNumber = it.registerNumber; this.userValue = it.userValue; this.injection = it.injection; this.flags = it.flags; this.specialKind = it.specialKind; this.pc = it.pc; } public Item(Item it, int reg) { this(it); this.registerNumber = reg; } public Item(String signature, FieldAnnotation f) { this.signature = signature; if (f != null) source = XFactory.createXField(f); fieldLoadedFromRegister = -1; } public Item(String signature, FieldAnnotation f, int fieldLoadedFromRegister) { this.signature = signature; if (f != null) source = XFactory.createXField(f); this.fieldLoadedFromRegister = fieldLoadedFromRegister; } public int getFieldLoadedFromRegister() { return fieldLoadedFromRegister; } public void setLoadedFromField(XField f, int fieldLoadedFromRegister) { source = f; this.fieldLoadedFromRegister = fieldLoadedFromRegister; this.registerNumber = -1; } public @CheckForNull String getHttpParameterName() { if (!isServletParameterTainted()) throw new IllegalStateException(); if (injection == null) return null; return injection.parameterName; } public int getInjectionPC() { if (!isServletParameterTainted()) throw new IllegalStateException(); if (injection == null) return -1; return injection.pc; } public Item(String signature, Object constantValue) { this.signature = signature; constValue = constantValue; if (constantValue instanceof Integer) { int value = (Integer) constantValue; if (value != 0 && (value & 0xff) == 0) specialKind = LOW_8_BITS_CLEAR; if (value == 0) setCouldBeZero(true); } else if (constantValue instanceof Long) { long value = (Long) constantValue; if (value != 0 && (value & 0xff) == 0) specialKind = LOW_8_BITS_CLEAR; if (value == 0) setCouldBeZero(true); } } public Item() { signature = "Ljava/lang/Object;"; constValue = null; setNull(true); } public static Item nullItem(String signature) { Item item = new Item(signature); item.constValue = null; item.setNull(true); return item; } /** Returns null for primitive and arrays */ public @CheckForNull JavaClass getJavaClass() throws ClassNotFoundException { String baseSig; try { if (isPrimitive() || isArray()) return null; baseSig = signature; if (baseSig.length() == 0) return null; baseSig = baseSig.substring(1, baseSig.length() - 1); baseSig = baseSig.replace('/', '.'); return Repository.lookupClass(baseSig); } catch (RuntimeException e) { e.printStackTrace(); throw e; } } public boolean isArray() { return signature.startsWith("["); } public String getElementSignature() { if (!isArray()) return signature; else { int pos = 0; int len = signature.length(); while (pos < len) { if (signature.charAt(pos) != '[') break; pos++; } return signature.substring(pos); } } public boolean isNonNegative() { if (specialKind == NON_NEGATIVE) return true; if (constValue instanceof Number) { double value = ((Number) constValue).doubleValue(); return value >= 0; } return false; } public boolean isPrimitive() { return !signature.startsWith("L") && !signature.startsWith("["); } public int getRegisterNumber() { return registerNumber; } public String getSignature() { return signature; } /** * Returns a constant value for this Item, if known. * NOTE: if the value is a constant Class object, the constant value returned is the name of the class. */ public Object getConstant() { return constValue; } /** Use getXField instead */ @Deprecated public FieldAnnotation getFieldAnnotation() { return FieldAnnotation.fromXField(getXField()); } public XField getXField() { if (source instanceof XField) return (XField) source; return null; } /** * @param specialKind The specialKind to set. */ public void setSpecialKind(int specialKind) { this.specialKind = specialKind; } /** * @return Returns the specialKind. */ public int getSpecialKind() { return specialKind; } /** * @return Returns the specialKind. */ public boolean isBooleanNullnessValue() { return specialKind == ZERO_MEANS_NULL || specialKind == NONZERO_MEANS_NULL; } /** * attaches a detector specified value to this item * * @param value the custom value to set */ public void setUserValue(Object value) { userValue = value; } /** * * @return if this value is the return value of a method, give the method * invoked */ public @CheckForNull XMethod getReturnValueOf() { if (source instanceof XMethod) return (XMethod) source; return null; } public boolean couldBeZero() { return isCouldBeZero(); } public boolean mustBeZero() { Object value = getConstant(); return value instanceof Number && ((Number)value).intValue() == 0; } /** * gets the detector specified value for this item * * @return the custom value */ public Object getUserValue() { return userValue; } public boolean isServletParameterTainted() { return getSpecialKind() == Item.SERVLET_REQUEST_TAINTED; } public void setServletParameterTainted() { setSpecialKind(Item.SERVLET_REQUEST_TAINTED); } public boolean valueCouldBeNegative() { return !isNonNegative() && (getSpecialKind() == Item.RANDOM_INT || getSpecialKind() == Item.SIGNED_BYTE || getSpecialKind() == Item.HASHCODE_INT || getSpecialKind() == Item.RANDOM_INT_REMAINDER || getSpecialKind() == Item.HASHCODE_INT_REMAINDER); } /** * @param isInitialParameter The isInitialParameter to set. */ private void setInitialParameter(boolean isInitialParameter) { setFlag(isInitialParameter, IS_INITIAL_PARAMETER_FLAG); } /** * @return Returns the isInitialParameter. */ public boolean isInitialParameter() { return (flags & IS_INITIAL_PARAMETER_FLAG) != 0; } /** * @param couldBeZero The couldBeZero to set. */ private void setCouldBeZero(boolean couldBeZero) { setFlag(couldBeZero, COULD_BE_ZERO_FLAG); } /** * @return Returns the couldBeZero. */ private boolean isCouldBeZero() { return (flags & COULD_BE_ZERO_FLAG) != 0; } /** * @param isNull The isNull to set. */ private void setNull(boolean isNull) { setFlag(isNull, IS_NULL_FLAG); } private void setFlag(boolean value, int flagBit) { if (value) flags |= flagBit; else flags &= ~flagBit; } /** * @return Returns the isNull. */ public boolean isNull() { return (flags & IS_NULL_FLAG) != 0; } } @Override public String toString() { if (isTop()) return "TOP"; return stack.toString() + "::" + lvValues.toString(); } public OpcodeStack() { stack = new ArrayList<Item>(); lvValues = new ArrayList<Item>(); lastUpdate = new ArrayList<Integer>(); } boolean needToMerge = true; private boolean reachOnlyByBranch = false; public static String getExceptionSig(DismantleBytecode dbc, CodeException e) { if (e.getCatchType() == 0) return "Ljava/lang/Throwable;"; Constant c = dbc.getConstantPool().getConstant(e.getCatchType()); if (c instanceof ConstantClass) return "L"+((ConstantClass)c).getBytes(dbc.getConstantPool())+";"; return "Ljava/lang/Throwable;"; } public void mergeJumps(DismantleBytecode dbc) { if (!needToMerge) return; needToMerge = false; boolean stackUpdated = false; if (!isTop() && (convertJumpToOneZeroState == 3 || convertJumpToZeroOneState == 3)) { pop(); Item top = new Item("I"); top.setCouldBeZero(true); push(top); convertJumpToOneZeroState = convertJumpToZeroOneState = 0; stackUpdated = true; } List<Item> jumpEntry = null; if (jumpEntryLocations.get(dbc.getPC())) jumpEntry = jumpEntries.get(dbc.getPC()); if (jumpEntry != null) { setReachOnlyByBranch(false); List<Item> jumpStackEntry = jumpStackEntries.get(dbc.getPC()); if (DEBUG2) { System.out.println("XXXXXXX " + isReachOnlyByBranch()); System.out.println("merging lvValues at jump target " + dbc.getPC() + " -> " + Integer.toString(System.identityHashCode(jumpEntry),16) + " " + jumpEntry); System.out.println(" current lvValues " + lvValues); System.out.println(" merging stack entry " + jumpStackEntry); System.out.println(" current stack values " + stack); } if (isTop()) { lvValues = new ArrayList<Item>(jumpEntry); if (jumpStackEntry != null) stack = new ArrayList<Item>(jumpStackEntry); else stack.clear(); setTop(false); return; } if (isReachOnlyByBranch()) { setTop(false); lvValues = new ArrayList<Item>(jumpEntry); if (!stackUpdated) { if (jumpStackEntry != null) stack = new ArrayList<Item>(jumpStackEntry); else stack.clear(); } } else { setTop(false); mergeLists(lvValues, jumpEntry, false); if (!stackUpdated && jumpStackEntry != null) mergeLists(stack, jumpStackEntry, false); } if (DEBUG) System.out.println(" merged lvValues " + lvValues); } else if (isReachOnlyByBranch() && !stackUpdated) { stack.clear(); for(CodeException e : dbc.getCode().getExceptionTable()) { if (e.getHandlerPC() == dbc.getPC()) { push(new Item(getExceptionSig(dbc, e))); setReachOnlyByBranch(false); setTop(false); return; } } setTop(true); } } int convertJumpToOneZeroState = 0; int convertJumpToZeroOneState = 0; private void setLastUpdate(int reg, int pc) { while (lastUpdate.size() <= reg) lastUpdate.add(0); lastUpdate.set(reg, pc); } public int getLastUpdate(int reg) { if (lastUpdate.size() <= reg) return 0; return lastUpdate.get(reg); } public int getNumLastUpdates() { return lastUpdate.size(); } boolean zeroOneComing = false; boolean oneMeansNull; public void sawOpcode(DismantleBytecode dbc, int seen) { int register; String signature; Item it, it2, it3; Constant cons; if (dbc.isRegisterStore()) setLastUpdate(dbc.getRegisterOperand(), dbc.getPC()); if (zeroOneComing) { top = false; OpcodeStack.Item item = new Item("I"); if (oneMeansNull) item.setSpecialKind(Item.NONZERO_MEANS_NULL); else item.setSpecialKind(Item.ZERO_MEANS_NULL); item.setPC(dbc.getPC() - 7); item.setCouldBeZero(true); jumpEntries.remove(dbc.getPC()+1); jumpStackEntries.remove(dbc.getPC()+1); push(item); convertJumpToOneZeroState = convertJumpToZeroOneState = 0; zeroOneComing= false; if (DEBUG) System.out.println("Updated to " + this); return; } mergeJumps(dbc); needToMerge = true; try { if (isTop()) { encountedTop = true; return; } if (seen == GOTO) { int nextPC = dbc.getPC() + 3; if (nextPC <= dbc.getMaxPC()) { int prevOpcode1 = dbc.getPrevOpcode(1); int prevOpcode2 = dbc.getPrevOpcode(2); try { int nextOpcode = dbc.getCodeByte(dbc.getPC() + 3); if ((prevOpcode1 == ICONST_0 || prevOpcode1 == ICONST_1) && (prevOpcode2 == IFNULL || prevOpcode2 == IFNONNULL) && (nextOpcode == ICONST_0 || nextOpcode == ICONST_1) && prevOpcode1 != nextOpcode) { oneMeansNull = prevOpcode1 == ICONST_0; if (prevOpcode2 != IFNULL) oneMeansNull = !oneMeansNull; zeroOneComing = true; } } catch(ArrayIndexOutOfBoundsException e) { throw e; // throw new ArrayIndexOutOfBoundsException(nextPC + " " + dbc.getMaxPC()); } } } switch (seen) { case ICONST_1: convertJumpToOneZeroState = 1; break; case GOTO: if (convertJumpToOneZeroState == 1 && dbc.getBranchOffset() == 4) convertJumpToOneZeroState = 2; else convertJumpToOneZeroState = 0; break; case ICONST_0: if (convertJumpToOneZeroState == 2) convertJumpToOneZeroState = 3; else convertJumpToOneZeroState = 0; break; default:convertJumpToOneZeroState = 0; } switch (seen) { case ICONST_0: convertJumpToZeroOneState = 1; break; case GOTO: if (convertJumpToZeroOneState == 1 && dbc.getBranchOffset() == 4) convertJumpToZeroOneState = 2; else convertJumpToZeroOneState = 0; break; case ICONST_1: if (convertJumpToZeroOneState == 2) convertJumpToZeroOneState = 3; else convertJumpToZeroOneState = 0; break; default:convertJumpToZeroOneState = 0; } switch (seen) { case ALOAD: pushByLocalObjectLoad(dbc, dbc.getRegisterOperand()); break; case ALOAD_0: case ALOAD_1: case ALOAD_2: case ALOAD_3: pushByLocalObjectLoad(dbc, seen - ALOAD_0); break; case DLOAD: pushByLocalLoad("D", dbc.getRegisterOperand()); break; case DLOAD_0: case DLOAD_1: case DLOAD_2: case DLOAD_3: pushByLocalLoad("D", seen - DLOAD_0); break; case FLOAD: pushByLocalLoad("F", dbc.getRegisterOperand()); break; case FLOAD_0: case FLOAD_1: case FLOAD_2: case FLOAD_3: pushByLocalLoad("F", seen - FLOAD_0); break; case ILOAD: pushByLocalLoad("I", dbc.getRegisterOperand()); break; case ILOAD_0: case ILOAD_1: case ILOAD_2: case ILOAD_3: pushByLocalLoad("I", seen - ILOAD_0); break; case LLOAD: pushByLocalLoad("J", dbc.getRegisterOperand()); break; case LLOAD_0: case LLOAD_1: case LLOAD_2: case LLOAD_3: pushByLocalLoad("J", seen - LLOAD_0); break; case GETSTATIC: { FieldSummary fieldSummary = AnalysisContext.currentAnalysisContext().getFieldSummary(); XField fieldOperand = dbc.getXFieldOperand(); if (fieldOperand != null && fieldSummary.isComplete() && !fieldOperand.isPublic()) { OpcodeStack.Item item = fieldSummary.getSummary(fieldOperand); if (item != null) { Item itm = new Item(item); itm.setLoadedFromField(fieldOperand, Integer.MAX_VALUE); push(itm); break; } } FieldAnnotation field = FieldAnnotation.fromReferencedField(dbc); Item i = new Item(dbc.getSigConstantOperand(), field, Integer.MAX_VALUE); if (field.getFieldName().equals("separator") && field.getClassName().equals("java.io.File")) { i.setSpecialKind(Item.FILE_SEPARATOR_STRING); } push(i); break; } case LDC: case LDC_W: case LDC2_W: cons = dbc.getConstantRefOperand(); pushByConstant(dbc, cons); break; case INSTANCEOF: pop(); push(new Item("I")); break; case IFEQ: case IFNE: case IFLT: case IFLE: case IFGT: case IFGE: case IFNONNULL: case IFNULL: seenTransferOfControl = true; { Item top = pop(); // if we see a test comparing a special negative value with 0, // reset all other such values on the opcode stack if (top.valueCouldBeNegative() && (seen == IFLT || seen == IFLE || seen == IFGT || seen == IFGE)) { int specialKind = top.getSpecialKind(); for(Item item : stack) if (item != null && item.getSpecialKind() == specialKind) item.setSpecialKind(0); for(Item item : lvValues) if (item != null && item.getSpecialKind() == specialKind) item.setSpecialKind(0); } } addJumpValue(dbc.getPC(), dbc.getBranchTarget()); break; case LOOKUPSWITCH: case TABLESWITCH: seenTransferOfControl = true; setReachOnlyByBranch(true); pop(); addJumpValue(dbc.getPC(), dbc.getBranchTarget()); int pc = dbc.getBranchTarget() - dbc.getBranchOffset(); for(int offset : dbc.getSwitchOffsets()) addJumpValue(dbc.getPC(), offset+pc); break; case ARETURN: case DRETURN: case FRETURN: case IRETURN: case LRETURN: seenTransferOfControl = true; setReachOnlyByBranch(true); pop(); break; case MONITORENTER: case MONITOREXIT: case POP: case PUTSTATIC: pop(); break; case IF_ACMPEQ: case IF_ACMPNE: case IF_ICMPEQ: case IF_ICMPNE: case IF_ICMPLT: case IF_ICMPLE: case IF_ICMPGT: case IF_ICMPGE: { seenTransferOfControl = true; pop(2); int branchTarget = dbc.getBranchTarget(); addJumpValue(dbc.getPC(), branchTarget); break; } case POP2: it = pop(); if (it.getSize() == 1) pop(); break; case PUTFIELD: pop(2); break; case IALOAD: case SALOAD: pop(2); push(new Item("I")); break; case DUP: handleDup(); break; case DUP2: handleDup2(); break; case DUP_X1: handleDupX1(); break; case DUP_X2: handleDupX2(); break; case DUP2_X1: handleDup2X1(); break; case DUP2_X2: handleDup2X2(); break; case IINC: register = dbc.getRegisterOperand(); it = getLVValue( register ); it2 = new Item("I", dbc.getIntConstant()); pushByIntMath(dbc, IADD, it2, it); pushByLocalStore(register); break; case ATHROW: pop(); seenTransferOfControl = true; setReachOnlyByBranch(true); setTop(true); break; case CHECKCAST: { String castTo = dbc.getClassConstantOperand(); if (castTo.charAt(0) != '[') castTo = "L" + castTo + ";"; it = new Item(pop()); it.signature = castTo; push(it); break; } case NOP: break; case RET: case RETURN: seenTransferOfControl = true; setReachOnlyByBranch(true); break; case GOTO: case GOTO_W: seenTransferOfControl = true; setReachOnlyByBranch(true); addJumpValue(dbc.getPC(), dbc.getBranchTarget()); stack.clear(); setTop(true); break; case SWAP: handleSwap(); break; case ICONST_M1: case ICONST_0: case ICONST_1: case ICONST_2: case ICONST_3: case ICONST_4: case ICONST_5: push(new Item("I", (seen-ICONST_0))); break; case LCONST_0: case LCONST_1: push(new Item("J", (long)(seen-LCONST_0))); break; case DCONST_0: case DCONST_1: push(new Item("D", (double)(seen-DCONST_0))); break; case FCONST_0: case FCONST_1: case FCONST_2: push(new Item("F", (float)(seen-FCONST_0))); break; case ACONST_NULL: push(new Item()); break; case ASTORE: case DSTORE: case FSTORE: case ISTORE: case LSTORE: pushByLocalStore(dbc.getRegisterOperand()); break; case ASTORE_0: case ASTORE_1: case ASTORE_2: case ASTORE_3: pushByLocalStore(seen - ASTORE_0); break; case DSTORE_0: case DSTORE_1: case DSTORE_2: case DSTORE_3: pushByLocalStore(seen - DSTORE_0); break; case FSTORE_0: case FSTORE_1: case FSTORE_2: case FSTORE_3: pushByLocalStore(seen - FSTORE_0); break; case ISTORE_0: case ISTORE_1: case ISTORE_2: case ISTORE_3: pushByLocalStore(seen - ISTORE_0); break; case LSTORE_0: case LSTORE_1: case LSTORE_2: case LSTORE_3: pushByLocalStore(seen - LSTORE_0); break; case GETFIELD: { FieldSummary fieldSummary = AnalysisContext.currentAnalysisContext().getFieldSummary(); XField fieldOperand = dbc.getXFieldOperand(); if (fieldOperand != null && fieldSummary.isComplete() && !fieldOperand.isPublic()) { OpcodeStack.Item item = fieldSummary.getSummary(fieldOperand); if (item != null) { Item addr = pop(); Item itm = new Item(item); itm.setLoadedFromField(fieldOperand, addr.getRegisterNumber()); push(itm); break; } } Item item = pop(); int reg = item.getRegisterNumber(); push(new Item(dbc.getSigConstantOperand(), FieldAnnotation.fromReferencedField(dbc), reg)); } break; case ARRAYLENGTH: { pop(); Item v = new Item("I"); v.setSpecialKind(Item.NON_NEGATIVE); push(v); } break; case BALOAD: { pop(2); Item v = new Item("I"); v.setSpecialKind(Item.SIGNED_BYTE); push(v); break; } case CALOAD: pop(2); push(new Item("I")); break; case DALOAD: pop(2); push(new Item("D")); break; case FALOAD: pop(2); push(new Item("F")); break; case LALOAD: pop(2); push(new Item("J")); break; case AASTORE: case BASTORE: case CASTORE: case DASTORE: case FASTORE: case IASTORE: case LASTORE: case SASTORE: pop(3); break; case BIPUSH: case SIPUSH: push(new Item("I", (Integer)dbc.getIntConstant())); break; case IADD: case ISUB: case IMUL: case IDIV: case IAND: case IOR: case IXOR: case ISHL: case ISHR: case IREM: case IUSHR: it = pop(); it2 = pop(); pushByIntMath(dbc, seen, it2, it); break; case INEG: it = pop(); if (it.getConstant() instanceof Integer) { push(new Item("I", ( Integer)(-(Integer) it.getConstant()))); } else { push(new Item("I")); } break; case LNEG: it = pop(); if (it.getConstant() instanceof Long) { push(new Item("J", ( Long)(-(Long) it.getConstant()))); } else { push(new Item("J")); } break; case FNEG: it = pop(); if (it.getConstant() instanceof Float) { push(new Item("F", ( Float)(-(Float) it.getConstant()))); } else { push(new Item("F")); } break; case DNEG: it = pop(); if (it.getConstant() instanceof Double) { push(new Item("D", ( Double)(-(Double) it.getConstant()))); } else { push(new Item("D")); } break; case LADD: case LSUB: case LMUL: case LDIV: case LAND: case LOR: case LXOR: case LSHL: case LSHR: case LREM: case LUSHR: it = pop(); it2 = pop(); pushByLongMath(seen, it2, it); break; case LCMP: handleLcmp(); break; case FCMPG: case FCMPL: handleFcmp(seen); break; case DCMPG: case DCMPL: handleDcmp(seen); break; case FADD: case FSUB: case FMUL: case FDIV: case FREM: it = pop(); it2 = pop(); pushByFloatMath(seen, it, it2); break; case DADD: case DSUB: case DMUL: case DDIV: case DREM: it = pop(); it2 = pop(); pushByDoubleMath(seen, it, it2); break; case I2B: it = pop(); if (it.getConstant() != null) { it =new Item("I", (byte)constantToInt(it)); } else { it = new Item("I"); } it.setSpecialKind(Item.SIGNED_BYTE); push(it); break; case I2C: it = pop(); if (it.getConstant() != null) { it = new Item("I", (char)constantToInt(it)); } else { it = new Item("I"); } it.setSpecialKind(Item.NON_NEGATIVE); push(it); break; case I2L: case D2L: case F2L:{ it = pop(); Item newValue; if (it.getConstant() != null) { newValue = new Item("J", constantToLong(it)); } else { newValue = new Item("J"); } newValue.setSpecialKind(it.getSpecialKind()); push(newValue); } break; case I2S: it = pop(); if (it.getConstant() != null) { push(new Item("I", (short)constantToInt(it))); } else { push(new Item("I")); } break; case L2I: case D2I: case F2I: it = pop(); if (it.getConstant() != null) { push(new Item("I",constantToInt(it))); } else { push(new Item("I")); } break; case L2F: case D2F: case I2F: it = pop(); if (it.getConstant() != null) { push(new Item("F", (Float)(constantToFloat(it)))); } else { push(new Item("F")); } break; case F2D: case I2D: case L2D: it = pop(); if (it.getConstant() != null) { push(new Item("D", constantToDouble(it))); } else { push(new Item("D")); } break; case NEW: { Item item = new Item("L" + dbc.getClassConstantOperand() + ";", (Object) null); item.specialKind = Item.NEWLY_ALLOCATED; push(item); } break; case NEWARRAY: pop(); signature = "[" + BasicType.getType((byte)dbc.getIntConstant()).getSignature(); pushBySignature(signature, dbc); break; // According to the VM Spec 4.4.1, anewarray and multianewarray // can refer to normal class/interface types (encoded in // "internal form"), or array classes (encoded as signatures // beginning with "["). case ANEWARRAY: pop(); signature = dbc.getClassConstantOperand(); if (!signature.startsWith("[")) { signature = "[L" + signature + ";"; } pushBySignature(signature, dbc); break; case MULTIANEWARRAY: int dims = dbc.getIntConstant(); while ((dims--) > 0) { pop(); } signature = dbc.getClassConstantOperand(); if (!signature.startsWith("[")) { dims = dbc.getIntConstant(); signature = Util.repeat("[", dims) +"L" + signature + ";"; } pushBySignature(signature, dbc); break; case AALOAD: pop(); it = pop(); pushBySignature(it.getElementSignature(), dbc); break; case JSR: seenTransferOfControl = true; setReachOnlyByBranch(false); push(new Item("")); // push return address on stack addJumpValue(dbc.getPC(), dbc.getBranchTarget()); pop(); if (dbc.getBranchOffset() < 0) { // OK, backwards JSRs are weird; reset the stack. int stackSize = stack.size(); stack.clear(); for(int i = 0; i < stackSize; i++) stack.add(new Item()); } setTop(false); break; case INVOKEINTERFACE: case INVOKESPECIAL: case INVOKESTATIC: case INVOKEVIRTUAL: processMethodCall(dbc, seen); break; default: throw new UnsupportedOperationException("OpCode " + OPCODE_NAMES[seen] + " not supported " ); } } catch (RuntimeException e) { //If an error occurs, we clear the stack and locals. one of two things will occur. //Either the client will expect more stack items than really exist, and so they're condition check will fail, //or the stack will resync with the code. But hopefully not false positives String msg = "Error processing opcode " + OPCODE_NAMES[seen] + " @ " + dbc.getPC() + " in " + dbc.getFullyQualifiedMethodName(); AnalysisContext.logError(msg , e); if (DEBUG) e.printStackTrace(); clear(); } finally { if (DEBUG) { System.out.println(dbc.getNextPC() + "pc : " + OPCODE_NAMES[seen] + " stack depth: " + getStackDepth()); System.out.println(this); } } } /** * @param it * @return */ private int constantToInt(Item it) { return ((Number)it.getConstant()).intValue(); } /** * @param it * @return */ private float constantToFloat(Item it) { return ((Number)it.getConstant()).floatValue(); } /** * @param it * @return */ private double constantToDouble(Item it) { return ((Number)it.getConstant()).doubleValue(); } /** * @param it * @return */ private long constantToLong(Item it) { return ((Number)it.getConstant()).longValue(); } /** * handle dcmp * */ private void handleDcmp(int opcode) { Item it; Item it2; it = pop(); it2 = pop(); if ((it.getConstant() != null) && it2.getConstant() != null) { double d = (Double) it.getConstant(); double d2 = (Double) it.getConstant(); if (Double.isNaN(d) || Double.isNaN(d2)) { if (opcode == DCMPG) push(new Item("I", (Integer)(1))); else push(new Item("I", (Integer)(-1))); } if (d2 < d) push(new Item("I", (Integer) (-1) )); else if (d2 > d) push(new Item("I", (Integer)1)); else push(new Item("I", (Integer)0)); } else { push(new Item("I")); } } /** * handle fcmp * */ private void handleFcmp(int opcode) { Item it; Item it2; it = pop(); it2 = pop(); if ((it.getConstant() != null) && it2.getConstant() != null) { float f = (Float) it.getConstant(); float f2 = (Float) it.getConstant(); if (Float.isNaN(f) || Float.isNaN(f2)) { if (opcode == FCMPG) push(new Item("I", (Integer)(1))); else push(new Item("I", (Integer)(-1))); } if (f2 < f) push(new Item("I", (Integer)(-1))); else if (f2 > f) push(new Item("I", (Integer)(1))); else push(new Item("I", (Integer)(0))); } else { push(new Item("I")); } } /** * handle lcmp */ private void handleLcmp() { Item it; Item it2; it = pop(); it2 = pop(); if ((it.getConstant() != null) && it2.getConstant() != null) { long l = (Long) it.getConstant(); long l2 = (Long) it.getConstant(); if (l2 < l) push(new Item("I", (Integer)(-1))); else if (l2 > l) push(new Item("I", (Integer)(1))); else push(new Item("I", (Integer)(0))); } else { push(new Item("I")); } } /** * handle swap */ private void handleSwap() { Item i1 = pop(); Item i2 = pop(); push(i1); push(i2); } /** * handleDup */ private void handleDup() { Item it; it = pop(); push(it); push(it); } /** * handle dupX1 */ private void handleDupX1() { Item it; Item it2; it = pop(); it2 = pop(); push(it); push(it2); push(it); } /** * handle dup2 */ private void handleDup2() { Item it, it2; it = pop(); if (it.getSize() == 2) { push(it); push(it); } else { it2 = pop(); push(it2); push(it); push(it2); push(it); } } /** * handle Dup2x1 */ private void handleDup2X1() { String signature; Item it; Item it2; Item it3; it = pop(); it2 = pop(); signature = it.getSignature(); if (signature.equals("J") || signature.equals("D")) { push(it); push(it2); push(it); } else { it3 = pop(); push(it2); push(it); push(it3); push(it2); push(it); } } private void handleDup2X2() { String signature; Item it = pop(); Item it2 = pop(); if (it.isWide()) { if (it2.isWide()) { push(it); push(it2); push(it); } else { Item it3 = pop(); push(it); push(it3); push(it2); push(it); } } else { Item it3 = pop(); if (it3.isWide()) { push(it2); push(it); push(it3); push(it2); push(it); } else { Item it4 = pop(); push(it2); push(it); push(it4); push(it3); push(it2); push(it); } } } /** * Handle DupX2 */ private void handleDupX2() { String signature; Item it; Item it2; Item it3; it = pop(); it2 = pop(); signature = it2.getSignature(); if (signature.equals("J") || signature.equals("D")) { push(it); push(it2); push(it); } else { it3 = pop(); push(it); push(it3); push(it2); push(it); } } private void processMethodCall(DismantleBytecode dbc, int seen) { String clsName = dbc.getClassConstantOperand(); String methodName = dbc.getNameConstantOperand(); String signature = dbc.getSigConstantOperand(); String appenderValue = null; boolean servletRequestParameterTainted = false; boolean sawUnknownAppend = false; Item sbItem = null; boolean topIsTainted = getStackDepth() > 0 && getStackItem(0).isServletParameterTainted(); Item topItem = null; if (getStackDepth() > 0) topItem = getStackItem(0); //TODO: stack merging for trinaries kills the constant.. would be nice to maintain. if ("java/lang/StringBuffer".equals(clsName) || "java/lang/StringBuilder".equals(clsName)) { if ("<init>".equals(methodName)) { if ("(Ljava/lang/String;)V".equals(signature)) { Item i = getStackItem(0); appenderValue = (String)i.getConstant(); if (i.isServletParameterTainted()) servletRequestParameterTainted = true; } else if ("()V".equals(signature)) { appenderValue = ""; } } else if ("toString".equals(methodName) && getStackDepth() >= 1) { Item i = getStackItem(0); appenderValue = (String)i.getConstant(); if (i.isServletParameterTainted()) servletRequestParameterTainted = true; } else if ("append".equals(methodName)) { if (signature.indexOf("II)") == -1 && getStackDepth() >= 2) { sbItem = getStackItem(1); Item i = getStackItem(0); if (i.isServletParameterTainted() || sbItem.isServletParameterTainted()) servletRequestParameterTainted = true; Object sbVal = sbItem.getConstant(); Object sVal = i.getConstant(); if ((sbVal != null) && (sVal != null)) { appenderValue = sbVal + sVal.toString(); } else if (sbItem.registerNumber >= 0) { OpcodeStack.Item item = getLVValue(sbItem.registerNumber); if (item != null) item.constValue = null; } } else if (signature.startsWith("([CII)")) { sawUnknownAppend = true; sbItem = getStackItem(3); if (sbItem.registerNumber >= 0) { OpcodeStack.Item item = getLVValue(sbItem.registerNumber); if (item != null) item.constValue = null; } } else { sawUnknownAppend = true; } } } else if (seen == INVOKESPECIAL && clsName.equals("java/io/FileOutputStream") && methodName.equals("<init>") && (signature.equals("(Ljava/io/File;Z)V") || signature.equals("(Ljava/lang/String;Z)V"))) { OpcodeStack.Item item = getStackItem(0); Object value = item.getConstant(); if ( value instanceof Integer && ((Integer)value).intValue() == 1) { pop(3); Item top = getStackItem(0); if (top.signature.equals("Ljava/io/FileOutputStream;")) { top.setSpecialKind(Item.FILE_OPENED_IN_APPEND_MODE); top.source = XFactory.createReferencedXMethod(dbc); top.setPC(dbc.getPC()); } return; } } else if (seen == INVOKESPECIAL && clsName.equals("java/io/BufferedOutputStream") && methodName.equals("<init>") && signature.equals("(Ljava/io/OutputStream;)V")) { OpcodeStack.Item item = getStackItem(0); if (getStackItem(0).getSpecialKind() == Item.FILE_OPENED_IN_APPEND_MODE && getStackItem(2).signature.equals("Ljava/io/BufferedOutputStream;")) { pop(2); Item top = getStackItem(0); top.setSpecialKind(Item.FILE_OPENED_IN_APPEND_MODE); top.source = XFactory.createReferencedXMethod(dbc); top.setPC(dbc.getPC()); return; } } else if (seen == INVOKEINTERFACE && methodName.equals("getParameter") && clsName.equals("javax/servlet/http/HttpServletRequest") || clsName.equals("javax/servlet/http/ServletRequest")) { Item requestParameter = pop(); pop(); Item result = new Item("Ljava/lang/String;"); result.setServletParameterTainted(); result.source = XFactory.createReferencedXMethod(dbc); String parameterName = null; if (requestParameter.getConstant() instanceof String) parameterName = (String) requestParameter.getConstant(); result.injection = new HttpParameterInjection(parameterName, dbc.getPC()); result.setPC(dbc.getPC()); push(result); return; } else if (seen == INVOKEINTERFACE && methodName.equals("getQueryString") && clsName.equals("javax/servlet/http/HttpServletRequest") || clsName.equals("javax/servlet/http/ServletRequest")) { pop(); Item result = new Item("Ljava/lang/String;"); result.setServletParameterTainted(); result.source = XFactory.createReferencedXMethod(dbc); result.setPC(dbc.getPC()); push(result); return; } else if (seen == INVOKEINTERFACE && methodName.equals("getHeader") && clsName.equals("javax/servlet/http/HttpServletRequest") || clsName.equals("javax/servlet/http/ServletRequest")) { Item requestParameter = pop(); pop(); Item result = new Item("Ljava/lang/String;"); result.setServletParameterTainted(); result.source = XFactory.createReferencedXMethod(dbc); result.setPC(dbc.getPC()); push(result); return; } pushByInvoke(dbc, seen != INVOKESTATIC); if ((sawUnknownAppend || appenderValue != null || servletRequestParameterTainted) && getStackDepth() > 0) { Item i = this.getStackItem(0); i.constValue = appenderValue; if (!sawUnknownAppend && servletRequestParameterTainted) { i.injection = topItem.injection; i.setServletParameterTainted(); } if (sbItem != null) { i.registerNumber = sbItem.registerNumber; i.source = sbItem.source; if (i.injection == null) i.injection = sbItem.injection; if (sbItem.registerNumber >= 0) setLVValue(sbItem.registerNumber, i ); } return; } if ((clsName.equals("java/util/Random") || clsName.equals("java/security/SecureRandom")) && methodName.equals("nextInt") && signature.equals("()I")) { Item i = pop(); i.setSpecialKind(Item.RANDOM_INT); push(i); } else if (clsName.equals("java/lang/Math") && methodName.equals("abs")) { Item i = pop(); i.setSpecialKind(Item.MATH_ABS); push(i); } else if (seen == INVOKEVIRTUAL && methodName.equals("hashCode") && signature.equals("()I") || seen == INVOKESTATIC && clsName.equals("java/lang/System") && methodName.equals("identityHashCode") && signature.equals("(Ljava/lang/Object;)I")) { Item i = pop(); i.setSpecialKind(Item.HASHCODE_INT); push(i); } else if (topIsTainted && ( methodName.startsWith("encode") && clsName.equals("javax/servlet/http/HttpServletResponse") || methodName.equals("trim") && clsName.equals("java/lang/String")) ) { Item i = pop(); i.setSpecialKind(Item.SERVLET_REQUEST_TAINTED); push(i); } if (!signature.endsWith(")V")) { Item i = pop(); i.source = XFactory.createReferencedXMethod(dbc); push(i); } } private void mergeLists(List<Item> mergeInto, List<Item> mergeFrom, boolean errorIfSizesDoNotMatch) { // merge stacks int intoSize = mergeInto.size(); int fromSize = mergeFrom.size(); if (errorIfSizesDoNotMatch && intoSize != fromSize) { if (DEBUG2) { System.out.println("Bad merging items"); System.out.println("current items: " + mergeInto); System.out.println("jump items: " + mergeFrom); } } else { if (DEBUG2) { if (intoSize == fromSize) System.out.println("Merging items"); else System.out.println("Bad merging items"); System.out.println("current items: " + mergeInto); System.out.println("jump items: " + mergeFrom); } for (int i = 0; i < Math.min(intoSize, fromSize); i++) mergeInto.set(i, Item.merge(mergeInto.get(i), mergeFrom.get(i))); if (DEBUG2) { System.out.println("merged items: " + mergeInto); } } } public void clear() { stack.clear(); lvValues.clear(); } boolean encountedTop; boolean backwardsBranch; BitSet exceptionHandlers = new BitSet(); private Map<Integer, List<Item>> jumpEntries = new HashMap<Integer, List<Item>>(); private Map<Integer, List<Item>> jumpStackEntries = new HashMap<Integer, List<Item>>(); private BitSet jumpEntryLocations = new BitSet(); static class JumpInfo { final Map<Integer, List<Item>> jumpEntries; final Map<Integer, List<Item>> jumpStackEntries; final BitSet jumpEntryLocations; JumpInfo(Map<Integer, List<Item>> jumpEntries, Map<Integer, List<Item>> jumpStackEntries, BitSet jumpEntryLocations) { this.jumpEntries = jumpEntries; this.jumpStackEntries = jumpStackEntries; this.jumpEntryLocations = jumpEntryLocations; } } public static class JumpInfoFactory extends AnalysisFactory<JumpInfo> { public JumpInfoFactory() { super("Jump info for opcode stack", JumpInfo.class); } public JumpInfo analyze(IAnalysisCache analysisCache, MethodDescriptor descriptor) throws CheckedAnalysisException { Method method = analysisCache.getMethodAnalysis(Method.class, descriptor); JavaClass jclass = getJavaClass(analysisCache, descriptor.getClassDescriptor()); Code code = method.getCode(); final OpcodeStack stack = new OpcodeStack(); if (code == null) { return null; } DismantleBytecode branchAnalysis = new DismantleBytecode() { @Override public void sawOpcode(int seen) { stack.sawOpcode(this, seen); } }; branchAnalysis.setupVisitorForClass(jclass); int oldCount = 0; while (true) { stack.resetForMethodEntry0(ClassName.toSlashedClassName(jclass.getClassName()), method); branchAnalysis.doVisitMethod(method); int newCount = stack.jumpEntries.size(); if (newCount == oldCount || !stack.encountedTop || !stack.backwardsBranch) break; oldCount = newCount; } return new JumpInfo(stack.jumpEntries, stack.jumpStackEntries, stack.jumpEntryLocations); }} private void addJumpValue(int from, int target) { if (DEBUG) System.out.println("Set jump entry at " + methodName + ":" + target + "pc to " + stack + " : " + lvValues ); if (from >= target) backwardsBranch = true; List<Item> atTarget = jumpEntries.get(target); if (atTarget == null) { if (DEBUG) System.out.println("Was null"); jumpEntries.put(target, new ArrayList<Item>(lvValues)); jumpEntryLocations.set(target); if (stack.size() > 0) { jumpStackEntries.put(target, new ArrayList<Item>(stack)); } return; } mergeLists(atTarget, lvValues, false); List<Item> stackAtTarget = jumpStackEntries.get(target); if (stack.size() > 0 && stackAtTarget != null) mergeLists(stackAtTarget, stack, false); if (DEBUG) System.out.println("merge target for " + methodName + ":" + target + "pc is " + atTarget); } private String methodName; DismantleBytecode v; public void learnFrom(JumpInfo info) { jumpEntries = new HashMap<Integer, List<Item>>(info.jumpEntries); jumpStackEntries = new HashMap<Integer, List<Item>>(info.jumpStackEntries); jumpEntryLocations = (BitSet) info.jumpEntryLocations.clone(); } public void initialize() { setTop(false); jumpEntries.clear(); jumpStackEntries.clear(); jumpEntryLocations.clear(); encountedTop = false; backwardsBranch = false; lastUpdate.clear(); convertJumpToOneZeroState = convertJumpToZeroOneState = 0; zeroOneComing = false; setReachOnlyByBranch(false); } public int resetForMethodEntry(final DismantleBytecode v) { this.v = v; initialize(); int result = resetForMethodEntry0(v); Code code = v.getMethod().getCode(); if (code == null) return result; if (useIterativeAnalysis) { IAnalysisCache analysisCache = Global.getAnalysisCache(); XMethod xMethod = XFactory.createXMethod(v.getThisClass(), v.getMethod()); try { JumpInfo jump = analysisCache.getMethodAnalysis(JumpInfo.class, xMethod.getMethodDescriptor()); if (jump != null) { learnFrom(jump); } } catch (CheckedAnalysisException e) { AnalysisContext.logError("Error getting jump information", e); } } return result; } private int resetForMethodEntry0(PreorderVisitor v) { return resetForMethodEntry0(v.getClassName(), v.getMethod()); } private int resetForMethodEntry0(@SlashedClassName String className, Method m) { methodName = m.getName(); if (DEBUG) System.out.println(" --- "); String signature = m.getSignature(); stack.clear(); lvValues.clear(); top = false; encountedTop = false; backwardsBranch = false; setReachOnlyByBranch(false); seenTransferOfControl = false; exceptionHandlers.clear(); Code code = m.getCode(); if (code != null) { CodeException[] exceptionTable = code.getExceptionTable(); if (exceptionTable != null) for(CodeException ex : exceptionTable) exceptionHandlers.set(ex.getHandlerPC()); } if (DEBUG) System.out.println(" --- " + className + " " + m.getName() + " " + signature); Type[] argTypes = Type.getArgumentTypes(signature); int reg = 0; if (!m.isStatic()) { Item it = new Item("L" + className+";"); it.setInitialParameter(true); it.registerNumber = reg; setLVValue( reg, it); reg += it.getSize(); } for (Type argType : argTypes) { Item it = new Item(argType.getSignature()); it.registerNumber = reg; it.setInitialParameter(true); setLVValue(reg, it); reg += it.getSize(); } return reg; } public int getStackDepth() { return stack.size(); } public Item getStackItem(int stackOffset) { if (stackOffset < 0 || stackOffset >= stack.size()) { AnalysisContext.logError("Can't get stack offset " + stackOffset + " from " + stack.toString() +" @ " + v.getPC() + " in " + v.getFullyQualifiedMethodName(), new IllegalArgumentException()); return new Item("Lfindbugs/OpcodeStackError;"); } int tos = stack.size() - 1; int pos = tos - stackOffset; try { return stack.get(pos); } catch (ArrayIndexOutOfBoundsException e) { throw new ArrayIndexOutOfBoundsException( "Requested item at offset " + stackOffset + " in a stack of size " + stack.size() +", made request for position " + pos); } } private Item pop() { return stack.remove(stack.size()-1); } public void replaceTop(Item newTop) { pop(); push(newTop); } private void pop(int count) { while ((count--) > 0) pop(); } private void push(Item i) { stack.add(i); } private void pushByConstant(DismantleBytecode dbc, Constant c) { if (c instanceof ConstantClass) push(new Item("Ljava/lang/Class;", ((ConstantClass)c).getConstantValue(dbc.getConstantPool()))); else if (c instanceof ConstantInteger) push(new Item("I", (Integer)(((ConstantInteger) c).getBytes()))); else if (c instanceof ConstantString) { int s = ((ConstantString) c).getStringIndex(); push(new Item("Ljava/lang/String;", getStringFromIndex(dbc, s))); } else if (c instanceof ConstantFloat) push(new Item("F", (Float)(((ConstantFloat) c).getBytes()))); else if (c instanceof ConstantDouble) push(new Item("D", (Double)(((ConstantDouble) c).getBytes()))); else if (c instanceof ConstantLong) push(new Item("J", (Long)(((ConstantLong) c).getBytes()))); else throw new UnsupportedOperationException("Constant type not expected" ); } private void pushByLocalObjectLoad(DismantleBytecode dbc, int register) { Method m = dbc.getMethod(); LocalVariableTable lvt = m.getLocalVariableTable(); if (lvt != null) { LocalVariable lv = LVTHelper.getLocalVariableAtPC(lvt, register, dbc.getPC()); if (lv != null) { String signature = lv.getSignature(); pushByLocalLoad(signature, register); return; } } pushByLocalLoad("", register); } private void pushByIntMath(DismantleBytecode dbc, int seen, Item lhs, Item rhs) { Item newValue = new Item("I"); if (lhs == null || rhs == null) { push(newValue); return; } try { if (DEBUG) System.out.println("pushByIntMath: " + rhs.getConstant() + " " + lhs.getConstant() ); if ((rhs.getConstant() != null) && lhs.getConstant() != null) { Integer lhsValue = (Integer) lhs.getConstant(); Integer rhsValue = (Integer) rhs.getConstant(); if (seen == IADD) newValue = new Item("I",lhsValue + rhsValue); else if (seen == ISUB) newValue = new Item("I",lhsValue - rhsValue); else if (seen == IMUL) newValue = new Item("I", lhsValue * rhsValue); else if (seen == IDIV) newValue = new Item("I", lhsValue / rhsValue); else if (seen == IAND) { newValue = new Item("I", lhsValue & rhsValue); if ((rhsValue&0xff) == 0 && rhsValue != 0 || (lhsValue&0xff) == 0 && lhsValue != 0 ) newValue.specialKind = Item.LOW_8_BITS_CLEAR; } else if (seen == IOR) newValue = new Item("I",lhsValue | rhsValue); else if (seen == IXOR) newValue = new Item("I",lhsValue ^ rhsValue); else if (seen == ISHL) { newValue = new Item("I",lhsValue << rhsValue); if (rhsValue >= 8) newValue.specialKind = Item.LOW_8_BITS_CLEAR; } else if (seen == ISHR) newValue = new Item("I",lhsValue >> rhsValue); else if (seen == IREM) newValue = new Item("I", lhsValue % rhsValue); else if (seen == IUSHR) newValue = new Item("I", lhsValue >>> rhsValue); } else if (rhs.getConstant() != null && seen == ISHL && (Integer) rhs.getConstant() >= 8) newValue.specialKind = Item.LOW_8_BITS_CLEAR; else if (lhs.getConstant() != null && seen == IAND) { int value = (Integer) lhs.getConstant(); if (value == 0) newValue = new Item("I", 0); else if ((value & 0xff) == 0) newValue.specialKind = Item.LOW_8_BITS_CLEAR; else if (value >= 0) newValue.specialKind = Item.NON_NEGATIVE; } else if (rhs.getConstant() != null && seen == IAND) { int value = (Integer) rhs.getConstant(); if (value == 0) newValue = new Item("I", 0); else if ((value & 0xff) == 0) newValue.specialKind = Item.LOW_8_BITS_CLEAR; else if (value >= 0) newValue.specialKind = Item.NON_NEGATIVE; } else if (seen == IAND && lhs.getSpecialKind() == Item.ZERO_MEANS_NULL) { newValue.setSpecialKind(Item.ZERO_MEANS_NULL); newValue.setPC(lhs.getPC()); } else if (seen == IAND && rhs.getSpecialKind() == Item.ZERO_MEANS_NULL) { newValue.setSpecialKind(Item.ZERO_MEANS_NULL); newValue.setPC(rhs.getPC()); } else if (seen == IOR && lhs.getSpecialKind() == Item.NONZERO_MEANS_NULL) { newValue.setSpecialKind(Item.NONZERO_MEANS_NULL); newValue.setPC(lhs.getPC()); } else if (seen == IOR && rhs.getSpecialKind() == Item.NONZERO_MEANS_NULL) { newValue.setSpecialKind(Item.NONZERO_MEANS_NULL); newValue.setPC(rhs.getPC()); } } catch (ArithmeticException e) { assert true; // ignore it } catch (RuntimeException e) { String msg = "Error processing2 " + lhs + OPCODE_NAMES[seen] + rhs + " @ " + dbc.getPC() + " in " + dbc.getFullyQualifiedMethodName(); AnalysisContext.logError(msg , e); } if (lhs.specialKind == Item.INTEGER_SUM && rhs.getConstant() != null ) { int rhsValue = (Integer) rhs.getConstant(); if (seen == IDIV && rhsValue ==2 || seen == ISHR && rhsValue == 1) newValue.specialKind = Item.AVERAGE_COMPUTED_USING_DIVISION; } if (seen == IADD && newValue.specialKind == 0 && lhs.getConstant() == null && rhs.getConstant() == null ) newValue.specialKind = Item.INTEGER_SUM; if (seen == IREM && lhs.specialKind == Item.HASHCODE_INT) newValue.specialKind = Item.HASHCODE_INT_REMAINDER; if (seen == IREM && lhs.specialKind == Item.RANDOM_INT) newValue.specialKind = Item.RANDOM_INT_REMAINDER; if (DEBUG) System.out.println("push: " + newValue); newValue.setPC(dbc.getPC()); push(newValue); } private void pushByLongMath(int seen, Item lhs, Item rhs) { Item newValue = new Item("J"); try { if ((rhs.getConstant() != null) && lhs.getConstant() != null) { Long lhsValue = ((Long) lhs.getConstant()); if (seen == LSHL) { newValue =new Item("J", lhsValue << ((Number) rhs.getConstant()).intValue()); if (((Number) rhs.getConstant()).intValue() >= 8) newValue.specialKind = Item.LOW_8_BITS_CLEAR; } else if (seen == LSHR) newValue =new Item("J", lhsValue >> ((Number) rhs.getConstant()).intValue()); else if (seen == LUSHR) newValue =new Item("J", lhsValue >>> ((Number) rhs.getConstant()).intValue()); else { Long rhsValue = ((Long) rhs.getConstant()); if (seen == LADD) newValue = new Item("J", lhsValue + rhsValue); else if (seen == LSUB) newValue = new Item("J", lhsValue - rhsValue); else if (seen == LMUL) newValue = new Item("J", lhsValue * rhsValue); else if (seen == LDIV) newValue =new Item("J", lhsValue / rhsValue); else if (seen == LAND) { newValue = new Item("J", lhsValue & rhsValue); if ((rhsValue&0xff) == 0 && rhsValue != 0 || (lhsValue&0xff) == 0 && lhsValue != 0 ) newValue.specialKind = Item.LOW_8_BITS_CLEAR; } else if (seen == LOR) newValue = new Item("J", lhsValue | rhsValue); else if (seen == LXOR) newValue =new Item("J", lhsValue ^ rhsValue); else if (seen == LREM) newValue =new Item("J", lhsValue % rhsValue); } } else if (rhs.getConstant() != null && seen == LSHL && ((Integer) rhs.getConstant()) >= 8) newValue.specialKind = Item.LOW_8_BITS_CLEAR; else if (lhs.getConstant() != null && seen == LAND && (((Long) lhs.getConstant()) & 0xff) == 0) newValue.specialKind = Item.LOW_8_BITS_CLEAR; else if (rhs.getConstant() != null && seen == LAND && (((Long) rhs.getConstant()) & 0xff) == 0) newValue.specialKind = Item.LOW_8_BITS_CLEAR; } catch (RuntimeException e) { // ignore it } push(newValue); } private void pushByFloatMath(int seen, Item it, Item it2) { Item result; int specialKind = Item.FLOAT_MATH; if ((it.getConstant() instanceof Float) && it2.getConstant() instanceof Float) { if (seen == FADD) result =new Item("F", ((Float) it2.getConstant()) + ((Float) it.getConstant())); else if (seen == FSUB) result =new Item("F", ((Float) it2.getConstant()) - ((Float) it.getConstant())); else if (seen == FMUL) result =new Item("F", ((Float) it2.getConstant()) * ((Float) it.getConstant())); else if (seen == FDIV) result =new Item("F", ((Float) it2.getConstant()) / ((Float) it.getConstant())); else if (seen == FREM) result =new Item("F", ((Float) it2.getConstant()) % ((Float) it.getConstant())); else result =new Item("F"); } else { result =new Item("F"); if (seen == DDIV) specialKind = Item.NASTY_FLOAT_MATH; } result.setSpecialKind(specialKind); push(result); } private void pushByDoubleMath(int seen, Item it, Item it2) { Item result; int specialKind = Item.FLOAT_MATH; if ((it.getConstant() instanceof Double) && it2.getConstant() instanceof Double) { if (seen == DADD) result = new Item("D", ((Double) it2.getConstant()) + ((Double) it.getConstant())); else if (seen == DSUB) result = new Item("D", ((Double) it2.getConstant()) - ((Double) it.getConstant())); else if (seen == DMUL) result = new Item("D", ((Double) it2.getConstant()) * ((Double) it.getConstant())); else if (seen == DDIV) result = new Item("D", ((Double) it2.getConstant()) / ((Double) it.getConstant())); else if (seen == DREM) result = new Item("D", ((Double) it2.getConstant()) % ((Double) it.getConstant())); else result = new Item("D"); //? } else { result = new Item("D"); if (seen == DDIV) specialKind = Item.NASTY_FLOAT_MATH; } result.setSpecialKind(specialKind); push(result); } private void pushByInvoke(DismantleBytecode dbc, boolean popThis) { String signature = dbc.getSigConstantOperand(); if (dbc.getNameConstantOperand().equals("<init>") && signature.endsWith(")V") && popThis) { pop(PreorderVisitor.getNumberArguments(signature)); Item constructed = pop(); if (getStackDepth() > 0) { Item next = getStackItem(0); if (constructed.equals(next)) next.source = XFactory.createReferencedXMethod(dbc); } return; } pop(PreorderVisitor.getNumberArguments(signature)+(popThis ? 1 : 0)); pushBySignature(Type.getReturnType(signature).getSignature(), dbc); } private String getStringFromIndex(DismantleBytecode dbc, int i) { ConstantUtf8 name = (ConstantUtf8) dbc.getConstantPool().getConstant(i); return name.getBytes(); } private void pushBySignature(String s, DismantleBytecode dbc) { if ("V".equals(s)) return; Item item = new Item(s, (Object) null); if (dbc != null) item.setPC(dbc.getPC()); push(item); } private void pushByLocalStore(int register) { Item it = pop(); if (it.getRegisterNumber() != register) { for(Item i : lvValues) if (i != null) { if (i.registerNumber == register) i.registerNumber = -1; if (i.fieldLoadedFromRegister == register) i.fieldLoadedFromRegister = -1; } for(Item i : stack) if (i != null) { if (i.registerNumber == register) i.registerNumber = -1; if (i.fieldLoadedFromRegister == register) i.fieldLoadedFromRegister = -1; } } setLVValue( register, it ); } private void pushByLocalLoad(String signature, int register) { Item it = getLVValue(register); if (it == null) { Item item = new Item(signature); item.registerNumber = register; push(item); } else if (it.getRegisterNumber() >= 0) push(it); else { push(new Item(it, register)); } } private void setLVValue(int index, Item value ) { int addCount = index - lvValues.size() + 1; while ((addCount--) > 0) lvValues.add(null); if (!useIterativeAnalysis && seenTransferOfControl) value = Item.merge(value, lvValues.get(index) ); lvValues.set(index, value); } private Item getLVValue(int index) { if (index >= lvValues.size()) return new Item(); return lvValues.get(index); } /** * @param top The top to set. */ private void setTop(boolean top) { if (top) { if (!this.top) this.top = true; } else if (this.top) this.top = false; } /** * @return Returns the top. */ public boolean isTop() { if (top) return true; return false; } /** * @param reachOnlyByBranch The reachOnlyByBranch to set. */ void setReachOnlyByBranch(boolean reachOnlyByBranch) { if (reachOnlyByBranch) setTop(true); this.reachOnlyByBranch = reachOnlyByBranch; } /** * @return Returns the reachOnlyByBranch. */ boolean isReachOnlyByBranch() { return reachOnlyByBranch; } } // vim:ts=4
remove debugging code git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@9658 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3
findbugs/src/java/edu/umd/cs/findbugs/OpcodeStack.java
remove debugging code
Java
lgpl-2.1
eea1446b3cdb76436f5b7bbed21bc9e3101b93b7
0
julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine
package org.modmine.web; /* * Copyright (C) 2002-2011 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.tiles.ComponentContext; import org.apache.struts.tiles.actions.TilesAction; import org.intermine.api.InterMineAPI; import org.intermine.api.profile.InterMineBag; import org.intermine.model.bio.ResultFile; import org.intermine.model.bio.Submission; import org.intermine.model.bio.SubmissionProperty; import org.intermine.util.Util; import org.intermine.web.logic.session.SessionMethods; import org.modmine.web.logic.ModMineUtil; /** * Class that generates GBrowse track links for a List of submissions. * @author fh */ public class SubListDetailsController extends TilesAction { protected static final Logger LOG = Logger.getLogger(SubListDetailsController.class); /** * {@inheritDoc} */ @Override public ActionForward execute(ComponentContext context, ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession()); InterMineBag bag = (InterMineBag) request.getAttribute("bag"); Class c = null; try { // or use - // Class.forName(im.getObjectStore().getModel().getPackageName() + "." + bag.getType()); // Class is: interface org.intermine.model.bio.Submission c = Class.forName(bag.getQualifiedType()); } catch (ClassNotFoundException e) { e.printStackTrace(); return null; } if (!"Submission".equals(bag.getType())) { return null; } // Logic 1: query all the DccId for the list of submission in the bag, refer to // OrthologueLinkController and BioUtil Set<Submission> subs = ModMineUtil.getSubmissions(im.getObjectStore(), bag); Set<String> subDCCids = new LinkedHashSet<String>(); for (Submission sub : subs) { subDCCids.add(sub.getdCCid()); } Set<String> orgSet = new LinkedHashSet<String>(); for (Submission sub : subs) { orgSet.add(sub.getOrganism().getShortName()); } /* ======== FILES ========== */ // do the same for files associated with a submission // note: we need submission and not dccId because the gbrowse displayer uses // submissions titles. Map<Submission, List<ResultFile>> subFiles = new LinkedHashMap<Submission, List<ResultFile>>(); for (Submission sub : subs) { List<ResultFile> files = MetadataCache.getFilesByDccId(im.getObjectStore(), sub.getdCCid()); for (ResultFile file : files) { String fileName = file.getName(); int index = fileName.lastIndexOf(System.getProperty("file.separator")); file.setName(fileName.substring(index + 1)); } subFiles.put(sub, files); } request.setAttribute("files", subFiles); // /* ======== PROPERTIES ========== */ // // do the same for properties associated with a submission // // note: we need submission and not dccId because the gbrowse displayer uses // // submissions titles. Map<Submission, List<SubmissionProperty>> subProps = new LinkedHashMap<Submission, List<SubmissionProperty>>(); for (Submission sub : subs) { for (SubmissionProperty prop : sub.getProperties()) { // String subName = prop.getName(); // int index = fileName.lastIndexOf(System.getProperty("file.separator")); // file.setName(fileName.substring(index + 1)); Util.addToListMap(subProps, sub, prop); } } request.setAttribute("props", subProps); /* ======== REPOSITORY ENTRIES ========== */ // do the same for files associated with a submission // note: we need submission and not dccId because the gbrowse displayer uses // submissions titles. Map<Submission, List<String[]>> subReposited = new LinkedHashMap<Submission, List<String[]>>(); for (Submission sub : subs) { List<String[]> reposited = MetadataCache.getRepositoryEntriesByDccId(im.getObjectStore(), sub.getdCCid()); subReposited.put(sub, reposited); } request.setAttribute("reposited", subReposited); return null; } }
modmine/webapp/src/org/modmine/web/SubListDetailsController.java
package org.modmine.web; /* * Copyright (C) 2002-2011 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.tiles.ComponentContext; import org.apache.struts.tiles.actions.TilesAction; import org.intermine.api.InterMineAPI; import org.intermine.api.profile.InterMineBag; import org.intermine.model.bio.ResultFile; import org.intermine.model.bio.Submission; import org.intermine.model.bio.SubmissionProperty; import org.intermine.util.Util; import org.intermine.web.logic.session.SessionMethods; import org.modmine.web.GBrowseParser.GBrowseTrack; import org.modmine.web.logic.ModMineUtil; /** * Class that generates GBrowse track links for a List of submissions. * @author */ public class SubListDetailsController extends TilesAction { protected static final Logger LOG = Logger.getLogger(SubListDetailsController.class); /** * {@inheritDoc} */ @Override public ActionForward execute(ComponentContext context, ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession()); InterMineBag bag = (InterMineBag) request.getAttribute("bag"); Class c = null; try { // or use - // Class.forName(im.getObjectStore().getModel().getPackageName() + "." + bag.getType()); // Class is: interface org.intermine.model.bio.Submission c = Class.forName(bag.getQualifiedType()); } catch (ClassNotFoundException e) { e.printStackTrace(); return null; } if (!"Submission".equals(bag.getType())) { return null; } // Logic 1: query all the DccId for the list of submission in the bag, refer to // OrthologueLinkController and BioUtil Set<Submission> subs = ModMineUtil.getSubmissions(im.getObjectStore(), bag); Set<String> subDCCids = new LinkedHashSet<String>(); for (Submission sub : subs) { subDCCids.add(sub.getdCCid()); } Set<String> orgSet = new LinkedHashSet<String>(); for (Submission sub : subs) { orgSet.add(sub.getOrganism().getShortName()); } /* ======== FILES ========== */ // do the same for files associated with a submission // note: we need submission and not dccId because the gbrowse displayer uses // submissions titles. Map<Submission, List<ResultFile>> subFiles = new LinkedHashMap<Submission, List<ResultFile>>(); for (Submission sub : subs) { List<ResultFile> files = MetadataCache.getFilesByDccId(im.getObjectStore(), sub.getdCCid()); for (ResultFile file : files) { String fileName = file.getName(); int index = fileName.lastIndexOf(System.getProperty("file.separator")); file.setName(fileName.substring(index + 1)); } subFiles.put(sub, files); } request.setAttribute("files", subFiles); // /* ======== PROPERTIES ========== */ // // do the same for properties associated with a submission // // note: we need submission and not dccId because the gbrowse displayer uses // // submissions titles. Map<Submission, List<SubmissionProperty>> subProps = new LinkedHashMap<Submission, List<SubmissionProperty>>(); for (Submission sub : subs) { for (SubmissionProperty prop : sub.getProperties()) { String subName = prop.getName(); // int index = fileName.lastIndexOf(System.getProperty("file.separator")); // file.setName(fileName.substring(index + 1)); Util.addToListMap(subProps, sub, prop); } } request.setAttribute("props", subProps); /* ======== REPOSITORY ENTRIES ========== */ // do the same for files associated with a submission // note: we need submission and not dccId because the gbrowse displayer uses // submissions titles. Map<Submission, List<String[]>> subReposited = new LinkedHashMap<Submission, List<String[]>>(); for (Submission sub : subs) { List<String[]> reposited = MetadataCache.getRepositoryEntriesByDccId(im.getObjectStore(), sub.getdCCid()); subReposited.put(sub, reposited); } request.setAttribute("reposited", subReposited); return null; } }
cs Former-commit-id: c173a47be3e12aa3de5fc28acf4378b0f55870b0
modmine/webapp/src/org/modmine/web/SubListDetailsController.java
cs
Java
unlicense
58feeba81bd50e2f06ecee4034c79c967a2c7225
0
TheGoodlike13/goodlike-utils
package eu.goodlike.misc; import java.util.concurrent.Executor; import java.util.concurrent.Executors; /** * Global thread pools, used by various classes of this library */ public final class ThreadPools { /** * @return cached thread pool, which is best for many short tasks */ public static Executor forShortTasks() { return CACHED_EX; } /** * @return fixed thread pool with size equal to available processors, which is best for longer tasks */ public static Executor forLongTasks() { return FIXED_EX; } // PRIVATE private static final int CORE_COUNT = Runtime.getRuntime().availableProcessors(); private static final Executor CACHED_EX = Executors.newCachedThreadPool(); private static final Executor FIXED_EX = Executors.newFixedThreadPool(CORE_COUNT); private ThreadPools() { throw new AssertionError("Do not instantiate, use static methods!"); } }
src/main/java/eu/goodlike/misc/ThreadPools.java
package eu.goodlike.misc; import java.util.concurrent.Executor; import java.util.concurrent.Executors; /** * Global thread pools, used by various classes of this library */ public final class ThreadPools { /** * @return cached thread pool, which is best for many short tasks */ public static Executor forShortTasks() { return CACHED_EX; } /** * @return fixed thread pool with size equal to available processors, which is best for longer tasks */ public static Executor forLongTasks() { return FIXED_EX; } // PRIVATE private ThreadPools() { throw new AssertionError("Do not instantiate, use static methods!"); } private static final int CORE_COUNT = Runtime.getRuntime().availableProcessors(); private static final Executor CACHED_EX = Executors.newCachedThreadPool(); private static final Executor FIXED_EX = Executors.newFixedThreadPool(CORE_COUNT); }
Ordering change
src/main/java/eu/goodlike/misc/ThreadPools.java
Ordering change
Java
apache-2.0
ff5997b1b41a8cc68a56c0efa53d7be8295ff4ae
0
BITPlan/can4eve,BITPlan/can4eve,BITPlan/can4eve
/** * * This file is part of the https://github.com/BITPlan/can4eve open source project * * Copyright 2017 BITPlan GmbH https://github.com/BITPlan * * 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.bitplan.obdii; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.logging.Logger; import org.apache.commons.lang3.StringUtils; import org.junit.Ignore; import org.junit.Test; import com.bitplan.can4eve.CANInfo; import com.bitplan.can4eve.CANValue; import com.bitplan.can4eve.CANValue.DoubleValue; import com.bitplan.can4eve.CANValue.IntegerValue; import com.bitplan.can4eve.VehicleGroup; import com.bitplan.can4eve.gui.App; import com.bitplan.can4eve.gui.Group; import com.bitplan.can4eve.gui.javafx.GenericDialog; import com.bitplan.can4eve.gui.javafx.SampleApp; import com.bitplan.can4eve.gui.javafx.WaitableApp; import com.bitplan.can4eve.json.JsonManager; import com.bitplan.can4eve.json.JsonManagerImpl; import com.bitplan.can4eve.states.StopWatch; import com.bitplan.can4eve.util.TaskLaunch; import com.bitplan.i18n.Translator; import com.bitplan.obdii.Preferences.LangChoice; import com.bitplan.obdii.javafx.ChargePane; import com.bitplan.obdii.javafx.ClockPane; import com.bitplan.obdii.javafx.ClockPane.Watch; import com.bitplan.obdii.javafx.JFXCanCellStatePlot; import com.bitplan.obdii.javafx.JFXCanValueHistoryPlot; import com.bitplan.obdii.javafx.JFXStopWatch; import com.bitplan.obdii.javafx.LCDPane; import eu.hansolo.OverviewDemo; import eu.hansolo.medusa.FGauge; import eu.hansolo.medusa.Gauge; import eu.hansolo.medusa.Gauge.NeedleSize; import eu.hansolo.medusa.GaugeBuilder; import eu.hansolo.medusa.GaugeDesign; import eu.hansolo.medusa.GaugeDesign.GaugeBackground; import eu.hansolo.medusa.LcdDesign; import eu.hansolo.medusa.LcdFont; import eu.hansolo.medusa.Marker; import eu.hansolo.medusa.Marker.MarkerType; import eu.hansolo.medusa.Section; import eu.hansolo.medusa.TickLabelLocation; import eu.hansolo.medusa.TickLabelOrientation; import eu.hansolo.medusa.TickMarkType; import javafx.application.Platform; import javafx.beans.binding.Bindings; import javafx.beans.binding.LongBinding; import javafx.beans.property.DoubleProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.property.SimpleLongProperty; import javafx.fxml.FXMLLoader; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.layout.GridPane; import javafx.scene.layout.Region; import javafx.scene.paint.Color; import javafx.stage.Stage; /** * test the descriptive application gui * * @author wf * */ public class TestAppGUI { public static final int SHOW_TIME = 4000; protected static Logger LOGGER = Logger.getLogger("com.bitplan.obdii"); @Test public void testAppGUI() throws Exception { App app = App.getInstance(); assertNotNull(app); assertEquals(6, app.getMainMenu().getSubMenus().size()); assertEquals(3, app.getGroups().size()); int[] expected = { 3, 8, 1 }; int i = 0; for (Group group : app.getGroups()) { assertEquals(expected[i++], group.getForms().size()); } } @Test public void testJoin() { String langs = StringUtils.join(LangChoice.values(), ","); assertEquals("en,de,notSet", langs); } @Test public void testPreferences() { Preferences pref = new Preferences(); pref.debug = true; pref.setLanguage(LangChoice.de); String json = pref.asJson(); //System.out.println(json); assertEquals("{\n" + " \"language\": \"de\",\n" + " \"debug\": true,\n" + " \"screenPercent\": 100,\n" + " \"logDirectory\": \"can4eveLogs\",\n" + " \"screenShotDirectory\": \"can4eveScreenShots\"\n" + "}", json); JsonManager<Preferences> jmPreferences = new JsonManagerImpl<Preferences>( Preferences.class); Preferences pref2 = jmPreferences.fromJson(json); assertNotNull(pref2); assertEquals(pref2.debug, pref.debug); assertEquals(pref2.getLanguage(), pref.getLanguage()); Preferences pref3 = new Preferences(); pref3.fromMap(pref2.asMap()); assertEquals(pref3.debug, pref.debug); assertEquals(pref3.getLanguage(), pref.getLanguage()); } /** * get the plot Values * * @return * @throws Exception */ public List<CANValue<?>> getPlotValues() throws Exception { VehicleGroup vg = VehicleGroup.get("triplet"); CANInfo socInfo = vg.getCANInfoByName("SOC"); assertNotNull(socInfo); DoubleValue SOC = new DoubleValue(socInfo); CANInfo rrInfo = vg.getCANInfoByName("Range"); assertNotNull(rrInfo); IntegerValue RR = new IntegerValue(rrInfo); Calendar date = Calendar.getInstance(); final long ONE_MINUTE_IN_MILLIS = 60000;// millisecs // https://stackoverflow.com/a/9044010/1497139 long t = date.getTimeInMillis(); for (int i = 0; i < 50; i++) { Date timeStamp = new Date(t + (i * ONE_MINUTE_IN_MILLIS)); SOC.setValue(90 - i * 1.2, timeStamp); RR.setValue(90 - i, timeStamp); } List<CANValue<?>> plotValues = new ArrayList<CANValue<?>>(); plotValues.add(SOC); plotValues.add(RR); return plotValues; } // Swing Version of things /* * @Test public void testLineChart() throws Exception { List<CANValue<?>> * plotValues = this.getPlotValues(); String title = "SOC/RR"; String xTitle = * "time"; String yTitle = "%/km"; final CANValueHistoryPlot valuePlot = new * CANValueHistoryPlot(title, xTitle, yTitle, plotValues); final PanelFrame * plotDemo = new PanelFrame(false); plotDemo.show(valuePlot.getPanel()); * plotDemo.waitOpen(); Thread.sleep(5000); plotDemo.frame.setVisible(false); * } */ @Test public void testLCDPane() throws Exception { WaitableApp.toolkitInit(); int cols=3; int rows=4; String[] texts=new String[rows*cols]; for (int row=0;row<rows;row++) { for (int col=0;col<cols;col++) { texts[row*cols+col]=String.format("row %2d col %2d",row,col); } } LCDPane lcdPane=new LCDPane(rows,cols,250,30,LcdFont.STANDARD,"rpm",texts); SampleApp.createAndShow("LCDPane", lcdPane, SHOW_TIME); } @Test public void testBarChartJavaFx() throws Exception { VehicleGroup vg = VehicleGroup.get("triplet"); CANInfo cellInfo = vg.getCANInfoByName("CellTemperature"); assertNotNull(cellInfo); DoubleValue cellTemp = new DoubleValue(cellInfo); Date timeStamp = new Date(); for (int i = 0; i < cellTemp.canInfo.getMaxIndex(); i++) { cellTemp.setValue(i, 15 + Math.random() * 15, timeStamp); } String title = "Cell Temperature"; String xTitle = "cell"; String yTitle = "° Celsius"; SampleApp.toolkitInit(); final JFXCanCellStatePlot valuePlot = new JFXCanCellStatePlot(title, xTitle, yTitle, cellTemp, 2.0, 0.5); SampleApp sampleApp = new SampleApp("Cell Temperature", valuePlot.getBarChart()); sampleApp.show(); sampleApp.waitOpen(); Thread.sleep(SHOW_TIME); sampleApp.close(); } @Test public void testMedusa() throws Exception { WaitableApp.toolkitInit(); OverviewDemo demo = new OverviewDemo(); demo.init(); GridPane demoPane = demo.getDemoPane(); SampleApp.createAndShow("Controls", demoPane,SHOW_TIME); } @Test public void testGauge() throws InterruptedException { WaitableApp.toolkitInit(); GridPane pane = new GridPane(); Gauge gauge = GaugeBuilder.create().minValue(0).maxValue(100) .tickLabelDecimals(0).decimals(1).autoScale(true).animated(true) // .backgroundPaint(Color.TRANSPARENT) // .borderPaint(Color.LIGHTGRAY) // .knobColor(Color.rgb(0, 90, 120)) .shadowsEnabled(true) // .tickLabelColor(Color.rgb(0, 175, 248)) // .ledColor(Color.rgb(0, 175, 248)) .ledVisible(true).ledBlinking(true).sectionsVisible(true) .sections(new Section(75, 100, Color.rgb(139, 195, 102, 0.5))) .areasVisible(true) .areas(new Section(0.00, 25, Color.rgb(234, 83, 79, 0.5))) .majorTickMarkColor(Color.MAGENTA) // .minorTickMarkColor(Color.rgb(0, 175, 248)) .majorTickMarkType(TickMarkType.TRAPEZOID) .mediumTickMarkType(TickMarkType.DOT) .minorTickMarkType(TickMarkType.LINE) .tickLabelOrientation(TickLabelOrientation.ORTHOGONAL) .tickMarkSections(new Section(0.25, 0.5, Color.rgb(241, 161, 71))) .tickMarkSectionsVisible(true) .markers(new Marker(0.5, "", Color.CYAN, MarkerType.TRIANGLE)) .markersVisible(true) // .majorTickMarksVisible(true) // .minorTickMarksVisible(true) .tickLabelLocation(TickLabelLocation.INSIDE) // .tickLabelsVisible(true) .tickLabelSections(new Section(0.1, 0.3, Color.rgb(0, 175, 248))) // .tickLabelSectionsVisible(true) .title("SOC") // .titleColor(Color.rgb(223, 223, 223)) .unit("%").lcdDesign(LcdDesign.SECTIONS).lcdVisible(true) .lcdFont(LcdFont.STANDARD) // .unitColor(Color.rgb(223, 223, 223)) // .valueColor(Color.rgb(223, 223, 223)) .needleSize(NeedleSize.THICK).build(); FGauge framedGauge = new FGauge(gauge, GaugeDesign.ENZO, GaugeBackground.DARK_GRAY); pane.add(framedGauge, 0, 0); DoubleProperty dproperty = new SimpleDoubleProperty(85.0); SampleApp sampleApp = new SampleApp("Gauge", pane, 67, 2, 2); sampleApp.show(); sampleApp.waitOpen(); Stage stage = sampleApp.getStage(); framedGauge.prefWidthProperty().bind(stage.widthProperty()); framedGauge.prefHeightProperty().bind(stage.heightProperty()); gauge.valueProperty().bind(dproperty); while (stage.isShowing()) { Thread.sleep(15); Platform.runLater(() -> dproperty.setValue(dproperty.getValue() - 0.1)); if (dproperty.getValue() < 45) sampleApp.close(); } } @Test public void testClockPanel() throws Exception { WaitableApp.toolkitInit(); Translator.initialize(Preferences.getInstance().getLanguage().name()); ClockPane clockPane = new ClockPane(); clockPane.setWatch(Watch.Charging, 1320 * 1000); clockPane.setWatch(Watch.Parking, 390 * 1000); SampleApp sampleApp = new SampleApp("Clocks", clockPane); sampleApp.show(); sampleApp.waitOpen(); for (int i = 0; i < (SHOW_TIME / 1000 * 2); i++) { Thread.sleep(1000); clockPane.setWatch(Watch.Moving, i * 1000 + 300 * 1000); } sampleApp.close(); } @Test public void testChargePanel() throws Exception { WaitableApp.toolkitInit(); Translator.initialize(Preferences.getInstance().getLanguage().name()); ChargePane chargePane = new ChargePane(); SimpleDoubleProperty sd = new SimpleDoubleProperty(); SimpleDoubleProperty rr = new SimpleDoubleProperty(); chargePane.getGaugeMap().get("SOC").valueProperty().bind(sd); chargePane.getGaugeMap().get("Range").valueProperty().bind(rr); sd.setValue(100); SampleApp sampleApp = new SampleApp("Charge", chargePane); sampleApp.show(); sampleApp.waitOpen(); int loops = SHOW_TIME / 50 * 2; for (int i = 0; i < loops; i++) { Thread.sleep(50); double newValue = 100 - (95 * i / loops); // LOGGER.log(Level.INFO, "new value "+newValue); sd.setValue(newValue); rr.setValue(newValue*0.9); } sampleApp.close(); } @Test public void testLineChartJavaFx() throws Exception { List<CANValue<?>> plotValues = this.getPlotValues(); String title = "SOC/RR"; String xTitle = "time"; String yTitle = "%/km"; SampleApp.toolkitInit(); final JFXCanValueHistoryPlot valuePlot = new JFXCanValueHistoryPlot(title, xTitle, yTitle, plotValues); SampleApp sampleApp = new SampleApp("SOC/RR", valuePlot.getLineChart()); sampleApp.show(); sampleApp.waitOpen(); Thread.sleep(SHOW_TIME); sampleApp.close(); } public static ArrayList<Node> getAllNodes(Parent root) { ArrayList<Node> nodes = new ArrayList<Node>(); addAllDescendents(root, nodes); return nodes; } private static void addAllDescendents(Parent parent, ArrayList<Node> nodes) { for (Node node : parent.getChildrenUnmodifiable()) { nodes.add(node); if (node instanceof Parent) addAllDescendents((Parent) node, nodes); } } @Test public void testFXML() throws Exception { WaitableApp.toolkitInit(); Parent root = FXMLLoader.load( getClass().getResource("/com/bitplan/can4eve/gui/connection.fxml")); assertNotNull(root); ArrayList<Node> nodes = getAllNodes(root); assertEquals(8, nodes.size()); SampleApp.createAndShow("FXML", (Region) root, SHOW_TIME); } @Test public void testStopWatch() { WaitableApp.toolkitInit(); StopWatch stopWatch = new JFXStopWatch("test"); stopWatch.halt(); stopWatch.reset(); // System.out.println(stopWatch.asIsoDateStr()); // assertEquals(0l,stopWatch.getTime()); long times[] = { 90000 * 1000, 7200000, 0, 2000, 500, 1000, 2000 }; for (long time : times) { stopWatch.setTime(time); // System.out.println(stopWatch.asIsoDateStr()); assertEquals(time, stopWatch.getTime()); } } @Ignore // if enable would actually call e-mail software public void testSupportMail() { try { throw new Exception("a problem!"); } catch (Throwable th) { String exceptionText = GenericDialog.getStackTraceText(th); // needs software version to work! GenericDialog.sendReport(null, "testSupportMail", exceptionText); } } Integer counter = 0; boolean running = false; public Integer increment() { running = true; while (running) { counter++; try { Thread.sleep(1); } catch (InterruptedException e) { } } return counter; } /** * @throws Exception */ @SuppressWarnings("unchecked") @Test public void testTaskLaunch() throws Exception { WaitableApp.toolkitInit(); // https://stackoverflow.com/questions/30089593/java-fx-lambda-for-task-interface TaskLaunch<Integer> launch = TaskLaunch.start(() -> increment(), Integer.class); try { while (counter <= 10) Thread.sleep(20); } catch (InterruptedException e) { // } running = false; assertTrue(launch.getTask().get() > 10); } long calledEffect = 0; private LongBinding keepBinding; public long callMe(Number newValue) { calledEffect = newValue.longValue() + 1; return calledEffect; } @Test public void testBinding() { // WaitableApp.toolkitInit(); SimpleLongProperty lp = new SimpleLongProperty(); lp.setValue(4711); keepBinding = Bindings.createLongBinding(() -> callMe(lp.get()), lp); lp.addListener((obs, oldValue, newValue) -> callMe(newValue)); lp.setValue(1); assertEquals(2, calledEffect); assertEquals(2, keepBinding.get()); } }
obdii/src/test/java/com/bitplan/obdii/TestAppGUI.java
/** * * This file is part of the https://github.com/BITPlan/can4eve open source project * * Copyright 2017 BITPlan GmbH https://github.com/BITPlan * * 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.bitplan.obdii; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.logging.Logger; import org.apache.commons.lang3.StringUtils; import org.junit.Ignore; import org.junit.Test; import com.bitplan.can4eve.CANInfo; import com.bitplan.can4eve.CANValue; import com.bitplan.can4eve.CANValue.DoubleValue; import com.bitplan.can4eve.CANValue.IntegerValue; import com.bitplan.can4eve.VehicleGroup; import com.bitplan.can4eve.gui.App; import com.bitplan.can4eve.gui.Group; import com.bitplan.can4eve.gui.javafx.GenericDialog; import com.bitplan.can4eve.gui.javafx.SampleApp; import com.bitplan.can4eve.gui.javafx.WaitableApp; import com.bitplan.can4eve.json.JsonManager; import com.bitplan.can4eve.json.JsonManagerImpl; import com.bitplan.can4eve.states.StopWatch; import com.bitplan.can4eve.util.TaskLaunch; import com.bitplan.i18n.Translator; import com.bitplan.obdii.Preferences.LangChoice; import com.bitplan.obdii.javafx.ChargePane; import com.bitplan.obdii.javafx.ClockPane; import com.bitplan.obdii.javafx.ClockPane.Watch; import com.bitplan.obdii.javafx.JFXCanCellStatePlot; import com.bitplan.obdii.javafx.JFXCanValueHistoryPlot; import com.bitplan.obdii.javafx.JFXStopWatch; import com.bitplan.obdii.javafx.LCDPane; import eu.hansolo.OverviewDemo; import eu.hansolo.medusa.FGauge; import eu.hansolo.medusa.Gauge; import eu.hansolo.medusa.Gauge.NeedleSize; import eu.hansolo.medusa.GaugeBuilder; import eu.hansolo.medusa.GaugeDesign; import eu.hansolo.medusa.GaugeDesign.GaugeBackground; import eu.hansolo.medusa.LcdDesign; import eu.hansolo.medusa.LcdFont; import eu.hansolo.medusa.Marker; import eu.hansolo.medusa.Marker.MarkerType; import eu.hansolo.medusa.Section; import eu.hansolo.medusa.TickLabelLocation; import eu.hansolo.medusa.TickLabelOrientation; import eu.hansolo.medusa.TickMarkType; import javafx.application.Platform; import javafx.beans.binding.Bindings; import javafx.beans.binding.LongBinding; import javafx.beans.property.DoubleProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.property.SimpleLongProperty; import javafx.fxml.FXMLLoader; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.layout.GridPane; import javafx.scene.layout.Region; import javafx.scene.paint.Color; import javafx.stage.Stage; /** * test the descriptive application gui * * @author wf * */ public class TestAppGUI { public static final int SHOW_TIME = 4000; protected static Logger LOGGER = Logger.getLogger("com.bitplan.obdii"); @Test public void testAppGUI() throws Exception { App app = App.getInstance(); assertNotNull(app); assertEquals(6, app.getMainMenu().getSubMenus().size()); assertEquals(3, app.getGroups().size()); int[] expected = { 3, 8, 1 }; int i = 0; for (Group group : app.getGroups()) { assertEquals(expected[i++], group.getForms().size()); } } @Test public void testJoin() { String langs = StringUtils.join(LangChoice.values(), ","); assertEquals("en,de,notSet", langs); } @Test public void testPreferences() { Preferences pref = new Preferences(); pref.debug = true; pref.setLanguage(LangChoice.de); String json = pref.asJson(); // System.out.println(json); assertEquals("{\n" + " \"language\": \"de\",\n" + " \"debug\": true,\n" + " \"screenPercent\": 100\n" + "}", json); JsonManager<Preferences> jmPreferences = new JsonManagerImpl<Preferences>( Preferences.class); Preferences pref2 = jmPreferences.fromJson(json); assertNotNull(pref2); assertEquals(pref2.debug, pref.debug); assertEquals(pref2.getLanguage(), pref.getLanguage()); Preferences pref3 = new Preferences(); pref3.fromMap(pref2.asMap()); assertEquals(pref3.debug, pref.debug); assertEquals(pref3.getLanguage(), pref.getLanguage()); } /** * get the plot Values * * @return * @throws Exception */ public List<CANValue<?>> getPlotValues() throws Exception { VehicleGroup vg = VehicleGroup.get("triplet"); CANInfo socInfo = vg.getCANInfoByName("SOC"); assertNotNull(socInfo); DoubleValue SOC = new DoubleValue(socInfo); CANInfo rrInfo = vg.getCANInfoByName("Range"); assertNotNull(rrInfo); IntegerValue RR = new IntegerValue(rrInfo); Calendar date = Calendar.getInstance(); final long ONE_MINUTE_IN_MILLIS = 60000;// millisecs // https://stackoverflow.com/a/9044010/1497139 long t = date.getTimeInMillis(); for (int i = 0; i < 50; i++) { Date timeStamp = new Date(t + (i * ONE_MINUTE_IN_MILLIS)); SOC.setValue(90 - i * 1.2, timeStamp); RR.setValue(90 - i, timeStamp); } List<CANValue<?>> plotValues = new ArrayList<CANValue<?>>(); plotValues.add(SOC); plotValues.add(RR); return plotValues; } // Swing Version of things /* * @Test public void testLineChart() throws Exception { List<CANValue<?>> * plotValues = this.getPlotValues(); String title = "SOC/RR"; String xTitle = * "time"; String yTitle = "%/km"; final CANValueHistoryPlot valuePlot = new * CANValueHistoryPlot(title, xTitle, yTitle, plotValues); final PanelFrame * plotDemo = new PanelFrame(false); plotDemo.show(valuePlot.getPanel()); * plotDemo.waitOpen(); Thread.sleep(5000); plotDemo.frame.setVisible(false); * } */ @Test public void testLCDPane() throws Exception { WaitableApp.toolkitInit(); int cols=3; int rows=4; String[] texts=new String[rows*cols]; for (int row=0;row<rows;row++) { for (int col=0;col<cols;col++) { texts[row*cols+col]=String.format("row %2d col %2d",row,col); } } LCDPane lcdPane=new LCDPane(rows,cols,250,30,LcdFont.STANDARD,"rpm",texts); SampleApp.createAndShow("LCDPane", lcdPane, SHOW_TIME); } @Test public void testBarChartJavaFx() throws Exception { VehicleGroup vg = VehicleGroup.get("triplet"); CANInfo cellInfo = vg.getCANInfoByName("CellTemperature"); assertNotNull(cellInfo); DoubleValue cellTemp = new DoubleValue(cellInfo); Date timeStamp = new Date(); for (int i = 0; i < cellTemp.canInfo.getMaxIndex(); i++) { cellTemp.setValue(i, 15 + Math.random() * 15, timeStamp); } String title = "Cell Temperature"; String xTitle = "cell"; String yTitle = "° Celsius"; SampleApp.toolkitInit(); final JFXCanCellStatePlot valuePlot = new JFXCanCellStatePlot(title, xTitle, yTitle, cellTemp, 2.0, 0.5); SampleApp sampleApp = new SampleApp("Cell Temperature", valuePlot.getBarChart()); sampleApp.show(); sampleApp.waitOpen(); Thread.sleep(SHOW_TIME); sampleApp.close(); } @Test public void testMedusa() throws Exception { WaitableApp.toolkitInit(); OverviewDemo demo = new OverviewDemo(); demo.init(); GridPane demoPane = demo.getDemoPane(); SampleApp.createAndShow("Controls", demoPane,SHOW_TIME); } @Test public void testGauge() throws InterruptedException { WaitableApp.toolkitInit(); GridPane pane = new GridPane(); Gauge gauge = GaugeBuilder.create().minValue(0).maxValue(100) .tickLabelDecimals(0).decimals(1).autoScale(true).animated(true) // .backgroundPaint(Color.TRANSPARENT) // .borderPaint(Color.LIGHTGRAY) // .knobColor(Color.rgb(0, 90, 120)) .shadowsEnabled(true) // .tickLabelColor(Color.rgb(0, 175, 248)) // .ledColor(Color.rgb(0, 175, 248)) .ledVisible(true).ledBlinking(true).sectionsVisible(true) .sections(new Section(75, 100, Color.rgb(139, 195, 102, 0.5))) .areasVisible(true) .areas(new Section(0.00, 25, Color.rgb(234, 83, 79, 0.5))) .majorTickMarkColor(Color.MAGENTA) // .minorTickMarkColor(Color.rgb(0, 175, 248)) .majorTickMarkType(TickMarkType.TRAPEZOID) .mediumTickMarkType(TickMarkType.DOT) .minorTickMarkType(TickMarkType.LINE) .tickLabelOrientation(TickLabelOrientation.ORTHOGONAL) .tickMarkSections(new Section(0.25, 0.5, Color.rgb(241, 161, 71))) .tickMarkSectionsVisible(true) .markers(new Marker(0.5, "", Color.CYAN, MarkerType.TRIANGLE)) .markersVisible(true) // .majorTickMarksVisible(true) // .minorTickMarksVisible(true) .tickLabelLocation(TickLabelLocation.INSIDE) // .tickLabelsVisible(true) .tickLabelSections(new Section(0.1, 0.3, Color.rgb(0, 175, 248))) // .tickLabelSectionsVisible(true) .title("SOC") // .titleColor(Color.rgb(223, 223, 223)) .unit("%").lcdDesign(LcdDesign.SECTIONS).lcdVisible(true) .lcdFont(LcdFont.STANDARD) // .unitColor(Color.rgb(223, 223, 223)) // .valueColor(Color.rgb(223, 223, 223)) .needleSize(NeedleSize.THICK).build(); FGauge framedGauge = new FGauge(gauge, GaugeDesign.ENZO, GaugeBackground.DARK_GRAY); pane.add(framedGauge, 0, 0); DoubleProperty dproperty = new SimpleDoubleProperty(85.0); SampleApp sampleApp = new SampleApp("Gauge", pane, 67, 2, 2); sampleApp.show(); sampleApp.waitOpen(); Stage stage = sampleApp.getStage(); framedGauge.prefWidthProperty().bind(stage.widthProperty()); framedGauge.prefHeightProperty().bind(stage.heightProperty()); gauge.valueProperty().bind(dproperty); while (stage.isShowing()) { Thread.sleep(15); Platform.runLater(() -> dproperty.setValue(dproperty.getValue() - 0.1)); if (dproperty.getValue() < 45) sampleApp.close(); } } @Test public void testClockPanel() throws Exception { WaitableApp.toolkitInit(); Translator.initialize(Preferences.getInstance().getLanguage().name()); ClockPane clockPane = new ClockPane(); clockPane.setWatch(Watch.Charging, 1320 * 1000); clockPane.setWatch(Watch.Parking, 390 * 1000); SampleApp sampleApp = new SampleApp("Clocks", clockPane); sampleApp.show(); sampleApp.waitOpen(); for (int i = 0; i < (SHOW_TIME / 1000 * 2); i++) { Thread.sleep(1000); clockPane.setWatch(Watch.Moving, i * 1000 + 300 * 1000); } sampleApp.close(); } @Test public void testChargePanel() throws Exception { WaitableApp.toolkitInit(); Translator.initialize(Preferences.getInstance().getLanguage().name()); ChargePane chargePane = new ChargePane(); SimpleDoubleProperty sd = new SimpleDoubleProperty(); SimpleDoubleProperty rr = new SimpleDoubleProperty(); chargePane.getGaugeMap().get("SOC").valueProperty().bind(sd); chargePane.getGaugeMap().get("Range").valueProperty().bind(rr); sd.setValue(100); SampleApp sampleApp = new SampleApp("Charge", chargePane); sampleApp.show(); sampleApp.waitOpen(); int loops = SHOW_TIME / 50 * 2; for (int i = 0; i < loops; i++) { Thread.sleep(50); double newValue = 100 - (95 * i / loops); // LOGGER.log(Level.INFO, "new value "+newValue); sd.setValue(newValue); rr.setValue(newValue*0.9); } sampleApp.close(); } @Test public void testLineChartJavaFx() throws Exception { List<CANValue<?>> plotValues = this.getPlotValues(); String title = "SOC/RR"; String xTitle = "time"; String yTitle = "%/km"; SampleApp.toolkitInit(); final JFXCanValueHistoryPlot valuePlot = new JFXCanValueHistoryPlot(title, xTitle, yTitle, plotValues); SampleApp sampleApp = new SampleApp("SOC/RR", valuePlot.getLineChart()); sampleApp.show(); sampleApp.waitOpen(); Thread.sleep(SHOW_TIME); sampleApp.close(); } public static ArrayList<Node> getAllNodes(Parent root) { ArrayList<Node> nodes = new ArrayList<Node>(); addAllDescendents(root, nodes); return nodes; } private static void addAllDescendents(Parent parent, ArrayList<Node> nodes) { for (Node node : parent.getChildrenUnmodifiable()) { nodes.add(node); if (node instanceof Parent) addAllDescendents((Parent) node, nodes); } } @Test public void testFXML() throws Exception { WaitableApp.toolkitInit(); Parent root = FXMLLoader.load( getClass().getResource("/com/bitplan/can4eve/gui/connection.fxml")); assertNotNull(root); ArrayList<Node> nodes = getAllNodes(root); assertEquals(8, nodes.size()); SampleApp.createAndShow("FXML", (Region) root, SHOW_TIME); } @Test public void testStopWatch() { WaitableApp.toolkitInit(); StopWatch stopWatch = new JFXStopWatch("test"); stopWatch.halt(); stopWatch.reset(); // System.out.println(stopWatch.asIsoDateStr()); // assertEquals(0l,stopWatch.getTime()); long times[] = { 90000 * 1000, 7200000, 0, 2000, 500, 1000, 2000 }; for (long time : times) { stopWatch.setTime(time); // System.out.println(stopWatch.asIsoDateStr()); assertEquals(time, stopWatch.getTime()); } } @Ignore // if enable would actually call e-mail software public void testSupportMail() { try { throw new Exception("a problem!"); } catch (Throwable th) { String exceptionText = GenericDialog.getStackTraceText(th); // needs software version to work! GenericDialog.sendReport(null, "testSupportMail", exceptionText); } } Integer counter = 0; boolean running = false; public Integer increment() { running = true; while (running) { counter++; try { Thread.sleep(1); } catch (InterruptedException e) { } } return counter; } /** * @throws Exception */ @SuppressWarnings("unchecked") @Test public void testTaskLaunch() throws Exception { WaitableApp.toolkitInit(); // https://stackoverflow.com/questions/30089593/java-fx-lambda-for-task-interface TaskLaunch<Integer> launch = TaskLaunch.start(() -> increment(), Integer.class); try { while (counter <= 10) Thread.sleep(20); } catch (InterruptedException e) { // } running = false; assertTrue(launch.getTask().get() > 10); } long calledEffect = 0; private LongBinding keepBinding; public long callMe(Number newValue) { calledEffect = newValue.longValue() + 1; return calledEffect; } @Test public void testBinding() { // WaitableApp.toolkitInit(); SimpleLongProperty lp = new SimpleLongProperty(); lp.setValue(4711); keepBinding = Bindings.createLongBinding(() -> callMe(lp.get()), lp); lp.addListener((obs, oldValue, newValue) -> callMe(newValue)); lp.setValue(1); assertEquals(2, calledEffect); assertEquals(2, keepBinding.get()); } }
fixes testPreferences
obdii/src/test/java/com/bitplan/obdii/TestAppGUI.java
fixes testPreferences
Java
apache-2.0
abdb36360de86f80da298d95abaf5eac4882774e
0
JNOSQL/artemis
/* * Copyright 2017 Otavio Santana and others * * 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.jnosql.artemis.reflection; import org.apache.commons.lang3.builder.ToStringBuilder; import java.lang.reflect.Constructor; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.function.Function; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.toMap; class DefaultClassRepresentation implements ClassRepresentation { private final String name; private final List<String> fieldsName; private final Class<?> classInstance; private final List<FieldRepresentation> fields; private final Constructor constructor; private final Map<String, String> javaFieldGroupedByColumn; private final Map<String, FieldRepresentation> fieldsGroupedByName; private final Optional<FieldRepresentation> id; DefaultClassRepresentation(String name, List<String> fieldsName, Class<?> classInstance, List<FieldRepresentation> fields, Constructor constructor) { this.name = name; this.fieldsName = fieldsName; this.classInstance = classInstance; this.fields = fields; this.constructor = constructor; this.fieldsGroupedByName = fields.stream() .collect(toMap(FieldRepresentation::getName, Function.identity())); this.javaFieldGroupedByColumn = fields.stream() .collect(toMap(FieldRepresentation::getFieldName, FieldRepresentation::getName)); this.id = fields.stream().filter(FieldRepresentation::isId).findFirst(); } @Override public String getName() { return name; } @Override public List<String> getFieldsName() { return fieldsName; } @Override public Class<?> getClassInstance() { return classInstance; } @Override public List<FieldRepresentation> getFields() { return fields; } @Override public Constructor getConstructor() { return constructor; } @Override public String getColumnField(String javaField) throws NullPointerException { requireNonNull(javaField, "javaField is required"); return javaFieldGroupedByColumn.getOrDefault(javaField, javaField); } @Override public Map<String, FieldRepresentation> getFieldsGroupByName() { return fieldsGroupedByName; } @Override public Optional<FieldRepresentation> getId() { return id; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof DefaultClassRepresentation)) { return false; } DefaultClassRepresentation that = (DefaultClassRepresentation) o; return Objects.equals(classInstance, that.classInstance); } @Override public int hashCode() { return Objects.hashCode(classInstance); } @Override public String toString() { return new ToStringBuilder(this) .append("name", name) .append("fieldsName", fieldsName) .append("classInstance", classInstance) .append("fields", fields) .append("id", id) .append("constructor", constructor) .toString(); } /** * Creates a builder * * @return {@link ClassRepresentationBuilder} */ static ClassRepresentationBuilder builder() { return new ClassRepresentationBuilder(); } }
artemis-core/src/main/java/org/jnosql/artemis/reflection/DefaultClassRepresentation.java
/* * Copyright 2017 Otavio Santana and others * * 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.jnosql.artemis.reflection; import org.apache.commons.lang3.builder.ToStringBuilder; import java.lang.reflect.Constructor; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.function.Function; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.toMap; class DefaultClassRepresentation implements ClassRepresentation { private final String name; private final List<String> fieldsName; private final Class<?> classInstance; private final List<FieldRepresentation> fields; private final Constructor constructor; private final Map<String, String> javaFieldGroupedByColumn; private final Map<String, FieldRepresentation> fieldsGroupedByName; private final Optional<FieldRepresentation> id; DefaultClassRepresentation(String name, List<String> fieldsName, Class<?> classInstance, List<FieldRepresentation> fields, Constructor constructor) { this.name = name; this.fieldsName = fieldsName; this.classInstance = classInstance; this.fields = fields; this.constructor = constructor; this.fieldsGroupedByName = fields.stream() .collect(toMap(FieldRepresentation::getName, Function.identity())); this.javaFieldGroupedByColumn = fields.stream() .collect(toMap(FieldRepresentation::getFieldName, FieldRepresentation::getName)); this.id = fields.stream().filter(FieldRepresentation::isId).findFirst(); } @Override public String getName() { return name; } @Override public List<String> getFieldsName() { return fieldsName; } @Override public Class<?> getClassInstance() { return classInstance; } @Override public List<FieldRepresentation> getFields() { return fields; } @Override public Constructor getConstructor() { return constructor; } @Override public String getColumnField(String javaField) throws NullPointerException { requireNonNull(javaField, "javaField is required"); return javaFieldGroupedByColumn.getOrDefault(javaField, javaField); } @Override public Map<String, FieldRepresentation> getFieldsGroupByName() { return fieldsGroupedByName; } @Override public Optional<FieldRepresentation> getId() { return id; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof DefaultClassRepresentation)) { return false; } DefaultClassRepresentation that = (DefaultClassRepresentation) o; return Objects.equals(classInstance, that.classInstance); } @Override public int hashCode() { return Objects.hashCode(classInstance); } @Override public String toString() { return new ToStringBuilder(this) .append("name", name) .append("fieldsName", fieldsName) .append("classInstance", classInstance) .append("fields", fields) .append("constructor", constructor) .toString(); } /** * Creates a builder * * @return {@link ClassRepresentationBuilder} */ static ClassRepresentationBuilder builder() { return new ClassRepresentationBuilder(); } }
Fixes tests
artemis-core/src/main/java/org/jnosql/artemis/reflection/DefaultClassRepresentation.java
Fixes tests
Java
apache-2.0
11b9d45d5305bdee61b1f490ac753d9432f713dd
0
mohanaraosv/commons-pool,mohanaraosv/commons-pool,mohanaraosv/commons-pool
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool2.impl; import java.util.NoSuchElementException; import java.util.Stack; import org.apache.commons.pool2.BaseObjectPool; import org.apache.commons.pool2.ObjectPool; import org.apache.commons.pool2.PoolUtils; import org.apache.commons.pool2.PoolableObjectFactory; /** * A simple, {@link java.util.Stack Stack}-based {@link ObjectPool} implementation. * <p> * Given a {@link PoolableObjectFactory}, this class will maintain * a simple pool of instances. A finite number of "sleeping" * or idle instances is enforced, but when the pool is * empty, new instances are created to support the new load. * Hence this class places no limit on the number of "active" * instances created by the pool, but is quite useful for * re-using <tt>Object</tt>s without introducing * artificial limits. * * @author Rodney Waldhoff * @author Dirk Verbeeck * @author Sandy McArthur * @version $Revision$ $Date$ * @since Pool 1.0 */ public class StackObjectPool<T> extends BaseObjectPool<T> implements ObjectPool<T>, StackObjectPoolMBean { /** * Create a new <tt>StackObjectPool</tt> using the specified <i>factory</i> to create new instances * with the default configuration. * * @param factory the {@link PoolableObjectFactory} used to populate the pool */ public StackObjectPool(PoolableObjectFactory<T> factory) { this(factory,new StackObjectPoolConfig.Builder().createConfig()); } /** * Create a new <tt>SimpleObjectPool</tt> using the specified <i>factory</i> to create new instances, * with a user defined configuration. * * @param factory the {@link PoolableObjectFactory} used to populate the pool. * @param config the {@link StackObjectPoolConfig} used to configure the pool. */ public StackObjectPool(PoolableObjectFactory<T> factory, StackObjectPoolConfig config) { if (factory == null) { throw new IllegalArgumentException("factory must not be null"); } if (config == null) { throw new IllegalArgumentException("config must not be null"); } _factory = factory; _pool = new Stack<T>(); this.maxSleeping = config.getMaxSleeping(); _pool.ensureCapacity(config.getInitIdleCapacity() > config.getMaxSleeping() ? config.getMaxSleeping() : config.getInitIdleCapacity()); } /** * <p>Borrows an object from the pool. If there are idle instances available on the stack, * the top element of the stack is popped to activate, validate and return to the client. If there * are no idle instances available, the {@link PoolableObjectFactory#makeObject() makeObject} * method of the pool's {@link PoolableObjectFactory} is invoked to create a new instance.</p> * * <p>All instances are {@link PoolableObjectFactory#activateObject(Object) activated} and * {@link PoolableObjectFactory#validateObject(Object) validated} before being returned to the * client. If validation fails or an exception occurs activating or validating an instance * popped from the idle instance stack, the failing instance is * {@link PoolableObjectFactory#destroyObject(Object) destroyed} and the next instance on * the stack is popped, validated and activated. This process continues until either the * stack is empty or an instance passes validation. If the stack is empty on activation or * it does not contain any valid instances, the factory's <code>makeObject</code> method is used * to create a new instance. If a null instance is returned by the factory or the created * instance either raises an exception on activation or fails validation, <code>NoSuchElementException</code> * is thrown. Exceptions thrown by <code>MakeObject</code> are propagated to the caller; but * other than <code>ThreadDeath</code> or <code>VirtualMachineError</code>, exceptions generated by * activation, validation or destroy methods are swallowed silently.</p> * * @return an instance from the pool */ @Override public synchronized T borrowObject() throws Exception { assertOpen(); T obj = null; boolean newlyCreated = false; while (null == obj) { if (!_pool.empty()) { obj = _pool.pop(); } else { if(null == _factory) { throw new NoSuchElementException(); } else { obj = _factory.makeObject(); newlyCreated = true; if (obj == null) { throw new NoSuchElementException("PoolableObjectFactory.makeObject() returned null."); } } } if (null != _factory && null != obj) { try { _factory.activateObject(obj); if (!_factory.validateObject(obj)) { throw new Exception("ValidateObject failed"); } } catch (Throwable t) { PoolUtils.checkRethrow(t); try { _factory.destroyObject(obj); } catch (Throwable t2) { PoolUtils.checkRethrow(t2); // swallowed } finally { obj = null; } if (newlyCreated) { throw new NoSuchElementException( "Could not create a validated object, cause: " + t.getMessage()); } } } } _numActive++; return obj; } /** * <p>Returns an instance to the pool, pushing it on top of the idle instance stack after successful * validation and passivation. The returning instance is destroyed if any of the following are true:<ul> * <li>the pool is closed</li> * <li>{@link PoolableObjectFactory#validateObject(Object) validation} fails</li> * <li>{@link PoolableObjectFactory#passivateObject(Object) passivation} throws an exception</li> * </ul> * If adding a validated, passivated returning instance to the stack would cause * {@link #getMaxSleeping() maxSleeping} to be exceeded, the oldest (bottom) instance on the stack * is destroyed to make room for the returning instance, which is pushed on top of the stack.</p> * * <p>Exceptions passivating or destroying instances are silently swallowed. Exceptions validating * instances are propagated to the client.</p> * * @param obj instance to return to the pool */ @Override public synchronized void returnObject(T obj) throws Exception { boolean success = !isClosed(); if(null != _factory) { if(!_factory.validateObject(obj)) { success = false; } else { try { _factory.passivateObject(obj); } catch(Exception e) { success = false; } } } boolean shouldDestroy = !success; _numActive--; if (success) { T toBeDestroyed = null; if(_pool.size() >= this.maxSleeping) { shouldDestroy = true; toBeDestroyed = _pool.remove(0); // remove the stalest object } _pool.push(obj); obj = toBeDestroyed; // swap returned obj with the stalest one so it can be destroyed } notifyAll(); // _numActive has changed if(shouldDestroy) { // by constructor, shouldDestroy is false when _factory is null try { _factory.destroyObject(obj); } catch(Exception e) { // ignored } } } /** * {@inheritDoc} */ @Override public synchronized void invalidateObject(T obj) throws Exception { _numActive--; if (null != _factory) { _factory.destroyObject(obj); } notifyAll(); // _numActive has changed } /** * Return the number of instances * currently idle in this pool. * * @return the number of instances currently idle in this pool */ @Override public synchronized int getNumIdle() { return _pool.size(); } /** * Return the number of instances currently borrowed from this pool. * * @return the number of instances currently borrowed from this pool */ @Override public synchronized int getNumActive() { return _numActive; } /** * Clears any objects sitting idle in the pool. Silently swallows any * exceptions thrown by {@link PoolableObjectFactory#destroyObject(Object)}. */ @Override public synchronized void clear() { if(null != _factory) { for (T element : _pool) { try { _factory.destroyObject(element); } catch(Exception e) { // ignore error, keep destroying the rest } } } _pool.clear(); } /** * <p>Close this pool, and free any resources associated with it. Invokes * {@link #clear()} to destroy and remove instances in the pool.</p> * * <p>Calling {@link #addObject} or {@link #borrowObject} after invoking * this method on a pool will cause them to throw an * {@link IllegalStateException}.</p> * * @throws Exception never - exceptions clearing the pool are swallowed */ @Override public void close() throws Exception { super.close(); clear(); } /** * <p>Create an object, and place it on top of the stack. * This method is useful for "pre-loading" a pool with idle objects.</p> * * <p>Before being added to the pool, the newly created instance is * {@link PoolableObjectFactory#validateObject(Object) validated} and * {@link PoolableObjectFactory#passivateObject(Object) passivated}. If validation * fails, the new instance is {@link PoolableObjectFactory#destroyObject(Object) destroyed}. * Exceptions generated by the factory <code>makeObject</code> or <code>passivate</code> are * propagated to the caller. Exceptions destroying instances are silently swallowed.</p> * * <p>If a new instance is created and successfully validated and passivated and adding this * instance to the pool causes {@link #getMaxSleeping() maxSleeping} to be exceeded, the oldest * (bottom) instance in the pool is destroyed to make room for the newly created instance, which * is pushed on top of the stack. * * @throws Exception when the {@link #getFactory() factory} has a problem creating or passivating an object. */ @Override public synchronized void addObject() throws Exception { assertOpen(); if (_factory == null) { throw new IllegalStateException("Cannot add objects without a factory."); } T obj = _factory.makeObject(); boolean success = true; if(!_factory.validateObject(obj)) { success = false; } else { _factory.passivateObject(obj); } boolean shouldDestroy = !success; if (success) { T toBeDestroyed = null; if(_pool.size() >= this.maxSleeping) { shouldDestroy = true; toBeDestroyed = _pool.remove(0); // remove the stalest object } _pool.push(obj); obj = toBeDestroyed; // swap returned obj with the stalest one so it can be destroyed } notifyAll(); // _numIdle has changed if(shouldDestroy) { // by constructor, shouldDestroy is false when _factory is null try { _factory.destroyObject(obj); } catch(Exception e) { // ignored } } } /** * My pool. */ private final Stack<T> _pool; /** * My {@link PoolableObjectFactory}. */ private final PoolableObjectFactory<T> _factory; /** * cap on the number of "sleeping" instances in the pool */ private int maxSleeping; // @GuardedBy("this") /** * Number of objects borrowed but not yet returned to the pool. */ private int _numActive = 0; // @GuardedBy("this") /** * Returns the {@link PoolableObjectFactory} used by this pool to create and manage object instances. * * @return the factory * @since 1.5.5 */ public PoolableObjectFactory<T> getFactory() { return _factory; } /** * Returns the maximum number of idle instances in the pool. * * @return maxSleeping * @since 1.5.5 */ public synchronized int getMaxSleeping() { return this.maxSleeping; } /** * Sets the maximum number of idle instances in the pool. * * @param maxSleeping * @since 2.0 */ public synchronized void setMaxSleeping(int maxSleeping) { this.maxSleeping = maxSleeping; } }
src/java/org/apache/commons/pool2/impl/StackObjectPool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool2.impl; import java.util.NoSuchElementException; import java.util.Stack; import org.apache.commons.pool2.BaseObjectPool; import org.apache.commons.pool2.ObjectPool; import org.apache.commons.pool2.PoolUtils; import org.apache.commons.pool2.PoolableObjectFactory; /** * A simple, {@link java.util.Stack Stack}-based {@link ObjectPool} implementation. * <p> * Given a {@link PoolableObjectFactory}, this class will maintain * a simple pool of instances. A finite number of "sleeping" * or idle instances is enforced, but when the pool is * empty, new instances are created to support the new load. * Hence this class places no limit on the number of "active" * instances created by the pool, but is quite useful for * re-using <tt>Object</tt>s without introducing * artificial limits. * * @author Rodney Waldhoff * @author Dirk Verbeeck * @author Sandy McArthur * @version $Revision$ $Date$ * @since Pool 1.0 */ public class StackObjectPool<T> extends BaseObjectPool<T> implements ObjectPool<T>, StackObjectPoolMBean { /** * Create a new <tt>StackObjectPool</tt> using the specified <i>factory</i> to create new instances * with the default configuration. * * @param factory the {@link PoolableObjectFactory} used to populate the pool */ public StackObjectPool(PoolableObjectFactory<T> factory) { this(factory,new StackObjectPoolConfig.Builder().createConfig()); } /** * Create a new <tt>SimpleObjectPool</tt> using the specified <i>factory</i> to create new instances, * with a user defined configuration. * * @param factory the {@link PoolableObjectFactory} used to populate the pool. * @param config the {@link StackObjectPoolConfig} used to configure the pool. */ public StackObjectPool(PoolableObjectFactory<T> factory, StackObjectPoolConfig config) { if (factory == null) { throw new IllegalArgumentException("factory must not be null"); } if (config == null) { throw new IllegalArgumentException("config must not be null"); } _factory = factory; _pool = new Stack<T>(); this.maxSleeping = config.getMaxSleeping(); _pool.ensureCapacity(config.getInitIdleCapacity() > config.getMaxSleeping() ? config.getMaxSleeping() : config.getInitIdleCapacity()); } /** * <p>Borrows an object from the pool. If there are idle instances available on the stack, * the top element of the stack is popped to activate, validate and return to the client. If there * are no idle instances available, the {@link PoolableObjectFactory#makeObject() makeObject} * method of the pool's {@link PoolableObjectFactory} is invoked to create a new instance.</p> * * <p>All instances are {@link PoolableObjectFactory#activateObject(Object) activated} and * {@link PoolableObjectFactory#validateObject(Object) validated} before being returned to the * client. If validation fails or an exception occurs activating or validating an instance * popped from the idle instance stack, the failing instance is * {@link PoolableObjectFactory#destroyObject(Object) destroyed} and the next instance on * the stack is popped, validated and activated. This process continues until either the * stack is empty or an instance passes validation. If the stack is empty on activation or * it does not contain any valid instances, the factory's <code>makeObject</code> method is used * to create a new instance. If a null instance is returned by the factory or the created * instance either raises an exception on activation or fails validation, <code>NoSuchElementException</code> * is thrown. Exceptions thrown by <code>MakeObject</code> are propagated to the caller; but * other than <code>ThreadDeath</code> or <code>VirtualMachineError</code>, exceptions generated by * activation, validation or destroy methods are swallowed silently.</p> * * @return an instance from the pool */ @Override public synchronized T borrowObject() throws Exception { assertOpen(); T obj = null; boolean newlyCreated = false; while (null == obj) { if (!_pool.empty()) { obj = _pool.pop(); } else { if(null == _factory) { throw new NoSuchElementException(); } else { obj = _factory.makeObject(); newlyCreated = true; if (obj == null) { throw new NoSuchElementException("PoolableObjectFactory.makeObject() returned null."); } } } if (null != _factory && null != obj) { try { _factory.activateObject(obj); if (!_factory.validateObject(obj)) { throw new Exception("ValidateObject failed"); } } catch (Throwable t) { PoolUtils.checkRethrow(t); try { _factory.destroyObject(obj); } catch (Throwable t2) { PoolUtils.checkRethrow(t2); // swallowed } finally { obj = null; } if (newlyCreated) { throw new NoSuchElementException( "Could not create a validated object, cause: " + t.getMessage()); } } } } _numActive++; return obj; } /** * <p>Returns an instance to the pool, pushing it on top of the idle instance stack after successful * validation and passivation. The returning instance is destroyed if any of the following are true:<ul> * <li>the pool is closed</li> * <li>{@link PoolableObjectFactory#validateObject(Object) validation} fails</li> * <li>{@link PoolableObjectFactory#passivateObject(Object) passivation} throws an exception</li> * </ul> * If adding a validated, passivated returning instance to the stack would cause * {@link #getMaxSleeping() maxSleeping} to be exceeded, the oldest (bottom) instance on the stack * is destroyed to make room for the returning instance, which is pushed on top of the stack.</p> * * <p>Exceptions passivating or destroying instances are silently swallowed. Exceptions validating * instances are propagated to the client.</p> * * @param obj instance to return to the pool */ @Override public synchronized void returnObject(T obj) throws Exception { boolean success = !isClosed(); if(null != _factory) { if(!_factory.validateObject(obj)) { success = false; } else { try { _factory.passivateObject(obj); } catch(Exception e) { success = false; } } } boolean shouldDestroy = !success; _numActive--; if (success) { T toBeDestroyed = null; if(_pool.size() >= this.maxSleeping) { shouldDestroy = true; toBeDestroyed = _pool.remove(0); // remove the stalest object } _pool.push(obj); obj = toBeDestroyed; // swap returned obj with the stalest one so it can be destroyed } notifyAll(); // _numActive has changed if(shouldDestroy) { // by constructor, shouldDestroy is false when _factory is null try { _factory.destroyObject(obj); } catch(Exception e) { // ignored } } } /** * {@inheritDoc} */ @Override public synchronized void invalidateObject(T obj) throws Exception { _numActive--; if (null != _factory) { _factory.destroyObject(obj); } notifyAll(); // _numActive has changed } /** * Return the number of instances * currently idle in this pool. * * @return the number of instances currently idle in this pool */ @Override public synchronized int getNumIdle() { return _pool.size(); } /** * Return the number of instances currently borrowed from this pool. * * @return the number of instances currently borrowed from this pool */ @Override public synchronized int getNumActive() { return _numActive; } /** * Clears any objects sitting idle in the pool. Silently swallows any * exceptions thrown by {@link PoolableObjectFactory#destroyObject(Object)}. */ @Override public synchronized void clear() { if(null != _factory) { for (T element : _pool) { try { _factory.destroyObject(element); } catch(Exception e) { // ignore error, keep destroying the rest } } } _pool.clear(); } /** * <p>Close this pool, and free any resources associated with it. Invokes * {@link #clear()} to destroy and remove instances in the pool.</p> * * <p>Calling {@link #addObject} or {@link #borrowObject} after invoking * this method on a pool will cause them to throw an * {@link IllegalStateException}.</p> * * @throws Exception never - exceptions clearing the pool are swallowed */ @Override public void close() throws Exception { super.close(); clear(); } /** * <p>Create an object, and place it on top of the stack. * This method is useful for "pre-loading" a pool with idle objects.</p> * * <p>Before being added to the pool, the newly created instance is * {@link PoolableObjectFactory#validateObject(Object) validated} and * {@link PoolableObjectFactory#passivateObject(Object) passivated}. If validation * fails, the new instance is {@link PoolableObjectFactory#destroyObject(Object) destroyed}. * Exceptions generated by the factory <code>makeObject</code> or <code>passivate</code> are * propagated to the caller. Exceptions destroying instances are silently swallowed.</p> * * <p>If a new instance is created and successfully validated and passivated and adding this * instance to the pool causes {@link #getMaxSleeping() maxSleeping} to be exceeded, the oldest * (bottom) instance in the pool is destroyed to make room for the newly created instance, which * is pushed on top of the stack. * * @throws Exception when the {@link #getFactory() factory} has a problem creating or passivating an object. */ @Override public synchronized void addObject() throws Exception { assertOpen(); if (_factory == null) { throw new IllegalStateException("Cannot add objects without a factory."); } T obj = _factory.makeObject(); boolean success = true; if(!_factory.validateObject(obj)) { success = false; } else { _factory.passivateObject(obj); } boolean shouldDestroy = !success; if (success) { T toBeDestroyed = null; if(_pool.size() >= this.maxSleeping) { shouldDestroy = true; toBeDestroyed = _pool.remove(0); // remove the stalest object } _pool.push(obj); obj = toBeDestroyed; // swap returned obj with the stalest one so it can be destroyed } notifyAll(); // _numIdle has changed if(shouldDestroy) { // by constructor, shouldDestroy is false when _factory is null try { _factory.destroyObject(obj); } catch(Exception e) { // ignored } } } /** * My pool. */ private final Stack<T> _pool; /** * My {@link PoolableObjectFactory}. */ private final PoolableObjectFactory<T> _factory; /** * cap on the number of "sleeping" instances in the pool */ private int maxSleeping; // @GuardedBy("this") /** * Number of objects borrowed but not yet returned to the pool. */ private int _numActive = 0; // @GuardedBy("this") /** * Returns the {@link PoolableObjectFactory} used by this pool to create and manage object instances. * * @return the factory * @since 1.5.5 */ public synchronized PoolableObjectFactory<T> getFactory() { return _factory; } /** * Returns the maximum number of idle instances in the pool. * * @return maxSleeping * @since 1.5.5 */ public synchronized int getMaxSleeping() { return this.maxSleeping; } /** * Sets the maximum number of idle instances in the pool. * * @param maxSleeping * @since 2.0 */ public synchronized void setMaxSleeping(int maxSleeping) { this.maxSleeping = maxSleeping; } }
getFactory() method doesn't need to be synchronized since _factory is private final git-svn-id: a66ef3f0e6c00b14098e182847b4bd646263fa09@1051849 13f79535-47bb-0310-9956-ffa450edef68
src/java/org/apache/commons/pool2/impl/StackObjectPool.java
getFactory() method doesn't need to be synchronized since _factory is private final
Java
apache-2.0
192fb7a17990b3b9279772009003e505c90dd381
0
googleinterns/NeighborGood,googleinterns/NeighborGood,googleinterns/NeighborGood
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.neighborgood.helper; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; import java.util.ArrayList; import java.util.HashMap; /** * Helper class that stores the HTML depiction of tasks in groups of 10 per ArrayList index to * assist with pagination */ public class TaskPages { private static HashMap<String, String> usersNicknames; // Stores task owner's user info to prevent querying multiple times in // datastore for the same user's info private static DatastoreService datastore; private final boolean userLoggedIn; private final String userId; private int pageCount; private int taskCount; private StringBuilder page; // String-like representation of a page's worth of tasks private ArrayList<String> taskPages; public TaskPages() { this.usersNicknames = new HashMap<String, String>(); UserService userService = UserServiceFactory.getUserService(); this.userLoggedIn = userService.isUserLoggedIn(); this.userId = this.userLoggedIn ? userService.getCurrentUser().getUserId() : "null"; this.datastore = DatastoreServiceFactory.getDatastoreService(); this.taskPages = new ArrayList<String>(); this.page = new StringBuilder(); this.taskCount = 0; this.pageCount = 0; } /** addTask method adds a single task HTML string to the page variable */ public void addTask(Entity entity) { // adds current page to taskPages and starts new page if task count for current page reached 10 if (this.taskCount % 10 == 0 && this.taskCount != 0) { this.taskPages.add(page.toString()); this.page = new StringBuilder(); this.pageCount++; } page.append("<div class='task' data-key='") .append(KeyFactory.keyToString(entity.getKey())) .append("'>"); if (this.userLoggedIn) { page.append("<div class='help-overlay'>"); page.append("<div class='exit-help'><a>&times</a></div>"); page.append("<a class='confirm-help'>CONFIRM</a>"); page.append("</div>"); } page.append("<div class='task-container'>"); page.append("<div class='task-header'>"); page.append("<div class='user-nickname'>"); // Checks if tasks's user nickname has already been retrieved, // otherwise retrieves it and temporarily stores it String taskOwner = (String) entity.getProperty("Owner"); if (this.usersNicknames.containsKey(taskOwner)) { page.append(this.usersNicknames.get(taskOwner)); } else { Key taskOwnerKey = entity.getParent(); try { Entity userEntity = this.datastore.get(taskOwnerKey); String userNickname = (String) userEntity.getProperty("nickname"); this.usersNicknames.put(taskOwner, userNickname); page.append(userNickname); } catch (EntityNotFoundException e) { System.err.println( "Unable to find the task's owner info to retrieve the owner's nickname. Setting a default nickname."); page.append("Neighbor"); } } page.append("</div>"); if (this.userLoggedIn) { // changes the Help Button div if the current user is the owner of the task if (!this.userId.equals(taskOwner)) { page.append("<div class='help-out'>HELP OUT</div>"); } else { page.append( "<div class='help-out disable-help' title='This is your own task'>HELP OUT</div>"); } } page.append("</div>"); page.append( "<div class='task-content' onclick='showTaskInfo(\"" + KeyFactory.keyToString(entity.getKey()) + "\")'>") .append((String) entity.getProperty("overview")) .append("</div>"); page.append("<div class='task-footer'><div class='task-category'>#") .append((String) entity.getProperty("category")) .append("</div></div>"); page.append("</div></div>"); this.taskCount++; } /** * If there are no more tasks to add, it adds the current/last page onto the taskPages ArrayList */ public void addLastPage() { this.taskPages.add(page.toString()); this.pageCount++; } }
src/main/java/com/google/neighborgood/helper/TaskPages.java
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.neighborgood.helper; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; import java.util.ArrayList; import java.util.HashMap; /** * Helper class that stores the HTML depiction of tasks in groups of 10 per ArrayList index to * assist with pagination */ public class TaskPages { private static HashMap<String, String> usersNicknames; // Stores task owner's user info to prevent querying multiple times in // datastore for the same user's info private static DatastoreService datastore; private final boolean userLoggedIn; private final String userId; private int pageCount; private int taskCount; private StringBuilder page; // String-like representation of a page's worth of tasks private ArrayList<String> taskPages; public TaskPages() { this.usersNicknames = new HashMap<String, String>(); UserService userService = UserServiceFactory.getUserService(); this.userLoggedIn = userService.isUserLoggedIn(); this.userId = this.userLoggedIn ? userService.getCurrentUser().getUserId() : "null"; this.datastore = DatastoreServiceFactory.getDatastoreService(); this.taskPages = new ArrayList<String>(); this.page = new StringBuilder(); this.taskCount = 0; this.pageCount = 0; } /** addTask method adds a single task HTML string to the page variable */ public void addTask(Entity entity) { // adds current page to taskPages and starts new page if task count for current page reached 10 // already if (this.taskCount % 10 == 0 && this.taskCount != 0) { this.taskPages.add(page.toString()); this.page = new StringBuilder(); this.pageCount++; } page.append("<div class='task' data-key='") .append(KeyFactory.keyToString(entity.getKey())) .append("'>"); if (this.userLoggedIn) { page.append("<div class='help-overlay'>"); page.append("<div class='exit-help'><a>&times</a></div>"); page.append("<a class='confirm-help'>CONFIRM</a>"); page.append("</div>"); } page.append("<div class='task-container'>"); page.append("<div class='task-header'>"); page.append("<div class='user-nickname'>"); // Checks if tasks's user nickname has already been retrieved, // otherwise retrieves it and temporarily stores it String taskOwner = (String) entity.getProperty("Owner"); if (this.usersNicknames.containsKey(taskOwner)) { page.append(this.usersNicknames.get(taskOwner)); } else { Key taskOwnerKey = entity.getParent(); try { Entity userEntity = this.datastore.get(taskOwnerKey); String userNickname = (String) userEntity.getProperty("nickname"); this.usersNicknames.put(taskOwner, userNickname); page.append(userNickname); } catch (EntityNotFoundException e) { System.err.println( "Unable to find the task's owner info to retrieve the owner's nickname. Setting a default nickname."); page.append("Neighbor"); } } page.append("</div>"); if (this.userLoggedIn) { // changes the Help Button div if the current user is the owner of the task if (!this.userId.equals(taskOwner)) { page.append("<div class='help-out'>HELP OUT</div>"); } else { page.append( "<div class='help-out disable-help' title='This is your own task'>HELP OUT</div>"); } } page.append("</div>"); page.append( "<div class='task-content' onclick='showTaskInfo(\"" + KeyFactory.keyToString(entity.getKey()) + "\")'>") .append((String) entity.getProperty("overview")) .append("</div>"); page.append("<div class='task-footer'><div class='task-category'>#") .append((String) entity.getProperty("category")) .append("</div></div>"); page.append("</div></div>"); this.taskCount++; } /** * If there are no more tasks to add, it adds the current/last page onto the taskPages ArrayList */ public void addLastPage() { this.taskPages.add(page.toString()); this.pageCount++; } }
remove word from comment
src/main/java/com/google/neighborgood/helper/TaskPages.java
remove word from comment
Java
apache-2.0
50d9e34ae8c6626c428e258dbdcc589380cb7d7f
0
Ensembl/ensj-healthcheck,thomasmaurel/ensj-healthcheck,Ensembl/ensj-healthcheck,thomasmaurel/ensj-healthcheck,thomasmaurel/ensj-healthcheck,thomasmaurel/ensj-healthcheck,Ensembl/ensj-healthcheck,Ensembl/ensj-healthcheck
/* * Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute * * 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.ensembl.healthcheck.testcase.compara; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.Map; import java.util.Vector; import java.util.regex.Pattern; import org.ensembl.healthcheck.DatabaseRegistry; import org.ensembl.healthcheck.DatabaseRegistryEntry; import org.ensembl.healthcheck.DatabaseType; import org.ensembl.healthcheck.ReportManager; import org.ensembl.healthcheck.Species; import org.ensembl.healthcheck.Team; import org.ensembl.healthcheck.testcase.MultiDatabaseTestCase; import org.ensembl.healthcheck.util.DBUtils; /** * Check compara genome_db table against core meta one. */ public class CheckGenomeDB extends MultiDatabaseTestCase { /** * Create a new instance of MetaCrossSpecies */ public CheckGenomeDB() { addToGroup("compara_external_foreign_keys"); setDescription("Check that the properties of the genome_db table (taxon_id, assembly" + " and genebuild) correspond to the meta data in the core DB and vice versa."); setTeamResponsible(Team.COMPARA); } /** * Check that the properties of the genome_db table (taxon_id, assembly and genebuild) * correspond to the meta data in the core DB and vice versa. * NB: A warning message is displayed if some dnafrags cannot be checked because * there is not any connection to the corresponding core database. * * @param dbr * The database registry containing all the specified databases. * @return true if the all the dnafrags are top_level seq_regions in their corresponding * core database. */ public boolean run(DatabaseRegistry dbr) { boolean result = true; // Get compara DB connection DatabaseRegistryEntry[] allComparaDBs = dbr.getAll(DatabaseType.COMPARA); if (allComparaDBs.length == 0) { result = false; ReportManager.problem(this, "", "Cannot find compara database"); usage(); return false; } Map speciesDbrs = getSpeciesDatabaseMap(dbr, true); for (int i = 0; i < allComparaDBs.length; i++) { result &= checkAssemblies(allComparaDBs[i]); result &= checkGenomeDB(allComparaDBs[i], speciesDbrs); } return result; } public boolean checkAssemblies(DatabaseRegistryEntry comparaDbre) { boolean result = true; Connection comparaCon = comparaDbre.getConnection(); String comparaDbName = (comparaCon == null) ? "no_database" : DBUtils.getShortDatabaseName(comparaCon); // Get list of species with more than 1 default assembly String sql = "SELECT DISTINCT genome_db.name FROM genome_db WHERE assembly_default = 1" + " GROUP BY name HAVING count(*) <> 1"; try { Statement stmt = comparaCon.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { ReportManager.problem(this, comparaCon, "There are more than 1 default assembly for " + rs.getString(1)); result = false; } rs.close(); stmt.close(); } catch (Exception e) { e.printStackTrace(); } // Get list of species with a non-default assembly sql = "SELECT DISTINCT name FROM genome_db WHERE assembly_default = 0"; if (!Pattern.matches(".*master.*", comparaDbName)) { try { Statement stmt = comparaCon.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { ReportManager.problem(this, comparaCon, comparaDbName + " There is at least one non-default assembly for " + rs.getString(1) + " (this should not happen in the release DB)"); } rs.close(); stmt.close(); } catch (Exception e) { e.printStackTrace(); } } // Get list of species with no default assembly sql = "SELECT DISTINCT gdb1.name FROM genome_db gdb1 LEFT JOIN genome_db gdb2" + " ON (gdb1.name = gdb2.name and gdb1.assembly_default = 1 - gdb2.assembly_default)" + " WHERE gdb1.assembly_default = 0 AND gdb2.name is null"; try { Statement stmt = comparaCon.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { ReportManager.problem(this, comparaCon, "There is no default assembly for " + rs.getString(1)); result = false; } rs.close(); stmt.close(); } catch (Exception e) { e.printStackTrace(); } return result; } public boolean checkGenomeDB(DatabaseRegistryEntry comparaDbre, Map speciesDbrs) { boolean result = true; Connection comparaCon = comparaDbre.getConnection(); // Get list of species in compara Vector comparaSpecies = new Vector(); String sql = "SELECT DISTINCT genome_db.name FROM genome_db WHERE assembly_default = 1" + " AND name <> 'ancestral_sequences'"; try { Statement stmt = comparaCon.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { Species species = Species.resolveAlias(rs.getString(1).toLowerCase().replace(' ', '_')); if (species.toString().equals("unknown")) { ReportManager.problem(this, comparaCon, "No species defined for " + rs.getString(1) + " in org.ensembl.healthcheck.Species"); } else { comparaSpecies.add(species); } } rs.close(); stmt.close(); } catch (Exception e) { e.printStackTrace(); } boolean allSpeciesFound = true; for (int i = 0; i < comparaSpecies.size(); i++) { Species species = (Species) comparaSpecies.get(i); DatabaseRegistryEntry[] speciesDbr = (DatabaseRegistryEntry[]) speciesDbrs.get(species); if (speciesDbr != null) { Connection speciesCon = speciesDbr[0].getConnection(); /* Check taxon_id */ String sql1, sql2; sql1 = "SELECT \"" + species + "\", \"taxon_id\", taxon_id FROM genome_db" + " WHERE genome_db.name = \"" + species + "\" AND assembly_default = 1"; sql2 = "SELECT \"" + species + "\", \"taxon_id\", meta_value FROM meta" + " WHERE meta_key = \"species.taxonomy_id\""; result &= compareQueries(comparaCon, sql1, speciesCon, sql2); /* Check assembly */ sql1 = "SELECT \"" + species + "\", \"assembly\", assembly FROM genome_db" + " WHERE genome_db.name = \"" + species + "\" AND assembly_default = 1"; sql2 = "SELECT \"" + species + "\", \"assembly\", version FROM coord_system" + " WHERE rank=1"; result &= compareQueries(comparaCon, sql1, speciesCon, sql2); /* Check genebuild */ sql1 = "SELECT \"" + species + "\", \"genebuild\", genebuild FROM genome_db" + " WHERE genome_db.name = \"" + species + "\" AND assembly_default = 1"; sql2 = "SELECT \"" + species + "\", \"genebuild\", meta_value FROM meta" + " WHERE meta_key = \"genebuild.start_date\""; result &= compareQueries(comparaCon, sql1, speciesCon, sql2); } else { ReportManager.problem(this, comparaCon, "No connection for " + species); allSpeciesFound = false; } } if (!allSpeciesFound) { usage(); } return result; } /** * Prints the usage through the ReportManager * * @param * The database registry containing all the specified databases. * @return true if the all the dnafrags are top_level seq_regions in their corresponding * core database. */ private void usage() { ReportManager.problem(this, "USAGE", "run-healthcheck.sh -d ensembl_compara_.+ " + " -d2 .+_core_.+ CheckGenomeDB"); } } // CheckTopLevelDnaFrag
src/org/ensembl/healthcheck/testcase/compara/CheckGenomeDB.java
/* * Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute * * 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.ensembl.healthcheck.testcase.compara; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.Map; import java.util.Vector; import java.util.regex.Pattern; import org.ensembl.healthcheck.DatabaseRegistry; import org.ensembl.healthcheck.DatabaseRegistryEntry; import org.ensembl.healthcheck.DatabaseType; import org.ensembl.healthcheck.ReportManager; import org.ensembl.healthcheck.Species; import org.ensembl.healthcheck.Team; import org.ensembl.healthcheck.testcase.MultiDatabaseTestCase; import org.ensembl.healthcheck.util.DBUtils; /** * Check compara genome_db table against core meta one. */ public class CheckGenomeDB extends MultiDatabaseTestCase { /** * Create a new instance of MetaCrossSpecies */ public CheckGenomeDB() { addToGroup("compara_external_foreign_keys"); setDescription("Check that the properties of the genome_db table (taxon_id, assembly" + " and genebuild) correspond to the meta data in the core DB and vice versa."); setTeamResponsible(Team.COMPARA); } /** * Check that the properties of the genome_db table (taxon_id, assembly and genebuild) * correspond to the meta data in the core DB and vice versa. * NB: A warning message is displayed if some dnafrags cannot be checked because * there is not any connection to the corresponding core database. * * @param dbr * The database registry containing all the specified databases. * @return true if the all the dnafrags are top_level seq_regions in their corresponding * core database. */ public boolean run(DatabaseRegistry dbr) { boolean result = true; // Get compara DB connection DatabaseRegistryEntry[] allComparaDBs = dbr.getAll(DatabaseType.COMPARA); if (allComparaDBs.length == 0) { result = false; ReportManager.problem(this, "", "Cannot find compara database"); usage(); return false; } Map speciesDbrs = getSpeciesDatabaseMap(dbr, true); for (int i = 0; i < allComparaDBs.length; i++) { result &= checkAssemblies(allComparaDBs[i]); result &= checkGenomeDB(allComparaDBs[i], speciesDbrs); } return result; } public boolean checkAssemblies(DatabaseRegistryEntry comparaDbre) { boolean result = true; Connection comparaCon = comparaDbre.getConnection(); String comparaDbName = (comparaCon == null) ? "no_database" : DBUtils.getShortDatabaseName(comparaCon); // Get list of species with more than 1 default assembly String sql = "SELECT DISTINCT genome_db.name FROM genome_db WHERE assembly_default = 1" + " GROUP BY name HAVING count(*) <> 1"; try { Statement stmt = comparaCon.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { ReportManager.problem(this, comparaCon, "There are more than 1 default assembly for " + rs.getString(1)); result = false; } rs.close(); stmt.close(); } catch (Exception e) { e.printStackTrace(); } // Get list of species with a non-default assembly sql = "SELECT DISTINCT name FROM genome_db WHERE assembly_default = 0"; if (!Pattern.matches(".*master.*", comparaDbName)) { try { Statement stmt = comparaCon.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { ReportManager.problem(this, comparaCon, comparaDbName + " There is at least one non-default assembly for " + rs.getString(1) + " (this should not happen in the release DB)"); } rs.close(); stmt.close(); } catch (Exception e) { e.printStackTrace(); } } // Get list of species with no default assembly sql = "SELECT DISTINCT gdb1.name FROM genome_db gdb1 LEFT JOIN genome_db gdb2" + " ON (gdb1.name = gdb2.name and gdb1.assembly_default = 1 - gdb2.assembly_default)" + " WHERE gdb1.assembly_default = 0 AND gdb2.name is null"; try { Statement stmt = comparaCon.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { ReportManager.problem(this, comparaCon, "There is no default assembly for " + rs.getString(1)); result = false; } rs.close(); stmt.close(); } catch (Exception e) { e.printStackTrace(); } return result; } public boolean checkGenomeDB(DatabaseRegistryEntry comparaDbre, Map speciesDbrs) { boolean result = true; Connection comparaCon = comparaDbre.getConnection(); // Get list of species in compara Vector comparaSpecies = new Vector(); String sql = "SELECT DISTINCT genome_db.name FROM genome_db WHERE assembly_default = 1" + " AND name <> 'ancestral_sequences'"; try { Statement stmt = comparaCon.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { Species species = Species.resolveAlias(rs.getString(1).toLowerCase().replace(' ', '_')); if (species.toString().equals("unknown")) { ReportManager.problem(this, comparaCon, "No species defined for " + rs.getString(1) + " in org.ensembl.healthcheck.Species"); } else { comparaSpecies.add(species); } } rs.close(); stmt.close(); } catch (Exception e) { e.printStackTrace(); } boolean allSpeciesFound = true; for (int i = 0; i < comparaSpecies.size(); i++) { Species species = (Species) comparaSpecies.get(i); DatabaseRegistryEntry[] speciesDbr = (DatabaseRegistryEntry[]) speciesDbrs.get(species); if (speciesDbr != null) { Connection speciesCon = speciesDbr[0].getConnection(); /* Check taxon_id */ String sql1, sql2; sql1 = "SELECT \"" + species + "\", \"taxon_id\", taxon_id FROM genome_db" + " WHERE genome_db.name = \"" + species + "\" AND assembly_default = 1"; sql2 = "SELECT \"" + species + "\", \"taxon_id\", meta_value FROM meta" + " WHERE meta_key = \"species.taxonomy_id\""; result &= compareQueries(comparaCon, sql1, speciesCon, sql2); /* Check assembly */ sql1 = "SELECT \"" + species + "\", \"assembly\", assembly FROM genome_db" + " WHERE genome_db.name = \"" + species + "\" AND assembly_default = 1"; sql2 = "SELECT \"" + species + "\", \"assembly\", meta_value FROM meta" + " WHERE meta_key = \"assembly.default\""; result &= compareQueries(comparaCon, sql1, speciesCon, sql2); /* Check genebuild */ sql1 = "SELECT \"" + species + "\", \"genebuild\", genebuild FROM genome_db" + " WHERE genome_db.name = \"" + species + "\" AND assembly_default = 1"; sql2 = "SELECT \"" + species + "\", \"genebuild\", meta_value FROM meta" + " WHERE meta_key = \"genebuild.start_date\""; result &= compareQueries(comparaCon, sql1, speciesCon, sql2); } else { ReportManager.problem(this, comparaCon, "No connection for " + species); allSpeciesFound = false; } } if (!allSpeciesFound) { usage(); } return result; } /** * Prints the usage through the ReportManager * * @param * The database registry containing all the specified databases. * @return true if the all the dnafrags are top_level seq_regions in their corresponding * core database. */ private void usage() { ReportManager.problem(this, "USAGE", "run-healthcheck.sh -d ensembl_compara_.+ " + " -d2 .+_core_.+ CheckGenomeDB"); } } // CheckTopLevelDnaFrag
the up-to-date method of finding the assembly version is no longer from "meta" but from "coord_system"
src/org/ensembl/healthcheck/testcase/compara/CheckGenomeDB.java
the up-to-date method of finding the assembly version is no longer from "meta" but from "coord_system"
Java
apache-2.0
ee84bcb628471912e5080b1d27c89e2d37e8d9de
0
jabbrwcky/selenium,juangj/selenium,Ardesco/selenium,chrisblock/selenium,titusfortner/selenium,krmahadevan/selenium,jabbrwcky/selenium,HtmlUnit/selenium,juangj/selenium,Ardesco/selenium,joshmgrant/selenium,twalpole/selenium,mach6/selenium,GorK-ChO/selenium,oddui/selenium,chrisblock/selenium,5hawnknight/selenium,SeleniumHQ/selenium,Tom-Trumper/selenium,markodolancic/selenium,mach6/selenium,Tom-Trumper/selenium,jabbrwcky/selenium,oddui/selenium,markodolancic/selenium,chrisblock/selenium,joshbruning/selenium,Tom-Trumper/selenium,juangj/selenium,5hawnknight/selenium,asolntsev/selenium,xmhubj/selenium,markodolancic/selenium,Dude-X/selenium,twalpole/selenium,joshmgrant/selenium,Dude-X/selenium,bayandin/selenium,bayandin/selenium,juangj/selenium,chrisblock/selenium,GorK-ChO/selenium,Ardesco/selenium,joshbruning/selenium,GorK-ChO/selenium,asashour/selenium,bayandin/selenium,davehunt/selenium,krmahadevan/selenium,HtmlUnit/selenium,xmhubj/selenium,SeleniumHQ/selenium,mach6/selenium,SeleniumHQ/selenium,Dude-X/selenium,oddui/selenium,joshmgrant/selenium,valfirst/selenium,joshbruning/selenium,xmhubj/selenium,SeleniumHQ/selenium,bayandin/selenium,twalpole/selenium,5hawnknight/selenium,joshbruning/selenium,lmtierney/selenium,Dude-X/selenium,joshbruning/selenium,joshbruning/selenium,markodolancic/selenium,xmhubj/selenium,xmhubj/selenium,chrisblock/selenium,bayandin/selenium,Ardesco/selenium,valfirst/selenium,titusfortner/selenium,Ardesco/selenium,valfirst/selenium,valfirst/selenium,markodolancic/selenium,davehunt/selenium,GorK-ChO/selenium,valfirst/selenium,krmahadevan/selenium,HtmlUnit/selenium,chrisblock/selenium,jsakamoto/selenium,titusfortner/selenium,xmhubj/selenium,GorK-ChO/selenium,joshmgrant/selenium,jabbrwcky/selenium,Tom-Trumper/selenium,HtmlUnit/selenium,asolntsev/selenium,titusfortner/selenium,juangj/selenium,oddui/selenium,asolntsev/selenium,juangj/selenium,jsakamoto/selenium,markodolancic/selenium,twalpole/selenium,5hawnknight/selenium,valfirst/selenium,mach6/selenium,joshmgrant/selenium,juangj/selenium,jabbrwcky/selenium,lmtierney/selenium,jsakamoto/selenium,juangj/selenium,krmahadevan/selenium,lmtierney/selenium,valfirst/selenium,Dude-X/selenium,mach6/selenium,jabbrwcky/selenium,jsakamoto/selenium,titusfortner/selenium,davehunt/selenium,SeleniumHQ/selenium,mach6/selenium,asashour/selenium,Dude-X/selenium,twalpole/selenium,chrisblock/selenium,jabbrwcky/selenium,asolntsev/selenium,davehunt/selenium,jsakamoto/selenium,titusfortner/selenium,5hawnknight/selenium,davehunt/selenium,Ardesco/selenium,asashour/selenium,jsakamoto/selenium,jabbrwcky/selenium,jsakamoto/selenium,valfirst/selenium,Tom-Trumper/selenium,joshbruning/selenium,lmtierney/selenium,SeleniumHQ/selenium,markodolancic/selenium,Dude-X/selenium,asolntsev/selenium,markodolancic/selenium,5hawnknight/selenium,HtmlUnit/selenium,titusfortner/selenium,chrisblock/selenium,valfirst/selenium,davehunt/selenium,titusfortner/selenium,twalpole/selenium,joshmgrant/selenium,joshmgrant/selenium,5hawnknight/selenium,asashour/selenium,bayandin/selenium,lmtierney/selenium,SeleniumHQ/selenium,5hawnknight/selenium,asashour/selenium,twalpole/selenium,asolntsev/selenium,krmahadevan/selenium,bayandin/selenium,Ardesco/selenium,joshmgrant/selenium,SeleniumHQ/selenium,lmtierney/selenium,oddui/selenium,joshmgrant/selenium,joshbruning/selenium,twalpole/selenium,chrisblock/selenium,davehunt/selenium,asolntsev/selenium,5hawnknight/selenium,markodolancic/selenium,Tom-Trumper/selenium,twalpole/selenium,krmahadevan/selenium,Ardesco/selenium,jabbrwcky/selenium,Tom-Trumper/selenium,GorK-ChO/selenium,Ardesco/selenium,asashour/selenium,juangj/selenium,GorK-ChO/selenium,krmahadevan/selenium,valfirst/selenium,mach6/selenium,asashour/selenium,lmtierney/selenium,titusfortner/selenium,xmhubj/selenium,HtmlUnit/selenium,HtmlUnit/selenium,GorK-ChO/selenium,valfirst/selenium,asolntsev/selenium,krmahadevan/selenium,mach6/selenium,jsakamoto/selenium,davehunt/selenium,asolntsev/selenium,lmtierney/selenium,HtmlUnit/selenium,titusfortner/selenium,joshmgrant/selenium,Tom-Trumper/selenium,SeleniumHQ/selenium,bayandin/selenium,joshmgrant/selenium,krmahadevan/selenium,Tom-Trumper/selenium,bayandin/selenium,oddui/selenium,oddui/selenium,jsakamoto/selenium,Dude-X/selenium,titusfortner/selenium,asashour/selenium,GorK-ChO/selenium,SeleniumHQ/selenium,Dude-X/selenium,joshbruning/selenium,lmtierney/selenium,mach6/selenium,xmhubj/selenium,davehunt/selenium,SeleniumHQ/selenium,HtmlUnit/selenium,asashour/selenium,HtmlUnit/selenium,oddui/selenium,oddui/selenium,xmhubj/selenium
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.openqa.selenium; import java.io.Serializable; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class MutableCapabilities implements Capabilities, Serializable { private static final long serialVersionUID = -112816287184979465L; private static final Set<String> OPTION_KEYS; static { HashSet<String> keys = new HashSet<>(); keys.add("se:ieOptions"); keys.add("safari.options"); OPTION_KEYS = Collections.unmodifiableSet(keys); } private final Map<String, Object> caps = new HashMap<>(); public MutableCapabilities() { // no-arg constructor } public MutableCapabilities(Capabilities other) { this(other.asMap()); } public MutableCapabilities(Map<String, ?> capabilities) { capabilities.forEach((key, value) -> { if (value != null) { caps.put(key, value); } }); } @Override public Object getCapability(String capabilityName) { return caps.get(capabilityName); } @Override public Map<String, ?> asMap() { return Collections.unmodifiableMap(caps); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Capabilities)) { return false; } Capabilities that = (Capabilities) o; return caps.equals(that.asMap()); } @Override public int hashCode() { return caps.hashCode(); } /** * Merges the extra capabilities provided into this DesiredCapabilities instance. If capabilities * with the same name exist in this instance, they will be overridden by the values from the * extraCapabilities object. * * @param extraCapabilities Additional capabilities to be added. * @return DesiredCapabilities after the merge */ @Override public MutableCapabilities merge(Capabilities extraCapabilities) { if (extraCapabilities == null) { return this; } extraCapabilities.asMap().forEach(this::setCapability); return this; } public void setCapability(String capabilityName, boolean value) { setCapability(capabilityName, (Object) value); } public void setCapability(String capabilityName, String value) { setCapability(capabilityName, (Object) value); } public void setCapability(String capabilityName, Platform value) { setCapability(capabilityName, (Object) value); } public void setCapability(String key, Object value) { // We have to special-case some keys and values because of the popular idiom of calling // something like "capabilities.setCapability(SafariOptions.CAPABILITY, new SafariOptions()); // and this is no longer needed as options are capabilities. There will be a large amount of // legacy code that will always try and follow this pattern, however. if (OPTION_KEYS.contains(key) && value instanceof Capabilities) { merge((Capabilities) value); return; } caps.put(key, value); } @Override public String toString() { return String.format("Capabilities [%s]", shortenMapValues(asMap())); } private Map<String, ?> shortenMapValues(Map<String, ?> map) { Map<String, Object> newMap = new HashMap<>(); for (Map.Entry<String, ?> entry : map.entrySet()) { if (entry.getValue() instanceof Map) { @SuppressWarnings("unchecked") Map<String, ?> value = (Map<String, ?>) entry.getValue(); newMap.put(entry.getKey(), shortenMapValues(value)); } else { String value = String.valueOf(entry.getValue()); if (value.length() > 1024) { value = value.substring(0, 29) + "..."; } newMap.put(entry.getKey(), value); } } return newMap; } }
java/client/src/org/openqa/selenium/MutableCapabilities.java
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.openqa.selenium; import java.io.Serializable; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class MutableCapabilities implements Capabilities, Serializable { private static final long serialVersionUID = -112816287184979465L; private static final Set<String> OPTION_KEYS; static { HashSet<String> keys = new HashSet<>(); keys.add("safari.options"); OPTION_KEYS = Collections.unmodifiableSet(keys); } private final Map<String, Object> caps = new HashMap<>(); public MutableCapabilities() { // no-arg constructor } public MutableCapabilities(Capabilities other) { this(other.asMap()); } public MutableCapabilities(Map<String, ?> capabilities) { capabilities.forEach((key, value) -> { if (value != null) { caps.put(key, value); } }); } @Override public Object getCapability(String capabilityName) { return caps.get(capabilityName); } @Override public Map<String, ?> asMap() { return Collections.unmodifiableMap(caps); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Capabilities)) { return false; } Capabilities that = (Capabilities) o; return caps.equals(that.asMap()); } @Override public int hashCode() { return caps.hashCode(); } /** * Merges the extra capabilities provided into this DesiredCapabilities instance. If capabilities * with the same name exist in this instance, they will be overridden by the values from the * extraCapabilities object. * * @param extraCapabilities Additional capabilities to be added. * @return DesiredCapabilities after the merge */ @Override public MutableCapabilities merge(Capabilities extraCapabilities) { if (extraCapabilities == null) { return this; } extraCapabilities.asMap().forEach(this::setCapability); return this; } public void setCapability(String capabilityName, boolean value) { setCapability(capabilityName, (Object) value); } public void setCapability(String capabilityName, String value) { setCapability(capabilityName, (Object) value); } public void setCapability(String capabilityName, Platform value) { setCapability(capabilityName, (Object) value); } public void setCapability(String key, Object value) { // We have to special-case some keys and values because of the popular idiom of calling // something like "capabilities.setCapability(SafariOptions.CAPABILITY, new SafariOptions()); // and this is no longer needed as options are capabilities. There will be a large amount of // legacy code that will always try and follow this pattern, however. if (OPTION_KEYS.contains(key) && value instanceof Capabilities) { merge((Capabilities) value); return; } caps.put(key, value); } @Override public String toString() { return String.format("Capabilities [%s]", shortenMapValues(asMap())); } private Map<String, ?> shortenMapValues(Map<String, ?> map) { Map<String, Object> newMap = new HashMap<>(); for (Map.Entry<String, ?> entry : map.entrySet()) { if (entry.getValue() instanceof Map) { @SuppressWarnings("unchecked") Map<String, ?> value = (Map<String, ?>) entry.getValue(); newMap.put(entry.getKey(), shortenMapValues(value)); } else { String value = String.valueOf(entry.getValue()); if (value.length() > 1024) { value = value.substring(0, 29) + "..."; } newMap.put(entry.getKey(), value); } } return newMap; } }
Make recursive setting of IEOptions harder
java/client/src/org/openqa/selenium/MutableCapabilities.java
Make recursive setting of IEOptions harder
Java
apache-2.0
0d817d86285655b46461b086283f655f18e822ab
0
matthyx/carnotzet,swissquote/carnotzet,matthyx/carnotzet,matthyx/carnotzet,swissquote/carnotzet,swissquote/carnotzet
package com.github.swissquote.carnotzet.core.maven; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; import org.apache.commons.io.FileUtils; import org.apache.maven.shared.invoker.DefaultInvocationRequest; import org.apache.maven.shared.invoker.DefaultInvoker; import org.apache.maven.shared.invoker.InvocationOutputHandler; import org.apache.maven.shared.invoker.InvocationRequest; import org.apache.maven.shared.invoker.InvocationResult; import org.apache.maven.shared.invoker.Invoker; import org.apache.maven.shared.invoker.MavenInvocationException; import com.github.swissquote.carnotzet.core.CarnotzetDefinitionException; import com.github.swissquote.carnotzet.core.CarnotzetModule; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @Slf4j @RequiredArgsConstructor public class MavenDependencyResolver { private final Function<CarnotzetModuleCoordinates, String> moduleNameProvider; private final Path resourcesPath; private final Invoker maven = new DefaultInvoker(); private Path localRepoPath; private final TopologicalSorter topologicalSorter = new TopologicalSorter(); public List<CarnotzetModule> resolve(CarnotzetModuleCoordinates topLevelModuleId, Boolean failOnCycle) { log.debug("Resolving module dependencies"); Path pomFile = getPomFile(topLevelModuleId); Node tree = resolveDependencyTree(pomFile); log.debug("Computing topological ordering of GAs in full dependency tree before resolution (maven2)"); List<Node> topology = topologicalSorter.sort(tree, failOnCycle); topology = filterInterestingNodes(topology); String topLevelModuleName = moduleNameProvider.apply(topLevelModuleId); List<CarnotzetModule> result = convertNodesToModules(topology, topLevelModuleName); ensureJarFilesAreDownloaded(result, topLevelModuleId); return result; } private List<Node> filterInterestingNodes(List<Node> topology) { return topology.stream() .filter(n -> n.getScope() == null || "compile".equals(n.getScope()) || "runtime".equals(n.getScope())) .collect(Collectors.toList()); } private void ensureJarFilesAreDownloaded(List<CarnotzetModule> result, CarnotzetModuleCoordinates topLevelModuleId) { for (CarnotzetModule module : result) { if (!module.getJarPath().toFile().exists()) { downloadJars(topLevelModuleId); if (!module.getJarPath().toFile().exists()) { throw new CarnotzetDefinitionException("Unable to find jar [" + module.getJarPath() + "]"); } } } } private void downloadJars(CarnotzetModuleCoordinates topLevelModuleId) { // format : groupId:artifactId:version[:packaging[:classifier]] String gav = topLevelModuleId.getGroupId() + ":" + topLevelModuleId.getArtifactId() + ":" + topLevelModuleId.getVersion() + ":jar"; if (topLevelModuleId.getClassifier() != null) { gav += ":" + topLevelModuleId.getClassifier(); } executeMavenBuild(Arrays.asList("org.apache.maven.plugins:maven-dependency-plugin:2.10:get -Dartifact=" + gav), null); } private List<CarnotzetModule> convertNodesToModules(List<Node> nodes, String topLevelModuleName) { List<CarnotzetModule> result = new ArrayList<>(); for (Node artifact : nodes) { CarnotzetModuleCoordinates coord = new CarnotzetModuleCoordinates( artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), artifact.getClassifier()); String name = moduleNameProvider.apply(coord); if (name == null) { continue; } CarnotzetModule module = CarnotzetModule.builder() .id(coord) .name(name) .topLevelModuleName(topLevelModuleName) .jarPath(getJarFile(coord)) .build(); result.add(module); } return result; } private Path getJarFile(CarnotzetModuleCoordinates artifact) { Path localRepoPath = getLocalRepoPath(); return localRepoPath .resolve(artifact.getGroupId().replace(".", "/")) .resolve(artifact.getArtifactId()) .resolve(artifact.getVersion()) .resolve(getJarName(artifact)); } private String getJarName(CarnotzetModuleCoordinates artifact) { String jarName = artifact.getArtifactId() + "-" + artifact.getVersion(); if (artifact.getClassifier() != null) { jarName += "-" + artifact.getClassifier(); } return jarName + ".jar"; } private Path getPomFile(CarnotzetModuleCoordinates artifact) { Path localRepoPath = getLocalRepoPath(); Path localFile = localRepoPath .resolve(artifact.getGroupId().replace(".", "/")) .resolve(artifact.getArtifactId()) .resolve(artifact.getVersion()) .resolve(artifact.getArtifactId() + "-" + artifact.getVersion() + ".pom"); if (!localFile.toFile().exists()) { log.debug("pom file [{}] not found. invoking maven dependency:get to download it", localFile); String gav = artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getVersion(); executeMavenBuild(Arrays.asList( "org.apache.maven.plugins:maven-dependency-plugin:2.10:get " + "-Dpackaging=pom -Dtransitive=false -Dartifact=" + gav), null); } log.debug("Using pom file [{}] as top level artifact.", localFile); return localFile; } private void executeMavenBuild(List<String> goals, InvocationOutputHandler outputHandler) { log.debug("Invoking maven with goals {}", goals); InvocationRequest request = new DefaultInvocationRequest(); request.setBatchMode(true); request.setGoals(goals); // reset MAVEN_DEBUG_OPTS to allow debugging without blocking the invoker calls request.addShellEnvironment("MAVEN_DEBUG_OPTS", ""); InvocationOutputHandler outHandler = outputHandler; if (outHandler == null) { outHandler = log::debug; } request.setOutputHandler(outHandler); try { InvocationResult result = maven.execute(request); if (result.getExitCode() != 0) { throw new MavenInvocationException("Maven process exited with non-zero code [" + result.getExitCode() + "]. " + "Retry with debug log level enabled to see the maven invocation logs"); } } catch (MavenInvocationException e) { throw new CarnotzetDefinitionException("Error invoking mvn " + goals, e); } } /** * Relies on mvn dependency:tree -Dverbose to get a full dependency tree, including omitted ones. * This uses maven 2 and may be inconsistent with maven 3 resolved dependencies. */ private Node resolveDependencyTree(Path pomFile) { Path treePath = resourcesPath.resolve("tree.txt"); String command = "org.apache.maven.plugins:maven-dependency-plugin:2.10:tree -Dverbose" + " -f " + pomFile.toAbsolutePath().toString() + " -DoutputType=text " + " -DoutputFile=" + treePath.toAbsolutePath().toString(); executeMavenBuild(Arrays.asList(command), null); try (Reader r = new InputStreamReader(Files.newInputStream(treePath), "UTF-8")) { return new TreeTextParser().parse(r); } catch (ParseException | IOException e) { throw new RuntimeException(e); } } private Path getLocalRepoPath() { if (this.localRepoPath == null || !this.localRepoPath.toFile().exists()) { readUserConfigCache(); if (this.localRepoPath == null || !this.localRepoPath.toFile().exists()) { getLocalRepoLocationFromMaven(); if (this.localRepoPath == null || !this.localRepoPath.toFile().exists()) { throw new CarnotzetDefinitionException("Could not locate maven local repository path"); } writeDotConfigCache(); } } return this.localRepoPath; } private void writeDotConfigCache() { Path userConfigFolder = getUserConfigFolder(); if (!userConfigFolder.toFile().exists()) { if (!userConfigFolder.toFile().mkdirs()) { throw new CarnotzetDefinitionException("Could not create directory [" + userConfigFolder + "]"); } } Path localRepoPathCache = userConfigFolder.resolve("m2LocalRepoPath"); try { FileUtils.writeStringToFile(localRepoPathCache.toFile(), this.localRepoPath.toString(), "UTF-8"); } catch (IOException e) { log.warn("Could not write file [{}]", localRepoPathCache); } } private void getLocalRepoLocationFromMaven() { LocalRepoLocationOutputHandler handler = new LocalRepoLocationOutputHandler(); executeMavenBuild(Arrays.asList("help:evaluate -Dexpression=settings.localRepository"), handler); this.localRepoPath = Paths.get(handler.getResult()); } private void readUserConfigCache() { Path localRepoPathCache = getUserConfigFolder().resolve("m2LocalRepoPath"); if (localRepoPathCache.toFile().exists()) { try { this.localRepoPath = Paths.get(FileUtils.readFileToString(localRepoPathCache.toFile())); } catch (IOException e) { log.warn("unable to read file [{}]", localRepoPathCache); } } } private Path getUserConfigFolder() { return Paths.get(System.getProperty("user.home")).resolve(".carnotzet"); } private static final class LocalRepoLocationOutputHandler implements InvocationOutputHandler { @Getter private String result; @Override public void consumeLine(String line) { if (!line.contains("INFO")) { result = line; } } } }
core/src/main/java/com/github/swissquote/carnotzet/core/maven/MavenDependencyResolver.java
package com.github.swissquote.carnotzet.core.maven; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; import org.apache.commons.io.FileUtils; import org.apache.maven.shared.invoker.DefaultInvocationRequest; import org.apache.maven.shared.invoker.DefaultInvoker; import org.apache.maven.shared.invoker.InvocationOutputHandler; import org.apache.maven.shared.invoker.InvocationRequest; import org.apache.maven.shared.invoker.InvocationResult; import org.apache.maven.shared.invoker.Invoker; import org.apache.maven.shared.invoker.MavenInvocationException; import com.github.swissquote.carnotzet.core.CarnotzetDefinitionException; import com.github.swissquote.carnotzet.core.CarnotzetModule; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @Slf4j @RequiredArgsConstructor public class MavenDependencyResolver { private final Function<CarnotzetModuleCoordinates, String> moduleNameProvider; private final Path resourcesPath; private final Invoker maven = new DefaultInvoker(); private Path localRepoPath; private final TopologicalSorter topologicalSorter = new TopologicalSorter(); public List<CarnotzetModule> resolve(CarnotzetModuleCoordinates topLevelModuleId, Boolean failOnCycle) { log.debug("Resolving module dependencies"); Path pomFile = getPomFile(topLevelModuleId); Node tree = resolveDependencyTree(pomFile); log.debug("Computing topological ordering of GAs in full dependency tree before resolution (maven2)"); List<Node> topology = topologicalSorter.sort(tree, failOnCycle); topology = filterInterestingNodes(topology); String topLevelModuleName = moduleNameProvider.apply(topLevelModuleId); List<CarnotzetModule> result = convertNodesToModules(topology, topLevelModuleName); ensureJarFilesAreDownloaded(result, topLevelModuleId); return result; } private List<Node> filterInterestingNodes(List<Node> topology) { return topology.stream() .filter(n -> n.getScope() == null || "compile".equals(n.getScope()) || "runtime".equals(n.getScope())) .collect(Collectors.toList()); } private void ensureJarFilesAreDownloaded(List<CarnotzetModule> result, CarnotzetModuleCoordinates topLevelModuleId) { for (CarnotzetModule module : result) { if (!module.getJarPath().toFile().exists()) { downloadJars(topLevelModuleId); if (!module.getJarPath().toFile().exists()) { throw new CarnotzetDefinitionException("Unable to find jar [" + module.getJarPath() + "]"); } } } } private void downloadJars(CarnotzetModuleCoordinates topLevelModuleId) { // GAV are specified in this order: // groupId:artifactId:packaging:classifier:version // groupId:artifactId:packaging:version String gav = topLevelModuleId.getGroupId() + ":" + topLevelModuleId.getArtifactId() + ":jar:"; if (topLevelModuleId.getClassifier() != null) { gav += topLevelModuleId.getClassifier() + ":"; } gav += topLevelModuleId.getVersion(); executeMavenBuild(Arrays.asList("org.apache.maven.plugins:maven-dependency-plugin:2.10:get -Dartifact=" + gav), null); } private List<CarnotzetModule> convertNodesToModules(List<Node> nodes, String topLevelModuleName) { List<CarnotzetModule> result = new ArrayList<>(); for (Node artifact : nodes) { CarnotzetModuleCoordinates coord = new CarnotzetModuleCoordinates( artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), artifact.getClassifier()); String name = moduleNameProvider.apply(coord); if (name == null) { continue; } CarnotzetModule module = CarnotzetModule.builder() .id(coord) .name(name) .topLevelModuleName(topLevelModuleName) .jarPath(getJarFile(coord)) .build(); result.add(module); } return result; } private Path getJarFile(CarnotzetModuleCoordinates artifact) { Path localRepoPath = getLocalRepoPath(); return localRepoPath .resolve(artifact.getGroupId().replace(".", "/")) .resolve(artifact.getArtifactId()) .resolve(artifact.getVersion()) .resolve(getJarName(artifact)); } private String getJarName(CarnotzetModuleCoordinates artifact) { String jarName = artifact.getArtifactId() + "-" + artifact.getVersion(); if (artifact.getClassifier() != null) { jarName += "-" + artifact.getClassifier(); } return jarName + ".jar"; } private Path getPomFile(CarnotzetModuleCoordinates artifact) { Path localRepoPath = getLocalRepoPath(); Path localFile = localRepoPath .resolve(artifact.getGroupId().replace(".", "/")) .resolve(artifact.getArtifactId()) .resolve(artifact.getVersion()) .resolve(artifact.getArtifactId() + "-" + artifact.getVersion() + ".pom"); if (!localFile.toFile().exists()) { log.debug("pom file [{}] not found. invoking maven dependency:get to download it", localFile); String gav = artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getVersion(); executeMavenBuild(Arrays.asList( "org.apache.maven.plugins:maven-dependency-plugin:2.10:get " + "-Dpackaging=pom -Dtransitive=false -Dartifact=" + gav), null); } log.debug("Using pom file [{}] as top level artifact.", localFile); return localFile; } private void executeMavenBuild(List<String> goals, InvocationOutputHandler outputHandler) { log.debug("Invoking maven with goals {}", goals); InvocationRequest request = new DefaultInvocationRequest(); request.setBatchMode(true); request.setGoals(goals); // reset MAVEN_DEBUG_OPTS to allow debugging without blocking the invoker calls request.addShellEnvironment("MAVEN_DEBUG_OPTS", ""); InvocationOutputHandler outHandler = outputHandler; if (outHandler == null) { outHandler = log::debug; } request.setOutputHandler(outHandler); try { InvocationResult result = maven.execute(request); if (result.getExitCode() != 0) { throw new MavenInvocationException("Maven process exited with non-zero code [" + result.getExitCode() + "]. " + "Retry with debug log level enabled to see the maven invocation logs"); } } catch (MavenInvocationException e) { throw new CarnotzetDefinitionException("Error invoking mvn " + goals, e); } } /** * Relies on mvn dependency:tree -Dverbose to get a full dependency tree, including omitted ones. * This uses maven 2 and may be inconsistent with maven 3 resolved dependencies. */ private Node resolveDependencyTree(Path pomFile) { Path treePath = resourcesPath.resolve("tree.txt"); String command = "org.apache.maven.plugins:maven-dependency-plugin:2.10:tree -Dverbose" + " -f " + pomFile.toAbsolutePath().toString() + " -DoutputType=text " + " -DoutputFile=" + treePath.toAbsolutePath().toString(); executeMavenBuild(Arrays.asList(command), null); try (Reader r = new InputStreamReader(Files.newInputStream(treePath), "UTF-8")) { return new TreeTextParser().parse(r); } catch (ParseException | IOException e) { throw new RuntimeException(e); } } private Path getLocalRepoPath() { if (this.localRepoPath == null || !this.localRepoPath.toFile().exists()) { readUserConfigCache(); if (this.localRepoPath == null || !this.localRepoPath.toFile().exists()) { getLocalRepoLocationFromMaven(); if (this.localRepoPath == null || !this.localRepoPath.toFile().exists()) { throw new CarnotzetDefinitionException("Could not locate maven local repository path"); } writeDotConfigCache(); } } return this.localRepoPath; } private void writeDotConfigCache() { Path userConfigFolder = getUserConfigFolder(); if (!userConfigFolder.toFile().exists()) { if (!userConfigFolder.toFile().mkdirs()) { throw new CarnotzetDefinitionException("Could not create directory [" + userConfigFolder + "]"); } } Path localRepoPathCache = userConfigFolder.resolve("m2LocalRepoPath"); try { FileUtils.writeStringToFile(localRepoPathCache.toFile(), this.localRepoPath.toString(), "UTF-8"); } catch (IOException e) { log.warn("Could not write file [{}]", localRepoPathCache); } } private void getLocalRepoLocationFromMaven() { LocalRepoLocationOutputHandler handler = new LocalRepoLocationOutputHandler(); executeMavenBuild(Arrays.asList("help:evaluate -Dexpression=settings.localRepository"), handler); this.localRepoPath = Paths.get(handler.getResult()); } private void readUserConfigCache() { Path localRepoPathCache = getUserConfigFolder().resolve("m2LocalRepoPath"); if (localRepoPathCache.toFile().exists()) { try { this.localRepoPath = Paths.get(FileUtils.readFileToString(localRepoPathCache.toFile())); } catch (IOException e) { log.warn("unable to read file [{}]", localRepoPathCache); } } } private Path getUserConfigFolder() { return Paths.get(System.getProperty("user.home")).resolve(".carnotzet"); } private static final class LocalRepoLocationOutputHandler implements InvocationOutputHandler { @Getter private String result; @Override public void consumeLine(String line) { if (!line.contains("INFO")) { result = line; } } } }
Fix wrong artifactId construction for internal mvn dependency:get call
core/src/main/java/com/github/swissquote/carnotzet/core/maven/MavenDependencyResolver.java
Fix wrong artifactId construction for internal mvn dependency:get call
Java
apache-2.0
741864a994699aeff81651b84f838f9fd12c504d
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.fileEditor.impl; import com.intellij.ProjectTopics; import com.intellij.featureStatistics.fusCollectors.LifecycleUsageTriggerCollector; import com.intellij.ide.IdeBundle; import com.intellij.ide.IdeEventQueue; import com.intellij.ide.actions.HideAllToolWindowsAction; import com.intellij.ide.actions.SplitAction; import com.intellij.ide.ui.UISettings; import com.intellij.ide.ui.UISettingsListener; import com.intellij.injected.editor.VirtualFileWindow; import com.intellij.notebook.editor.BackedVirtualFile; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.*; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.openapi.components.StoragePathMacros; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.ScrollType; import com.intellij.openapi.editor.event.EditorFactoryEvent; import com.intellij.openapi.editor.event.EditorFactoryListener; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.editor.ex.FocusChangeListener; import com.intellij.openapi.extensions.ExtensionPointListener; import com.intellij.openapi.extensions.PluginDescriptor; import com.intellij.openapi.fileEditor.*; import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx; import com.intellij.openapi.fileEditor.ex.FileEditorProviderManager; import com.intellij.openapi.fileEditor.ex.FileEditorWithProvider; import com.intellij.openapi.fileEditor.ex.IdeDocumentHistory; import com.intellij.openapi.fileEditor.impl.text.TextEditorImpl; import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider; import com.intellij.openapi.fileTypes.FileTypeEvent; import com.intellij.openapi.fileTypes.FileTypeListener; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.keymap.Keymap; import com.intellij.openapi.keymap.KeymapManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.project.*; import com.intellij.openapi.project.impl.ProjectImpl; import com.intellij.openapi.roots.ModuleRootEvent; import com.intellij.openapi.roots.ModuleRootListener; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.ui.Splitter; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.vcs.FileStatus; import com.intellij.openapi.vcs.FileStatusListener; import com.intellij.openapi.vcs.FileStatusManager; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.newvfs.BulkFileListener; import com.intellij.openapi.vfs.newvfs.events.VFileDeleteEvent; import com.intellij.openapi.vfs.newvfs.events.VFileEvent; import com.intellij.openapi.vfs.newvfs.events.VFileMoveEvent; import com.intellij.openapi.vfs.newvfs.events.VFilePropertyChangeEvent; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.pom.Navigatable; import com.intellij.reference.SoftReference; import com.intellij.ui.ComponentUtil; import com.intellij.ui.docking.DockContainer; import com.intellij.ui.docking.DockManager; import com.intellij.ui.docking.impl.DockManagerImpl; import com.intellij.ui.tabs.impl.JBTabsImpl; import com.intellij.ui.tabs.impl.tabsLayout.TabsLayoutInfo; import com.intellij.ui.tabs.impl.tabsLayout.TabsLayoutSettingsManager; import com.intellij.util.*; import com.intellij.util.concurrency.AppExecutorUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.SmartHashSet; import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.messages.impl.MessageListenerList; import com.intellij.util.ui.EdtInvocationManager; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.update.MergingUpdateQueue; import com.intellij.util.ui.update.Update; import one.util.streamex.StreamEx; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.concurrency.AsyncPromise; import org.jetbrains.concurrency.Promise; import javax.swing.*; import java.awt.*; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.util.List; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicInteger; import static com.intellij.openapi.actionSystem.IdeActions.ACTION_OPEN_IN_NEW_WINDOW; import static com.intellij.openapi.actionSystem.IdeActions.ACTION_OPEN_IN_RIGHT_SPLIT; /** * @author Anton Katilin * @author Eugene Belyaev * @author Vladimir Kondratyev */ @State(name = "FileEditorManager", storages = { @Storage(StoragePathMacros.PRODUCT_WORKSPACE_FILE), @Storage(value = StoragePathMacros.WORKSPACE_FILE, deprecated = true) }) public class FileEditorManagerImpl extends FileEditorManagerEx implements PersistentStateComponent<Element>, Disposable { private static final Logger LOG = Logger.getInstance(FileEditorManagerImpl.class); protected static final Key<Boolean> DUMB_AWARE = Key.create("DUMB_AWARE"); public static final Key<Boolean> NOTHING_WAS_OPENED_ON_START = Key.create("NOTHING_WAS_OPENED_ON_START"); private static final FileEditorProvider[] EMPTY_PROVIDER_ARRAY = {}; public static final Key<Boolean> CLOSING_TO_REOPEN = Key.create("CLOSING_TO_REOPEN"); public static final Key<Boolean> OPEN_IN_PREVIEW_TAB = Key.create("OPEN_IN_PREVIEW_TAB"); public static final String FILE_EDITOR_MANAGER = "FileEditorManager"; public enum OpenMode { NEW_WINDOW, RIGHT_SPLIT, DEFAULT } private EditorsSplitters mySplitters; private final Project myProject; private final List<Pair<VirtualFile, EditorWindow>> mySelectionHistory = new ArrayList<>(); private Reference<EditorComposite> myLastSelectedComposite = new WeakReference<>(null); private final MergingUpdateQueue myQueue = new MergingUpdateQueue("FileEditorManagerUpdateQueue", 50, true, MergingUpdateQueue.ANY_COMPONENT, this); private final BusyObject.Impl.Simple myBusyObject = new BusyObject.Impl.Simple(); /** * Removes invalid myEditor and updates "modified" status. */ private final PropertyChangeListener myEditorPropertyChangeListener = new MyEditorPropertyChangeListener(); private final DockManager myDockManager; private DockableEditorContainerFactory myContentFactory; private static final AtomicInteger ourOpenFilesSetModificationCount = new AtomicInteger(); static final ModificationTracker OPEN_FILE_SET_MODIFICATION_COUNT = ourOpenFilesSetModificationCount::get; private final List<EditorComposite> myOpenedEditors = new CopyOnWriteArrayList<>(); private final MessageListenerList<FileEditorManagerListener> myListenerList; public FileEditorManagerImpl(@NotNull Project project) { myProject = project; myDockManager = DockManager.getInstance(myProject); myListenerList = new MessageListenerList<>(myProject.getMessageBus(), FileEditorManagerListener.FILE_EDITOR_MANAGER); if (FileEditorAssociateFinder.EP_NAME.hasAnyExtensions()) { myListenerList.add(new FileEditorManagerListener() { @Override public void selectionChanged(@NotNull FileEditorManagerEvent event) { EditorsSplitters splitters = getSplitters(); openAssociatedFile(event.getNewFile(), splitters.getCurrentWindow(), splitters); } }); } myQueue.setTrackUiActivity(true); MessageBusConnection connection = project.getMessageBus().connect(this); connection.subscribe(DumbService.DUMB_MODE, new DumbService.DumbModeListener() { @Override public void exitDumbMode() { // can happen under write action, so postpone to avoid deadlock on FileEditorProviderManager.getProviders() ApplicationManager.getApplication().invokeLater(() -> dumbModeFinished(myProject), myProject.getDisposed()); } }); connection.subscribe(ProjectManager.TOPIC, new ProjectManagerListener() { @Override public void projectOpened(@NotNull Project project) { if (project == myProject) { FileEditorManagerImpl.this.projectOpened(connection); } } @Override public void projectClosing(@NotNull Project project) { if (project == myProject) { // Dispose created editors. We do not use use closeEditor method because // it fires event and changes history. closeAllFiles(); } } }); closeFilesOnFileEditorRemoval(); EditorFactory editorFactory = EditorFactory.getInstance(); for (Editor editor : editorFactory.getAllEditors()) { registerEditor(editor); } editorFactory.addEditorFactoryListener(new EditorFactoryListener() { @Override public void editorCreated(@NotNull EditorFactoryEvent event) { registerEditor(event.getEditor()); } }, myProject); } private void registerEditor(Editor editor) { Project project = editor.getProject(); if (project == null || project.isDisposed()) { return; } if (editor instanceof EditorEx) { ((EditorEx)editor).addFocusListener(new FocusChangeListener() { @Override public void focusGained(@NotNull Editor editor1) { if (!Registry.is("editor.maximize.on.focus.gained.if.collapsed.in.split")) return; Component comp = editor1.getComponent(); while (comp != getMainSplitters() && comp != null) { Component parent = comp.getParent(); if (parent instanceof Splitter) { Splitter splitter = (Splitter)parent; if ((splitter.getFirstComponent() == comp && (splitter.getProportion() == splitter.getMinProportion(true) || splitter.getProportion() == splitter.getMinimumProportion())) || (splitter.getProportion() == splitter.getMinProportion(false) || splitter.getProportion() == splitter.getMaximumProportion())) { Set<kotlin.Pair<Splitter, Boolean>> pairs = HideAllToolWindowsAction.Companion.getSplittersToMaximize(project, editor1); for (kotlin.Pair<Splitter, Boolean> pair : pairs) { Splitter s = pair.getFirst(); s.setProportion(pair.getSecond() ? s.getMaximumProportion() : s.getMinimumProportion()); } break; } } comp = parent; } } }); } } private void closeFilesOnFileEditorRemoval() { FileEditorProvider.EP_FILE_EDITOR_PROVIDER.addExtensionPointListener(new ExtensionPointListener<>() { @Override public void extensionRemoved(@NotNull FileEditorProvider extension, @NotNull PluginDescriptor pluginDescriptor) { for (EditorComposite editor : myOpenedEditors) { for (FileEditorProvider provider : editor.getProviders()) { if (provider.equals(extension)) { closeFile(editor.getFile()); break; } } } } }, this); } @Override public void dispose() { } private void dumbModeFinished(Project project) { VirtualFile[] files = getOpenFiles(); for (VirtualFile file : files) { Set<FileEditorProvider> providers = new HashSet<>(); List<EditorWithProviderComposite> composites = getEditorComposites(file); for (EditorWithProviderComposite composite : composites) { ContainerUtil.addAll(providers, composite.getProviders()); } FileEditorProvider[] newProviders = FileEditorProviderManager.getInstance().getProviders(project, file); List<FileEditorProvider> toOpen = new ArrayList<>(Arrays.asList(newProviders)); toOpen.removeAll(providers); // need to open additional non dumb-aware editors for (EditorWithProviderComposite composite : composites) { for (FileEditorProvider provider : toOpen) { FileEditor editor = provider.createEditor(myProject, file); composite.addEditor(editor, provider); } } updateFileBackgroundColor(file); } // update for non-dumb-aware EditorTabTitleProviders updateFileName(null); } public void initDockableContentFactory() { if (myContentFactory != null) { return; } myContentFactory = new DockableEditorContainerFactory(myProject, this); myDockManager.register(DockableEditorContainerFactory.TYPE, myContentFactory, this); } public static boolean isDumbAware(@NotNull FileEditor editor) { return Boolean.TRUE.equals(editor.getUserData(DUMB_AWARE)) && (!(editor instanceof PossiblyDumbAware) || ((PossiblyDumbAware)editor).isDumbAware()); } //------------------------------------------------------------------------------- @Override public JComponent getComponent() { return initUI(); } public @NotNull EditorsSplitters getMainSplitters() { return initUI(); } public @NotNull Set<EditorsSplitters> getAllSplitters() { Set<EditorsSplitters> all = new LinkedHashSet<>(); all.add(getMainSplitters()); Set<DockContainer> dockContainers = myDockManager.getContainers(); for (DockContainer each : dockContainers) { if (each instanceof DockableEditorTabbedContainer) { all.add(((DockableEditorTabbedContainer)each).getSplitters()); } } return Collections.unmodifiableSet(all); } private @NotNull Promise<EditorsSplitters> getActiveSplittersAsync() { AsyncPromise<EditorsSplitters> result = new AsyncPromise<>(); IdeFocusManager fm = IdeFocusManager.getInstance(myProject); TransactionGuard.getInstance().assertWriteSafeContext(ModalityState.defaultModalityState()); fm.doWhenFocusSettlesDown(() -> { if (myProject.isDisposed()) { result.cancel(); return; } Component focusOwner = fm.getFocusOwner(); DockContainer container = myDockManager.getContainerFor(focusOwner); if (container instanceof DockableEditorTabbedContainer) { result.setResult(((DockableEditorTabbedContainer)container).getSplitters()); } else { result.setResult(getMainSplitters()); } }, ModalityState.defaultModalityState()); return result; } private EditorsSplitters getActiveSplittersSync() { assertDispatchThread(); if (Registry.is("ide.navigate.to.recently.focused.editor", false)) { ArrayList<EditorsSplitters> splitters = new ArrayList<>(getAllSplitters()); if (!splitters.isEmpty()) { splitters.sort((o1, o2) -> Long.compare(o2.getLastFocusGainedTime(), o1.getLastFocusGainedTime())); return splitters.get(0); } } IdeFocusManager fm = IdeFocusManager.getInstance(myProject); Component focusOwner = fm.getFocusOwner(); if (focusOwner == null) { focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); } if (focusOwner == null) { focusOwner = fm.getLastFocusedFor(fm.getLastFocusedIdeWindow()); } DockContainer container = myDockManager.getContainerFor(focusOwner); if (container == null) { focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow(); container = myDockManager.getContainerFor(focusOwner); } if (container instanceof DockableEditorTabbedContainer) { return ((DockableEditorTabbedContainer)container).getSplitters(); } return getMainSplitters(); } private final Object myInitLock = new Object(); private @NotNull EditorsSplitters initUI() { EditorsSplitters result = mySplitters; if (result != null) { return result; } synchronized (myInitLock) { result = mySplitters; if (result == null) { result = new EditorsSplitters(this, true, this); mySplitters = result; } } return result; } @Override public JComponent getPreferredFocusedComponent() { assertReadAccess(); EditorWindow window = getSplitters().getCurrentWindow(); if (window != null) { EditorWithProviderComposite editor = window.getSelectedEditor(); if (editor != null) { return editor.getPreferredFocusedComponent(); } } return null; } //------------------------------------------------------- /** * @return color of the {@code file} which corresponds to the * file's status */ @NotNull Color getFileColor(@NotNull VirtualFile file) { FileStatusManager fileStatusManager = FileStatusManager.getInstance(myProject); Color statusColor = fileStatusManager != null ? fileStatusManager.getStatus(file).getColor() : UIUtil.getLabelForeground(); if (statusColor == null) statusColor = UIUtil.getLabelForeground(); return statusColor; } public boolean isProblem(@NotNull VirtualFile file) { return false; } public @NotNull @NlsContexts.Tooltip String getFileTooltipText(@NotNull VirtualFile file) { List<EditorTabTitleProvider> availableProviders = DumbService.getDumbAwareExtensions(myProject, EditorTabTitleProvider.EP_NAME); for (EditorTabTitleProvider provider : availableProviders) { String text = provider.getEditorTabTooltipText(myProject, file); if (text != null) { return text; } } return FileUtil.getLocationRelativeToUserHome(file.getPresentableUrl()); } @Override public void updateFilePresentation(@NotNull VirtualFile file) { if (!isFileOpen(file)) return; updateFileName(file); queueUpdateFile(file); } /** * Updates tab color for the specified {@code file}. The {@code file} * should be opened in the myEditor, otherwise the method throws an assertion. */ private void updateFileColor(@NotNull VirtualFile file) { Set<EditorsSplitters> all = getAllSplitters(); for (EditorsSplitters each : all) { each.updateFileColor(file); } } private void updateFileBackgroundColor(@NotNull VirtualFile file) { Set<EditorsSplitters> all = getAllSplitters(); for (EditorsSplitters each : all) { each.updateFileBackgroundColor(file); } } /** * Updates tab icon for the specified {@code file}. The {@code file} * should be opened in the myEditor, otherwise the method throws an assertion. */ protected void updateFileIcon(@NotNull VirtualFile file) { updateFileIcon(file, false); } /** * Reset the preview tab flag if an internal document change is made. */ private void resetPreviewFlag(@NotNull VirtualFile file) { if (!FileDocumentManager.getInstance().isFileModified(file)) { return; } for (EditorsSplitters splitter : getAllSplitters()) { splitter.findEditorComposites(file).stream() .filter(EditorComposite::isPreview) .forEach(c -> c.setPreview(false)); splitter.updateFileColor(file); } } /** * Updates tab icon for the specified {@code file}. The {@code file} * should be opened in the myEditor, otherwise the method throws an assertion. */ protected void updateFileIcon(@NotNull VirtualFile file, boolean immediately) { Set<EditorsSplitters> all = getAllSplitters(); for (EditorsSplitters each : all) { if (immediately) { each.updateFileIconImmediately(file, IconUtil.computeFileIcon(file, Iconable.ICON_FLAG_READ_STATUS, myProject)); } else { each.updateFileIcon(file); } } } /** * Updates tab title and tab tool tip for the specified {@code file} */ void updateFileName(@Nullable VirtualFile file) { // Queue here is to prevent title flickering when tab is being closed and two events arriving: with component==null and component==next focused tab // only the last event makes sense to handle myQueue.queue(new Update("UpdateFileName " + (file == null ? "" : file.getPath())) { @Override public boolean isExpired() { return myProject.isDisposed() || !myProject.isOpen() || (file == null ? super.isExpired() : !file.isValid()); } @Override public void run() { SlowOperations.allowSlowOperations(() -> { for (EditorsSplitters each : getAllSplitters()) { each.updateFileName(file); } }); } }); } private void updateFrameTitle() { getActiveSplittersAsync().onSuccess(splitters -> splitters.updateFileName(null)); } @Override public VirtualFile getFile(@NotNull FileEditor editor) { EditorComposite editorComposite = getEditorComposite(editor); VirtualFile tabFile = editorComposite == null ? null : editorComposite.getFile(); VirtualFile editorFile = editor.getFile(); if (!Objects.equals(editorFile, tabFile)) { if (editorFile == null) { LOG.warn(editor.getClass().getName() + ".getFile() shall not return null"); } else if (tabFile == null) { //todo DaemonCodeAnalyzerImpl#getSelectedEditors calls it for any Editor //LOG.warn(editor.getClass().getName() + ".getFile() shall be used, fileEditor is not opened in a tab."); } else { LOG.warn("fileEditor.getFile=" + editorFile + " != fileEditorManager.getFile=" + tabFile + ", fileEditor.class=" + editor.getClass().getName()); } } return tabFile; } @Override public void unsplitWindow() { EditorWindow currentWindow = getActiveSplittersSync().getCurrentWindow(); if (currentWindow != null) { currentWindow.unsplit(true); } } @Override public void unsplitAllWindow() { EditorWindow currentWindow = getActiveSplittersSync().getCurrentWindow(); if (currentWindow != null) { currentWindow.unsplitAll(); } } @Override public int getWindowSplitCount() { return getActiveSplittersSync().getSplitCount(); } @Override public boolean hasSplitOrUndockedWindows() { Set<EditorsSplitters> splitters = getAllSplitters(); if (splitters.size() > 1) return true; return getWindowSplitCount() > 1; } @Override public EditorWindow @NotNull [] getWindows() { List<EditorWindow> windows = new ArrayList<>(); Set<EditorsSplitters> all = getAllSplitters(); for (EditorsSplitters each : all) { EditorWindow[] eachList = each.getWindows(); ContainerUtil.addAll(windows, eachList); } return windows.toArray(new EditorWindow[0]); } @Override public EditorWindow getNextWindow(@NotNull EditorWindow window) { List<EditorWindow> windows = getSplitters().getOrderedWindows(); for (int i = 0; i != windows.size(); ++i) { if (windows.get(i).equals(window)) { return windows.get((i + 1) % windows.size()); } } LOG.error("Not window found"); return null; } @Override public EditorWindow getPrevWindow(@NotNull EditorWindow window) { List<EditorWindow> windows = getSplitters().getOrderedWindows(); for (int i = 0; i != windows.size(); ++i) { if (windows.get(i).equals(window)) { return windows.get((i + windows.size() - 1) % windows.size()); } } LOG.error("Not window found"); return null; } @Override public void createSplitter(int orientation, @Nullable EditorWindow window) { // window was available from action event, for example when invoked from the tab menu of an editor that is not the 'current' if (window != null) { window.split(orientation, true, null, false); } // otherwise we'll split the current window, if any else { EditorWindow currentWindow = getSplitters().getCurrentWindow(); if (currentWindow != null) { currentWindow.split(orientation, true, null, false); } } } @Override public void changeSplitterOrientation() { EditorWindow currentWindow = getSplitters().getCurrentWindow(); if (currentWindow != null) { currentWindow.changeOrientation(); } } @Override public boolean isInSplitter() { EditorWindow currentWindow = getSplitters().getCurrentWindow(); return currentWindow != null && currentWindow.inSplitter(); } @Override public boolean hasOpenedFile() { EditorWindow currentWindow = getSplitters().getCurrentWindow(); return currentWindow != null && currentWindow.getSelectedEditor() != null; } @Override public VirtualFile getCurrentFile() { return getActiveSplittersSync().getCurrentFile(); } @Override public @NotNull Promise<EditorWindow> getActiveWindow() { return getActiveSplittersAsync() .then(EditorsSplitters::getCurrentWindow); } @Override public EditorWindow getCurrentWindow() { if (!ApplicationManager.getApplication().isDispatchThread()) return null; EditorsSplitters splitters = getActiveSplittersSync(); return splitters == null ? null : splitters.getCurrentWindow(); } @Override public void setCurrentWindow(EditorWindow window) { getActiveSplittersSync().setCurrentWindow(window, true); } public void closeFile(@NotNull VirtualFile file, @NotNull EditorWindow window, boolean transferFocus) { assertDispatchThread(); ourOpenFilesSetModificationCount.incrementAndGet(); CommandProcessor.getInstance().executeCommand(myProject, () -> { if (window.isFileOpen(file)) { window.closeFile(file, true, transferFocus); } }, IdeBundle.message("command.close.active.editor"), null); removeSelectionRecord(file, window); } @Override public void closeFile(@NotNull VirtualFile file, @NotNull EditorWindow window) { closeFile(file, window, true); } //============================= EditorManager methods ================================ @Override public void closeFile(@NotNull VirtualFile file) { closeFile(file, true, false); } public void closeFile(@NotNull VirtualFile file, boolean moveFocus, boolean closeAllCopies) { assertDispatchThread(); CommandProcessor.getInstance().executeCommand(myProject, () -> { ourOpenFilesSetModificationCount.incrementAndGet(); runChange(splitters -> splitters.closeFile(file, moveFocus), closeAllCopies ? null : getActiveSplittersSync()); }, "", null); } //-------------------------------------- Open File ---------------------------------------- @Override public @NotNull Pair<FileEditor[], FileEditorProvider[]> openFileWithProviders(@NotNull VirtualFile file, boolean focusEditor, boolean searchForSplitter) { if (!file.isValid()) { throw new IllegalArgumentException("file is not valid: " + file); } assertDispatchThread(); OpenMode mode = getOpenMode(IdeEventQueue.getInstance().getTrueCurrentEvent()); if (mode == OpenMode.NEW_WINDOW) { return openFileInNewWindow(file); } if (mode == OpenMode.RIGHT_SPLIT) { Pair<FileEditor[], FileEditorProvider[]> pair = openInRightSplit(file); if (pair != null) return pair; } EditorWindow wndToOpenIn = null; if (searchForSplitter) { boolean selectionRequired = UISettings.getInstance().getEditorTabPlacement() == UISettings.TABS_NONE; Set<EditorsSplitters> all = getAllSplitters(); EditorsSplitters active = getActiveSplittersSync(); EditorWindow activeCurrentWindow = active.getCurrentWindow(); if (activeCurrentWindow != null && activeCurrentWindow.isFileOpen(file) && (!selectionRequired || file.equals(activeCurrentWindow.getSelectedFile()))) { wndToOpenIn = activeCurrentWindow; } else { for (EditorsSplitters splitters : all) { EditorWindow[] windows = splitters.getWindows(); for (EditorWindow window : windows) { if (window.isFileOpen(file) && (!selectionRequired || file.equals(window.getSelectedFile()))) { wndToOpenIn = window; break; } } } } } FileEditor selectedEditor = getSelectedEditor(); EditorsSplitters splitters; if (FileEditorManager.USE_MAIN_WINDOW.isIn(selectedEditor)) { boolean useCurrentWindow = selectedEditor != null && !FileEditorManager.USE_MAIN_WINDOW.get(selectedEditor, false); splitters = useCurrentWindow ? getSplitters() : getMainSplitters(); } else { splitters = UISettings.getInstance().getOpenTabsInMainWindow() ? getMainSplitters() : getSplitters(); } if (wndToOpenIn == null) { EditorWindow currentWindow = splitters.getCurrentWindow(); wndToOpenIn = currentWindow != null && UISettings.getInstance().getEditorTabPlacement() == UISettings.TABS_NONE ? currentWindow : splitters.getOrCreateCurrentWindow(file); } openAssociatedFile(file, wndToOpenIn, splitters); return openFileImpl2(wndToOpenIn, file, focusEditor); } public Pair<FileEditor[], FileEditorProvider[]> openFileInNewWindow(@NotNull VirtualFile file) { if (forbidSplitFor(file)) { closeFile(file); } return ((DockManagerImpl)DockManager.getInstance(getProject())).createNewDockContainerFor(file, this); } @Nullable private Pair<FileEditor[], FileEditorProvider[]> openInRightSplit(@NotNull VirtualFile file) { EditorsSplitters active = getSplitters(); EditorWindow window = active.getCurrentWindow(); if (window != null) { if (window.inSplitter() && file.equals(window.getSelectedFile()) && file.equals(ArrayUtil.getLastElement(window.getFiles()))) { //already in right splitter return null; } EditorWindow split = active.openInRightSplit(file); if (split != null) { Ref<Pair<FileEditor[], FileEditorProvider[]>> ref = Ref.create(); CommandProcessor.getInstance().executeCommand(myProject, () -> { EditorWithProviderComposite[] editorsWithProvider = split.getEditors(); FileEditor[] editors = Arrays.stream(editorsWithProvider) .map(el -> el.getEditors()) .flatMap(el -> Arrays.stream(el)) .toArray(FileEditor[]::new); FileEditorProvider[] providers = Arrays.stream(editorsWithProvider) .map(el -> el.getProviders()) .flatMap(el -> Arrays.stream(el)) .toArray(FileEditorProvider[]::new); ref.set(Pair.create(editors, providers)); }, "", null); return ref.get(); } } return null; } @NotNull public static OpenMode getOpenMode(@NotNull AWTEvent event) { if (event instanceof MouseEvent) { boolean isMouseClick = event.getID() == MouseEvent.MOUSE_CLICKED || event.getID() == MouseEvent.MOUSE_PRESSED || event.getID() == MouseEvent.MOUSE_RELEASED; int modifiers = ((MouseEvent)event).getModifiersEx(); if (modifiers == InputEvent.SHIFT_DOWN_MASK && isMouseClick) { return OpenMode.NEW_WINDOW; } } if (event instanceof KeyEvent) { KeyEvent ke = (KeyEvent)event; KeymapManager keymapManager = KeymapManager.getInstance(); if (keymapManager != null) { Keymap keymap = keymapManager.getActiveKeymap(); String[] ids = keymap.getActionIds(KeyStroke.getKeyStroke(ke.getKeyCode(), ke.getModifiers())); List<String> strings = Arrays.asList(ids); if (strings.contains(ACTION_OPEN_IN_NEW_WINDOW)) return OpenMode.NEW_WINDOW; if (strings.contains(ACTION_OPEN_IN_RIGHT_SPLIT)) return OpenMode.RIGHT_SPLIT; } } return OpenMode.DEFAULT; } private void openAssociatedFile(VirtualFile file, EditorWindow wndToOpenIn, @NotNull EditorsSplitters splitters) { EditorWindow[] windows = splitters.getWindows(); if (file != null && windows.length == 2) { for (FileEditorAssociateFinder finder : FileEditorAssociateFinder.EP_NAME.getExtensionList()) { VirtualFile associatedFile = finder.getAssociatedFileToOpen(myProject, file); if (associatedFile != null) { EditorWindow currentWindow = splitters.getCurrentWindow(); int idx = windows[0] == wndToOpenIn ? 1 : 0; openFileImpl2(windows[idx], associatedFile, false); if (currentWindow != null) { splitters.setCurrentWindow(currentWindow, false); } break; } } } } public static boolean forbidSplitFor(@NotNull VirtualFile file) { return Boolean.TRUE.equals(file.getUserData(SplitAction.FORBID_TAB_SPLIT)); } @Override public @NotNull Pair<FileEditor[], FileEditorProvider[]> openFileWithProviders(@NotNull VirtualFile file, boolean focusEditor, @NotNull EditorWindow window) { if (!file.isValid()) { throw new IllegalArgumentException("file is not valid: " + file); } assertDispatchThread(); return openFileImpl2(window, file, focusEditor); } public @NotNull Pair<FileEditor[], FileEditorProvider[]> openFileImpl2(@NotNull EditorWindow window, @NotNull VirtualFile file, boolean focusEditor) { Ref<Pair<FileEditor[], FileEditorProvider[]>> result = new Ref<>(); CommandProcessor.getInstance().executeCommand(myProject, () -> result.set(openFileImpl3(window, file, focusEditor, null)), "", null); return result.get(); } /** * @param file to be opened. Unlike openFile method, file can be * invalid. For example, all file were invalidate and they are being * removed one by one. If we have removed one invalid file, then another * invalid file become selected. That's why we do not require that * passed file is valid. * @param entry map between FileEditorProvider and FileEditorState. If this parameter */ @NotNull Pair<FileEditor[], FileEditorProvider[]> openFileImpl3(@NotNull EditorWindow window, @NotNull VirtualFile file, boolean focusEditor, @Nullable HistoryEntry entry) { if (file instanceof BackedVirtualFile) { file = ((BackedVirtualFile)file).getOriginFile(); } return openFileImpl4(window, file, entry, new FileEditorOpenOptions().withCurrentTab(true).withFocusEditor(focusEditor)); } /** * This method can be invoked from background thread. Of course, UI for returned editors should be accessed from EDT in any case. */ protected @NotNull Pair<FileEditor @NotNull [], FileEditorProvider @NotNull []> openFileImpl4(@NotNull EditorWindow window, @NotNull VirtualFile file, @Nullable HistoryEntry entry, @NotNull FileEditorOpenOptions options) { assert ApplicationManager.getApplication().isDispatchThread() || !ApplicationManager.getApplication().isReadAccessAllowed() : "must not open files under read action since we are doing a lot of invokeAndWaits here"; Ref<EditorWithProviderComposite> compositeRef = new Ref<>(); if (!options.isReopeningEditorsOnStartup()) { EdtInvocationManager.invokeAndWaitIfNeeded(() -> compositeRef.set(window.findFileComposite(file))); } FileEditorProvider[] newProviders; AsyncFileEditorProvider.Builder[] builders; if (compositeRef.isNull()) { // File is not opened yet. In this case we have to create editors // and select the created EditorComposite. newProviders = FileEditorProviderManager.getInstance().getProviders(myProject, file); if (newProviders.length == 0) { return Pair.createNonNull(FileEditor.EMPTY_ARRAY, EMPTY_PROVIDER_ARRAY); } builders = new AsyncFileEditorProvider.Builder[newProviders.length]; for (int i = 0; i < newProviders.length; i++) { try { FileEditorProvider provider = newProviders[i]; LOG.assertTrue(provider != null, "Provider for file "+file+" is null. All providers: "+Arrays.asList(newProviders)); builders[i] = ReadAction.compute(() -> { if (myProject.isDisposed() || !file.isValid()) { return null; } LOG.assertTrue(provider.accept(myProject, file), "Provider " + provider + " doesn't accept file " + file); return provider instanceof AsyncFileEditorProvider ? ((AsyncFileEditorProvider)provider).createEditorAsync(myProject, file) : null; }); } catch (ProcessCanceledException e) { throw e; } catch (Exception | AssertionError e) { LOG.error(e); } } } else { newProviders = null; builders = null; } ApplicationManager.getApplication().invokeAndWait(() -> runBulkTabChange(window.getOwner(), splitters -> openFileImpl4Edt(window, file, entry, options, compositeRef, newProviders, builders))); EditorWithProviderComposite composite = compositeRef.get(); return new Pair<>(composite == null ? FileEditor.EMPTY_ARRAY : composite.getEditors(), composite == null ? EMPTY_PROVIDER_ARRAY : composite.getProviders()); } private void openFileImpl4Edt(@NotNull EditorWindow window, @NotNull VirtualFile file, @Nullable HistoryEntry entry, @NotNull FileEditorOpenOptions options, @NotNull Ref<EditorWithProviderComposite> compositeRef, FileEditorProvider [] newProviders, AsyncFileEditorProvider.Builder [] builders) { if (myProject.isDisposed() || !file.isValid()) { return; } ((TransactionGuardImpl)TransactionGuard.getInstance()).assertWriteActionAllowed(); compositeRef.set(window.findFileComposite(file)); boolean newEditor = compositeRef.isNull(); if (newEditor) { getProject().getMessageBus().syncPublisher(FileEditorManagerListener.Before.FILE_EDITOR_MANAGER).beforeFileOpened(this, file); FileEditor[] newEditors = new FileEditor[newProviders.length]; for (int i = 0; i < newProviders.length; i++) { try { FileEditorProvider provider = newProviders[i]; FileEditor editor = builders[i] == null ? provider.createEditor(myProject, file) : builders[i].build(); LOG.assertTrue(editor.isValid(), "Invalid editor created by provider " + (provider == null ? null : provider.getClass().getName())); newEditors[i] = editor; // Register PropertyChangeListener into editor editor.addPropertyChangeListener(myEditorPropertyChangeListener); editor.putUserData(DUMB_AWARE, DumbService.isDumbAware(provider)); } catch (ProcessCanceledException e) { throw e; } catch (Exception | AssertionError e) { LOG.error(e); } } // Now we have to create EditorComposite and insert it into the TabbedEditorComponent. // After that we have to select opened editor. EditorWithProviderComposite composite = createComposite(file, newEditors, newProviders); if (composite == null) return; if (options.getIndex() >= 0) { composite.getFile().putUserData(EditorWindow.INITIAL_INDEX_KEY, options.getIndex()); } compositeRef.set(composite); myOpenedEditors.add(composite); } EditorWithProviderComposite composite = compositeRef.get(); FileEditor[] editors = composite.getEditors(); FileEditorProvider[] providers = composite.getProviders(); window.setEditor(composite, options.isCurrentTab(), options.isFocusEditor()); for (int i = 0; i < editors.length; i++) { restoreEditorState(file, providers[i], editors[i], entry, newEditor, options.isExactState()); } // Restore selected editor FileEditorProvider selectedProvider; if (entry == null) { selectedProvider = ((FileEditorProviderManagerImpl)FileEditorProviderManager.getInstance()) .getSelectedFileEditorProvider(EditorHistoryManager.getInstance(myProject), file, providers); } else { selectedProvider = entry.getSelectedProvider(); } if (selectedProvider != null) { for (int i = editors.length - 1; i >= 0; i--) { FileEditorProvider provider = providers[i]; if (provider.equals(selectedProvider)) { composite.setSelectedEditor(i); break; } } } // Notify editors about selection changes window.getOwner().setCurrentWindow(window, options.isFocusEditor()); window.getOwner().afterFileOpen(file); addSelectionRecord(file, window); composite.getSelectedEditor().selectNotify(); // transfer focus into editor if (!ApplicationManager.getApplication().isUnitTestMode() && options.isFocusEditor()) { //myFirstIsActive = myTabbedContainer1.equals(tabbedContainer); window.setAsCurrentWindow(true); Window windowAncestor = SwingUtilities.getWindowAncestor(window.myPanel); if (windowAncestor != null && windowAncestor.equals(KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow())) { JComponent component = composite.getPreferredFocusedComponent(); if (component != null) { component.requestFocus(); } IdeFocusManager.getInstance(myProject).toFront(window.getOwner()); } } if (newEditor) { ourOpenFilesSetModificationCount.incrementAndGet(); } //[jeka] this is a hack to support back-forward navigation // previously here was incorrect call to fireSelectionChanged() with a side-effect ((IdeDocumentHistoryImpl)IdeDocumentHistory.getInstance(myProject)).onSelectionChanged(); // Update frame and tab title updateFileName(file); // Make back/forward work IdeDocumentHistory.getInstance(myProject).includeCurrentCommandAsNavigation(); if (options.getPin() != null) { window.setFilePinned(file, options.getPin()); } if (newEditor) { getProject().getMessageBus().syncPublisher(FileEditorManagerListener.FILE_EDITOR_MANAGER) .fileOpenedSync(this, file, Pair.pair(editors, providers)); notifyPublisher(() -> { if (isFileOpen(file)) { getProject().getMessageBus().syncPublisher(FileEditorManagerListener.FILE_EDITOR_MANAGER) .fileOpened(this, file); } }); } } protected final @Nullable EditorWithProviderComposite createComposite(@NotNull VirtualFile file, FileEditor @NotNull [] editors, FileEditorProvider @NotNull [] providers) { if (ArrayUtil.contains(null, editors) || ArrayUtil.contains(null, providers)) { List<FileEditor> editorList = new ArrayList<>(editors.length); List<FileEditorProvider> providerList = new ArrayList<>(providers.length); for (int i = 0; i < editors.length; i++) { FileEditor editor = editors[i]; FileEditorProvider provider = providers[i]; if (editor != null && provider != null) { editorList.add(editor); providerList.add(provider); } } if (editorList.isEmpty()) return null; editors = editorList.toArray(FileEditor.EMPTY_ARRAY); providers = providerList.toArray(new FileEditorProvider[0]); } return new EditorWithProviderComposite(file, editors, providers, this); } private void restoreEditorState(@NotNull VirtualFile file, @NotNull FileEditorProvider provider, @NotNull FileEditor editor, HistoryEntry entry, boolean newEditor, boolean exactState) { FileEditorState state = null; if (entry != null) { state = entry.getState(provider); } if (state == null && newEditor) { // We have to try to get state from the history only in case // if editor is not opened. Otherwise history entry might have a state // out of sync with the current editor state. state = EditorHistoryManager.getInstance(myProject).getState(file, provider); } if (state != null) { if (!isDumbAware(editor)) { FileEditorState finalState = state; DumbService.getInstance(getProject()).runWhenSmart(() -> editor.setState(finalState, exactState)); } else { editor.setState(state, exactState); } } } @Override public @NotNull ActionCallback notifyPublisher(@NotNull Runnable runnable) { IdeFocusManager focusManager = IdeFocusManager.getInstance(myProject); ActionCallback done = new ActionCallback(); return myBusyObject.execute(new ActiveRunnable() { @Override public @NotNull ActionCallback run() { focusManager.doWhenFocusSettlesDown(ExpirableRunnable.forProject(myProject, () -> { runnable.run(); done.setDone(); }), ModalityState.current()); return done; } }); } @Override public void setSelectedEditor(@NotNull VirtualFile file, @NotNull String fileEditorProviderId) { ApplicationManager.getApplication().assertIsDispatchThread(); EditorWithProviderComposite composite = getCurrentEditorWithProviderComposite(file); if (composite == null) { List<EditorWithProviderComposite> composites = getEditorComposites(file); if (composites.isEmpty()) return; composite = composites.get(0); } FileEditorProvider[] editorProviders = composite.getProviders(); FileEditorProvider selectedProvider = composite.getSelectedWithProvider().getProvider(); for (int i = 0; i < editorProviders.length; i++) { if (editorProviders[i].getEditorTypeId().equals(fileEditorProviderId) && !selectedProvider.equals(editorProviders[i])) { composite.setSelectedEditor(i); composite.getSelectedEditor().selectNotify(); } } } @Nullable EditorWithProviderComposite newEditorComposite(@NotNull VirtualFile file) { FileEditorProviderManager editorProviderManager = FileEditorProviderManager.getInstance(); FileEditorProvider[] providers = editorProviderManager.getProviders(myProject, file); if (providers.length == 0) return null; FileEditor[] editors = new FileEditor[providers.length]; for (int i = 0; i < providers.length; i++) { FileEditorProvider provider = providers[i]; LOG.assertTrue(provider != null); LOG.assertTrue(provider.accept(myProject, file)); FileEditor editor = provider.createEditor(myProject, file); editors[i] = editor; LOG.assertTrue(editor.isValid()); editor.addPropertyChangeListener(myEditorPropertyChangeListener); } EditorWithProviderComposite newComposite = new EditorWithProviderComposite(file, editors, providers, this); EditorHistoryManager editorHistoryManager = EditorHistoryManager.getInstance(myProject); for (int i = 0; i < editors.length; i++) { FileEditor editor = editors[i]; FileEditorProvider provider = providers[i]; // Restore myEditor state FileEditorState state = editorHistoryManager.getState(file, provider); if (state != null) { editor.setState(state); } } return newComposite; } @Override public @NotNull List<FileEditor> openFileEditor(@NotNull FileEditorNavigatable descriptor, boolean focusEditor) { return openEditorImpl(descriptor, focusEditor).first; } /** * @return the list of opened editors, and the one of them that was selected (if any) */ private Pair<List<FileEditor>, FileEditor> openEditorImpl(@NotNull FileEditorNavigatable descriptor, boolean focusEditor) { assertDispatchThread(); FileEditorNavigatable realDescriptor; if (descriptor instanceof OpenFileDescriptor && descriptor.getFile() instanceof VirtualFileWindow) { OpenFileDescriptor openFileDescriptor = (OpenFileDescriptor)descriptor; VirtualFileWindow delegate = (VirtualFileWindow)descriptor.getFile(); int hostOffset = delegate.getDocumentWindow().injectedToHost(openFileDescriptor.getOffset()); OpenFileDescriptor fixedDescriptor = new OpenFileDescriptor(openFileDescriptor.getProject(), delegate.getDelegate(), hostOffset); fixedDescriptor.setUseCurrentWindow(openFileDescriptor.isUseCurrentWindow()); realDescriptor = fixedDescriptor; } else { realDescriptor = descriptor; } List<FileEditor> result = new SmartList<>(); Ref<FileEditor> selectedEditor = new Ref<>(); CommandProcessor.getInstance().executeCommand(myProject, () -> { VirtualFile file = realDescriptor.getFile(); FileEditor[] editors = openFile(file, focusEditor, !realDescriptor.isUseCurrentWindow()); ContainerUtil.addAll(result, editors); boolean navigated = false; for (FileEditor editor : editors) { if (editor instanceof NavigatableFileEditor && getSelectedEditor(realDescriptor.getFile()) == editor) { // try to navigate opened editor navigated = navigateAndSelectEditor((NavigatableFileEditor)editor, realDescriptor); if (navigated) { selectedEditor.set(editor); break; } } } if (!navigated) { for (FileEditor editor : editors) { if (editor instanceof NavigatableFileEditor && getSelectedEditor(realDescriptor.getFile()) != editor) { // try other editors if (navigateAndSelectEditor((NavigatableFileEditor)editor, realDescriptor)) { selectedEditor.set(editor); break; } } } } }, "", null); return Pair.create(result, selectedEditor.get()); } private boolean navigateAndSelectEditor(@NotNull NavigatableFileEditor editor, @NotNull Navigatable descriptor) { if (editor.canNavigateTo(descriptor)) { setSelectedEditor(editor); editor.navigateTo(descriptor); return true; } return false; } private void setSelectedEditor(@NotNull FileEditor editor) { EditorWithProviderComposite composite = getEditorComposite(editor); if (composite == null) return; FileEditor[] editors = composite.getEditors(); for (int i = 0; i < editors.length; i++) { FileEditor each = editors[i]; if (editor == each) { composite.setSelectedEditor(i); composite.getSelectedEditor().selectNotify(); break; } } } @Override public @NotNull Project getProject() { return myProject; } @Override public @Nullable Editor openTextEditor(@NotNull OpenFileDescriptor descriptor, boolean focusEditor) { TextEditor textEditor = doOpenTextEditor(descriptor, focusEditor); return textEditor == null ? null : textEditor.getEditor(); } private @Nullable TextEditor doOpenTextEditor(@NotNull FileEditorNavigatable descriptor, boolean focusEditor) { Pair<List<FileEditor>, FileEditor> editorsWithSelected = openEditorImpl(descriptor, focusEditor); Collection<FileEditor> fileEditors = editorsWithSelected.first; FileEditor selectedEditor = editorsWithSelected.second; if (fileEditors.isEmpty()) return null; else if (fileEditors.size() == 1) return ObjectUtils.tryCast(ContainerUtil.getFirstItem(fileEditors), TextEditor.class); List<TextEditor> textEditors = ContainerUtil.mapNotNull(fileEditors, e -> ObjectUtils.tryCast(e, TextEditor.class)); if (textEditors.isEmpty()) return null; TextEditor target = selectedEditor instanceof TextEditor ? (TextEditor)selectedEditor : textEditors.get(0); if (textEditors.size() > 1) { EditorWithProviderComposite composite = getEditorComposite(target); assert composite != null; FileEditor[] editors = composite.getEditors(); FileEditorProvider[] providers = composite.getProviders(); String textProviderId = TextEditorProvider.getInstance().getEditorTypeId(); for (int i = 0; i < editors.length; i++) { FileEditor editor = editors[i]; if (editor instanceof TextEditor && providers[i].getEditorTypeId().equals(textProviderId)) { target = (TextEditor)editor; break; } } } setSelectedEditor(target); return target; } @Override public Editor getSelectedTextEditor() { return getSelectedTextEditor(false); } public Editor getSelectedTextEditor(boolean lockfree) { if (!lockfree) { assertDispatchThread(); } EditorWindow currentWindow = lockfree ? getMainSplitters().getCurrentWindow() : getSplitters().getCurrentWindow(); if (currentWindow != null) { EditorWithProviderComposite selectedEditor = currentWindow.getSelectedEditor(); if (selectedEditor != null && selectedEditor.getSelectedEditor() instanceof TextEditor) { return ((TextEditor)selectedEditor.getSelectedEditor()).getEditor(); } } return null; } @Override public boolean isFileOpen(@NotNull VirtualFile file) { for (EditorComposite editor : myOpenedEditors) { if (editor.getFile().equals(file)) { return true; } } return false; } @Override public VirtualFile @NotNull [] getOpenFiles() { Set<VirtualFile> files = new LinkedHashSet<>(); for (EditorComposite composite : myOpenedEditors) { files.add(composite.getFile()); } return VfsUtilCore.toVirtualFileArray(files); } @Override public boolean hasOpenFiles() { return !myOpenedEditors.isEmpty(); } @Override public VirtualFile @NotNull [] getSelectedFiles() { Set<VirtualFile> selectedFiles = new LinkedHashSet<>(); EditorsSplitters activeSplitters = getSplitters(); ContainerUtil.addAll(selectedFiles, activeSplitters.getSelectedFiles()); for (EditorsSplitters each : getAllSplitters()) { if (each != activeSplitters) { ContainerUtil.addAll(selectedFiles, each.getSelectedFiles()); } } return VfsUtilCore.toVirtualFileArray(selectedFiles); } @Override public FileEditor @NotNull [] getSelectedEditors() { Set<FileEditor> selectedEditors = new SmartHashSet<>(); for (EditorsSplitters splitters : getAllSplitters()) { splitters.addSelectedEditorsTo(selectedEditors); } return selectedEditors.toArray(FileEditor.EMPTY_ARRAY); } @Override public @NotNull EditorsSplitters getSplitters() { EditorsSplitters active = null; if (ApplicationManager.getApplication().isDispatchThread()) active = getActiveSplittersSync(); return active == null ? getMainSplitters() : active; } @Override public @Nullable FileEditor getSelectedEditor() { EditorWindow window = getSplitters().getCurrentWindow(); if (window != null) { EditorComposite selected = window.getSelectedEditor(); if (selected != null) return selected.getSelectedEditor(); } return super.getSelectedEditor(); } @Override public @Nullable FileEditor getSelectedEditor(@NotNull VirtualFile file) { FileEditorWithProvider editorWithProvider = getSelectedEditorWithProvider(file); return editorWithProvider == null ? null : editorWithProvider.getFileEditor(); } @Override public @Nullable FileEditorWithProvider getSelectedEditorWithProvider(@NotNull VirtualFile file) { ApplicationManager.getApplication().assertIsDispatchThread(); if (file instanceof VirtualFileWindow) file = ((VirtualFileWindow)file).getDelegate(); file = BackedVirtualFile.getOriginFileIfBacked(file); EditorWithProviderComposite composite = getCurrentEditorWithProviderComposite(file); if (composite != null) { return composite.getSelectedWithProvider(); } List<EditorWithProviderComposite> composites = getEditorComposites(file); return composites.isEmpty() ? null : composites.get(0).getSelectedWithProvider(); } @Override public @NotNull Pair<FileEditor[], FileEditorProvider[]> getEditorsWithProviders(@NotNull VirtualFile file) { ApplicationManager.getApplication().assertIsDispatchThread(); EditorWithProviderComposite composite = getCurrentEditorWithProviderComposite(file); if (composite != null) { return new Pair<>(composite.getEditors(), composite.getProviders()); } List<EditorWithProviderComposite> composites = getEditorComposites(file); if (!composites.isEmpty()) { return new Pair<>(composites.get(0).getEditors(), composites.get(0).getProviders()); } return new Pair<>(FileEditor.EMPTY_ARRAY, EMPTY_PROVIDER_ARRAY); } @Override public FileEditor @NotNull [] getEditors(@NotNull VirtualFile file) { ApplicationManager.getApplication().assertIsDispatchThread(); if (file instanceof VirtualFileWindow) { file = ((VirtualFileWindow)file).getDelegate(); } file = BackedVirtualFile.getOriginFileIfBacked(file); EditorWithProviderComposite composite = getCurrentEditorWithProviderComposite(file); if (composite != null) { return composite.getEditors(); } List<EditorWithProviderComposite> composites = getEditorComposites(file); if (!composites.isEmpty()) { return composites.get(0).getEditors(); } return FileEditor.EMPTY_ARRAY; } @Override public FileEditor @NotNull [] getAllEditors(@NotNull VirtualFile file) { List<FileEditor> result = new ArrayList<>(); myOpenedEditors.forEach(composite -> { if (composite.getFile().equals(file)) ContainerUtil.addAll(result, composite.myEditors); }); return result.toArray(FileEditor.EMPTY_ARRAY); } private @Nullable EditorWithProviderComposite getCurrentEditorWithProviderComposite(@NotNull VirtualFile virtualFile) { EditorWindow editorWindow = getSplitters().getCurrentWindow(); if (editorWindow != null) { return editorWindow.findFileComposite(virtualFile); } return null; } private @NotNull List<EditorWithProviderComposite> getEditorComposites(@NotNull VirtualFile file) { List<EditorWithProviderComposite> result = new ArrayList<>(); Set<EditorsSplitters> all = getAllSplitters(); for (EditorsSplitters each : all) { result.addAll(each.findEditorComposites(file)); } return result; } @Override public FileEditor @NotNull [] getAllEditors() { List<FileEditor> result = new ArrayList<>(); myOpenedEditors.forEach(composite -> ContainerUtil.addAll(result, composite.myEditors)); return result.toArray(FileEditor.EMPTY_ARRAY); } public @NotNull List<JComponent> getTopComponents(@NotNull FileEditor editor) { ApplicationManager.getApplication().assertIsDispatchThread(); EditorComposite composite = getEditorComposite(editor); return composite != null ? composite.getTopComponents(editor) : Collections.emptyList(); } @Override public void addTopComponent(@NotNull FileEditor editor, @NotNull JComponent component) { ApplicationManager.getApplication().assertIsDispatchThread(); EditorComposite composite = getEditorComposite(editor); if (composite != null) { composite.addTopComponent(editor, component); } } @Override public void removeTopComponent(@NotNull FileEditor editor, @NotNull JComponent component) { ApplicationManager.getApplication().assertIsDispatchThread(); EditorComposite composite = getEditorComposite(editor); if (composite != null) { composite.removeTopComponent(editor, component); } } @Override public void addBottomComponent(@NotNull FileEditor editor, @NotNull JComponent component) { ApplicationManager.getApplication().assertIsDispatchThread(); EditorComposite composite = getEditorComposite(editor); if (composite != null) { composite.addBottomComponent(editor, component); } } @Override public void removeBottomComponent(@NotNull FileEditor editor, @NotNull JComponent component) { ApplicationManager.getApplication().assertIsDispatchThread(); EditorComposite composite = getEditorComposite(editor); if (composite != null) { composite.removeBottomComponent(editor, component); } } @Override public void addFileEditorManagerListener(@NotNull FileEditorManagerListener listener) { myListenerList.add(listener); } @Override public void removeFileEditorManagerListener(@NotNull FileEditorManagerListener listener) { myListenerList.remove(listener); } protected void projectOpened(@NotNull MessageBusConnection connection) { //myFocusWatcher.install(myWindows.getComponent ()); getMainSplitters().startListeningFocus(); FileStatusManager fileStatusManager = FileStatusManager.getInstance(myProject); if (fileStatusManager != null) { // updates tabs colors fileStatusManager.addFileStatusListener(new MyFileStatusListener(), myProject); } connection.subscribe(FileTypeManager.TOPIC, new MyFileTypeListener()); connection.subscribe(ProjectTopics.PROJECT_ROOTS, new MyRootsListener()); // updates tabs names connection.subscribe(VirtualFileManager.VFS_CHANGES, new MyVirtualFileListener()); // extends/cuts number of opened tabs. Also updates location of tabs connection.subscribe(UISettingsListener.TOPIC, new MyUISettingsListener()); StartupManager.getInstance(myProject).runAfterOpened(() -> { if (myProject.isDisposed()) { return; } ApplicationManager.getApplication().invokeLater(() -> CommandProcessor.getInstance().executeCommand(myProject, () -> { ApplicationManager.getApplication().invokeLater(() -> { Long startTime = myProject.getUserData(ProjectImpl.CREATION_TIME); if (startTime != null) { long time = TimeoutUtil.getDurationMillis(startTime.longValue()); LifecycleUsageTriggerCollector.onProjectOpenFinished(myProject, time); LOG.info("Project opening took " + time + " ms"); } }, myProject.getDisposed()); // group 1 }, "", null), myProject.getDisposed()); }); } @Override public @Nullable Element getState() { if (mySplitters == null) { // do not save if not initialized yet return null; } Element state = new Element("state"); getMainSplitters().writeExternal(state); return state; } @Override public void loadState(@NotNull Element state) { getMainSplitters().readExternal(state); } protected @Nullable EditorWithProviderComposite getEditorComposite(@NotNull FileEditor editor) { for (EditorsSplitters splitters : getAllSplitters()) { List<EditorWithProviderComposite> editorsComposites = splitters.getEditorComposites(); for (int i = editorsComposites.size() - 1; i >= 0; i--) { EditorWithProviderComposite composite = editorsComposites.get(i); FileEditor[] editors = composite.getEditors(); for (int j = editors.length - 1; j >= 0; j--) { FileEditor _editor = editors[j]; LOG.assertTrue(_editor != null); if (editor.equals(_editor)) { return composite; } } } } return null; } private static void assertDispatchThread() { ApplicationManager.getApplication().assertIsDispatchThread(); } private static void assertReadAccess() { ApplicationManager.getApplication().assertReadAccessAllowed(); } public void fireSelectionChanged(@Nullable EditorComposite newSelectedComposite) { Trinity<VirtualFile, FileEditor, FileEditorProvider> oldData = extract(SoftReference.dereference(myLastSelectedComposite)); Trinity<VirtualFile, FileEditor, FileEditorProvider> newData = extract(newSelectedComposite); myLastSelectedComposite = newSelectedComposite == null ? null : new WeakReference<>(newSelectedComposite); boolean filesEqual = Objects.equals(oldData.first, newData.first); boolean editorsEqual = Objects.equals(oldData.second, newData.second); if (!filesEqual || !editorsEqual) { if (oldData.first != null && newData.first != null) { for (FileEditorAssociateFinder finder : FileEditorAssociateFinder.EP_NAME.getExtensionList()) { VirtualFile associatedFile = finder.getAssociatedFileToOpen(myProject, oldData.first); if (Comparing.equal(associatedFile, newData.first)) { return; } } } FileEditorManagerEvent event = new FileEditorManagerEvent(this, oldData.first, oldData.second, oldData.third, newData.first, newData.second, newData.third); FileEditorManagerListener publisher = getProject().getMessageBus().syncPublisher(FileEditorManagerListener.FILE_EDITOR_MANAGER); if (newData.first != null) { JComponent component = newData.second.getComponent(); EditorWindowHolder holder = ComponentUtil.getParentOfType((Class<? extends EditorWindowHolder>)EditorWindowHolder.class, (Component)component); if (holder != null) { addSelectionRecord(newData.first, holder.getEditorWindow()); } } notifyPublisher(() -> publisher.selectionChanged(event)); } } private static @NotNull Trinity<VirtualFile, FileEditor, FileEditorProvider> extract(@Nullable EditorComposite composite) { VirtualFile file; FileEditor editor; FileEditorProvider provider; if (composite == null) { file = null; editor = null; provider = null; } else { file = composite.getFile(); FileEditorWithProvider pair = composite.getSelectedWithProvider(); editor = pair.getFileEditor(); provider = pair.getProvider(); } return new Trinity<>(file, editor, provider); } @Override public boolean isChanged(@NotNull EditorComposite editor) { FileStatusManager fileStatusManager = FileStatusManager.getInstance(myProject); if (fileStatusManager == null) { return false; } FileStatus status = fileStatusManager.getStatus(editor.getFile()); return status != FileStatus.UNKNOWN && status != FileStatus.NOT_CHANGED; } void disposeComposite(@NotNull EditorWithProviderComposite editor) { myOpenedEditors.remove(editor); if (getAllEditors().length == 0) { setCurrentWindow(null); } if (editor.equals(getLastSelected())) { editor.getSelectedEditor().deselectNotify(); getSplitters().setCurrentWindow(null, false); } FileEditor[] editors = editor.getEditors(); FileEditorProvider[] providers = editor.getProviders(); FileEditor selectedEditor = editor.getSelectedEditor(); for (int i = editors.length - 1; i >= 0; i--) { FileEditor editor1 = editors[i]; FileEditorProvider provider = providers[i]; // we already notified the myEditor (when fire event) if (selectedEditor.equals(editor1)) { editor1.deselectNotify(); } editor1.removePropertyChangeListener(myEditorPropertyChangeListener); provider.disposeEditor(editor1); } Disposer.dispose(editor); } private @Nullable EditorComposite getLastSelected() { EditorWindow currentWindow = getActiveSplittersSync().getCurrentWindow(); if (currentWindow != null) { return currentWindow.getSelectedEditor(); } return null; } /** * @param splitters - taken getAllSplitters() value if parameter is null */ private void runChange(@NotNull FileEditorManagerChange change, @Nullable EditorsSplitters splitters) { Set<EditorsSplitters> target = new HashSet<>(); if (splitters == null) { target.addAll(getAllSplitters()); } else { target.add(splitters); } for (EditorsSplitters each : target) { runBulkTabChange(each, change); } } static void runBulkTabChange(@NotNull EditorsSplitters splitters, @NotNull FileEditorManagerChange change) { if (!ApplicationManager.getApplication().isDispatchThread()) { change.run(splitters); } else { splitters.myInsideChange++; try { change.run(splitters); } finally { splitters.myInsideChange--; if (!splitters.isInsideChange()) { splitters.validate(); for (EditorWindow window : splitters.getWindows()) { ((JBTabsImpl)window.getTabbedPane().getTabs()).revalidateAndRepaint(); } } } } } /** * Closes deleted files. Closes file which are in the deleted directories. */ private final class MyVirtualFileListener implements BulkFileListener { @Override public void before(@NotNull List<? extends VFileEvent> events) { for (VFileEvent event : events) { if (event instanceof VFileDeleteEvent) { beforeFileDeletion((VFileDeleteEvent)event); } } } @Override public void after(@NotNull List<? extends VFileEvent> events) { for (VFileEvent event : events) { if (event instanceof VFilePropertyChangeEvent) { propertyChanged((VFilePropertyChangeEvent)event); } else if (event instanceof VFileMoveEvent) { fileMoved((VFileMoveEvent)event); } } } private void beforeFileDeletion(@NotNull VFileDeleteEvent event) { assertDispatchThread(); VirtualFile file = event.getFile(); VirtualFile[] openFiles = getOpenFiles(); for (int i = openFiles.length - 1; i >= 0; i--) { if (VfsUtilCore.isAncestor(file, openFiles[i], false)) { closeFile(openFiles[i],true, true); } } } private void propertyChanged(@NotNull VFilePropertyChangeEvent event) { if (VirtualFile.PROP_NAME.equals(event.getPropertyName())) { assertDispatchThread(); VirtualFile file = event.getFile(); if (isFileOpen(file)) { updateFileName(file); updateFileIcon(file); // file type can change after renaming updateFileBackgroundColor(file); } } else if (VirtualFile.PROP_WRITABLE.equals(event.getPropertyName()) || VirtualFile.PROP_ENCODING.equals(event.getPropertyName())) { updateIcon(event); } } private void updateIcon(@NotNull VFilePropertyChangeEvent event) { assertDispatchThread(); VirtualFile file = event.getFile(); if (isFileOpen(file)) { updateFileIcon(file); } } private void fileMoved(@NotNull VFileMoveEvent e) { VirtualFile file = e.getFile(); for (VirtualFile openFile : getOpenFiles()) { if (VfsUtilCore.isAncestor(file, openFile, false)) { updateFileName(openFile); updateFileBackgroundColor(openFile); } } } } @Override public boolean isInsideChange() { return getSplitters().isInsideChange(); } private final class MyEditorPropertyChangeListener implements PropertyChangeListener { @Override public void propertyChange(@NotNull PropertyChangeEvent e) { assertDispatchThread(); String propertyName = e.getPropertyName(); if (FileEditor.PROP_MODIFIED.equals(propertyName)) { FileEditor editor = (FileEditor)e.getSource(); EditorComposite composite = getEditorComposite(editor); if (composite != null) { updateFileIcon(composite.getFile()); } } else if (FileEditor.PROP_VALID.equals(propertyName)) { boolean valid = ((Boolean)e.getNewValue()).booleanValue(); if (!valid) { FileEditor editor = (FileEditor)e.getSource(); LOG.assertTrue(editor != null); EditorComposite composite = getEditorComposite(editor); if (composite != null) { closeFile(composite.getFile()); } } } } } /** * Gets events from VCS and updates color of myEditor tabs */ private final class MyFileStatusListener implements FileStatusListener { @Override public void fileStatusesChanged() { // update color of all open files assertDispatchThread(); LOG.debug("FileEditorManagerImpl.MyFileStatusListener.fileStatusesChanged()"); VirtualFile[] openFiles = getOpenFiles(); for (int i = openFiles.length - 1; i >= 0; i--) { VirtualFile file = openFiles[i]; LOG.assertTrue(file != null); ApplicationManager.getApplication().invokeLater(() -> { if (LOG.isDebugEnabled()) { LOG.debug("updating file status in tab for " + file.getPath()); } updateFileStatus(file); }, ModalityState.NON_MODAL, myProject.getDisposed()); } } @Override public void fileStatusChanged(@NotNull VirtualFile file) { // update color of the file (if necessary) assertDispatchThread(); if (isFileOpen(file)) { updateFileStatus(file); } } private void updateFileStatus(VirtualFile file) { updateFileColor(file); updateFileIcon(file); } } /** * Gets events from FileTypeManager and updates icons on tabs */ private final class MyFileTypeListener implements FileTypeListener { @Override public void fileTypesChanged(@NotNull FileTypeEvent event) { assertDispatchThread(); VirtualFile[] openFiles = getOpenFiles(); for (int i = openFiles.length - 1; i >= 0; i--) { VirtualFile file = openFiles[i]; LOG.assertTrue(file != null); updateFileIcon(file, true); } } } private class MyRootsListener implements ModuleRootListener { @Override public void rootsChanged(@NotNull ModuleRootEvent event) { AppUIExecutor .onUiThread(ModalityState.any()) .expireWith(myProject) .submit(() -> StreamEx.of(getWindows()).flatArray(EditorWindow::getEditors).toList()) .onSuccess(allEditors -> ReadAction .nonBlocking(() -> calcEditorReplacements(allEditors)) .inSmartMode(myProject) .finishOnUiThread(ModalityState.defaultModalityState(), this::replaceEditors) .coalesceBy(this) .submit(AppExecutorUtil.getAppExecutorService())); } private Map<EditorWithProviderComposite, Pair<VirtualFile, Integer>> calcEditorReplacements(List<EditorWithProviderComposite> allEditors) { List<EditorFileSwapper> swappers = EditorFileSwapper.EP_NAME.getExtensionList(); return StreamEx.of(allEditors).mapToEntry(editor -> { if (editor.getFile().isValid()) { for (EditorFileSwapper each : swappers) { Pair<VirtualFile, Integer> fileAndOffset = each.getFileToSwapTo(myProject, editor); if (fileAndOffset != null) return fileAndOffset; } } return null; }).nonNullValues().toMap(); } private void replaceEditors(Map<EditorWithProviderComposite, Pair<VirtualFile, Integer>> replacements) { if (replacements.isEmpty()) return; for (EditorWindow eachWindow : getWindows()) { EditorWithProviderComposite selected = eachWindow.getSelectedEditor(); EditorWithProviderComposite[] editors = eachWindow.getEditors(); for (int i = 0; i < editors.length; i++) { EditorWithProviderComposite editor = editors[i]; VirtualFile file = editor.getFile(); if (!file.isValid()) continue; Pair<VirtualFile, Integer> newFilePair = replacements.get(editor); if (newFilePair == null) continue; VirtualFile newFile = newFilePair.first; if (newFile == null) continue; // already open if (eachWindow.findFileIndex(newFile) != -1) continue; try { newFile.putUserData(EditorWindow.INITIAL_INDEX_KEY, i); Pair<FileEditor[], FileEditorProvider[]> pair = openFileImpl2(eachWindow, newFile, editor == selected); if (newFilePair.second != null) { TextEditorImpl openedEditor = EditorFileSwapper.findSinglePsiAwareEditor(pair.first); if (openedEditor != null) { openedEditor.getEditor().getCaretModel().moveToOffset(newFilePair.second); openedEditor.getEditor().getScrollingModel().scrollToCaret(ScrollType.CENTER); } } } finally { newFile.putUserData(EditorWindow.INITIAL_INDEX_KEY, null); } closeFile(file, eachWindow); } } } } /** * Gets notifications from UISetting component to track changes of RECENT_FILES_LIMIT * and EDITOR_TAB_LIMIT, etc values. */ private final class MyUISettingsListener implements UISettingsListener { @Override public void uiSettingsChanged(@NotNull UISettings uiSettings) { assertDispatchThread(); mySplitters.revalidate(); for (EditorsSplitters each : getAllSplitters()) { each.setTabsPlacement(uiSettings.getEditorTabPlacement()); each.trimToSize(); if (JBTabsImpl.NEW_TABS) { TabsLayoutInfo tabsLayoutInfo = TabsLayoutSettingsManager.getInstance().getSelectedTabsLayoutInfo(); each.updateTabsLayout(tabsLayoutInfo); } else { // Tab layout policy if (uiSettings.getScrollTabLayoutInEditor()) { each.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); } else { each.setTabLayoutPolicy(JTabbedPane.WRAP_TAB_LAYOUT); } } } // "Mark modified files with asterisk" VirtualFile[] openFiles = getOpenFiles(); for (int i = openFiles.length - 1; i >= 0; i--) { VirtualFile file = openFiles[i]; updateFileIcon(file); updateFileName(file); updateFileBackgroundColor(file); } // "Show full paths in window header" updateFrameTitle(); } } @Override public void closeAllFiles() { runBulkTabChange(getSplitters(), splitters -> { for (VirtualFile openFile : splitters.getOpenFileList()) { closeFile(openFile); } }); } @Override public VirtualFile @NotNull [] getSiblings(@NotNull VirtualFile file) { return getOpenFiles(); } void queueUpdateFile(@NotNull VirtualFile file) { myQueue.queue(new Update(file) { @Override public void run() { if (isFileOpen(file)) { updateFileIcon(file); updateFileColor(file); updateFileBackgroundColor(file); resetPreviewFlag(file); } } }); } @Override public EditorsSplitters getSplittersFor(Component c) { EditorsSplitters splitters = null; DockContainer dockContainer = myDockManager.getContainerFor(c); if (dockContainer instanceof DockableEditorTabbedContainer) { splitters = ((DockableEditorTabbedContainer)dockContainer).getSplitters(); } if (splitters == null) { splitters = getMainSplitters(); } return splitters; } public @NotNull List<Pair<VirtualFile, EditorWindow>> getSelectionHistory() { List<Pair<VirtualFile, EditorWindow>> copy = new ArrayList<>(); for (Pair<VirtualFile, EditorWindow> pair : mySelectionHistory) { if (pair.second.getFiles().length == 0) { EditorWindow[] windows = pair.second.getOwner().getWindows(); if (windows.length > 0 && windows[0] != null && windows[0].getFiles().length > 0) { Pair<VirtualFile, EditorWindow> p = Pair.create(pair.first, windows[0]); if (!copy.contains(p)) { copy.add(p); } } } else { if (!copy.contains(pair)) { copy.add(pair); } } } mySelectionHistory.clear(); mySelectionHistory.addAll(copy); return mySelectionHistory; } public void addSelectionRecord(@NotNull VirtualFile file, @NotNull EditorWindow window) { Pair<VirtualFile, EditorWindow> record = Pair.create(file, window); mySelectionHistory.remove(record); mySelectionHistory.add(0, record); } void removeSelectionRecord(@NotNull VirtualFile file, @NotNull EditorWindow window) { mySelectionHistory.remove(Pair.create(file, window)); updateFileName(file); } @Override public @NotNull ActionCallback getReady(@NotNull Object requestor) { return myBusyObject.getReady(requestor); } }
platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileEditorManagerImpl.java
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.fileEditor.impl; import com.intellij.ProjectTopics; import com.intellij.featureStatistics.fusCollectors.LifecycleUsageTriggerCollector; import com.intellij.ide.IdeBundle; import com.intellij.ide.IdeEventQueue; import com.intellij.ide.actions.HideAllToolWindowsAction; import com.intellij.ide.actions.SplitAction; import com.intellij.ide.ui.UISettings; import com.intellij.ide.ui.UISettingsListener; import com.intellij.injected.editor.VirtualFileWindow; import com.intellij.notebook.editor.BackedVirtualFile; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.*; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.openapi.components.StoragePathMacros; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.ScrollType; import com.intellij.openapi.editor.event.EditorFactoryEvent; import com.intellij.openapi.editor.event.EditorFactoryListener; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.editor.ex.FocusChangeListener; import com.intellij.openapi.extensions.ExtensionPointListener; import com.intellij.openapi.extensions.PluginDescriptor; import com.intellij.openapi.fileEditor.*; import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx; import com.intellij.openapi.fileEditor.ex.FileEditorProviderManager; import com.intellij.openapi.fileEditor.ex.FileEditorWithProvider; import com.intellij.openapi.fileEditor.ex.IdeDocumentHistory; import com.intellij.openapi.fileEditor.impl.text.TextEditorImpl; import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider; import com.intellij.openapi.fileTypes.FileTypeEvent; import com.intellij.openapi.fileTypes.FileTypeListener; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.keymap.Keymap; import com.intellij.openapi.keymap.KeymapManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.project.*; import com.intellij.openapi.project.impl.ProjectImpl; import com.intellij.openapi.roots.ModuleRootEvent; import com.intellij.openapi.roots.ModuleRootListener; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.ui.Splitter; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.vcs.FileStatus; import com.intellij.openapi.vcs.FileStatusListener; import com.intellij.openapi.vcs.FileStatusManager; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.newvfs.BulkFileListener; import com.intellij.openapi.vfs.newvfs.events.VFileDeleteEvent; import com.intellij.openapi.vfs.newvfs.events.VFileEvent; import com.intellij.openapi.vfs.newvfs.events.VFileMoveEvent; import com.intellij.openapi.vfs.newvfs.events.VFilePropertyChangeEvent; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.pom.Navigatable; import com.intellij.reference.SoftReference; import com.intellij.ui.ComponentUtil; import com.intellij.ui.docking.DockContainer; import com.intellij.ui.docking.DockManager; import com.intellij.ui.docking.impl.DockManagerImpl; import com.intellij.ui.tabs.impl.JBTabsImpl; import com.intellij.ui.tabs.impl.tabsLayout.TabsLayoutInfo; import com.intellij.ui.tabs.impl.tabsLayout.TabsLayoutSettingsManager; import com.intellij.util.*; import com.intellij.util.concurrency.AppExecutorUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.SmartHashSet; import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.messages.impl.MessageListenerList; import com.intellij.util.ui.EdtInvocationManager; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.update.MergingUpdateQueue; import com.intellij.util.ui.update.Update; import one.util.streamex.StreamEx; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.concurrency.AsyncPromise; import org.jetbrains.concurrency.Promise; import javax.swing.*; import java.awt.*; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.util.List; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicInteger; import static com.intellij.openapi.actionSystem.IdeActions.ACTION_OPEN_IN_NEW_WINDOW; import static com.intellij.openapi.actionSystem.IdeActions.ACTION_OPEN_IN_RIGHT_SPLIT; /** * @author Anton Katilin * @author Eugene Belyaev * @author Vladimir Kondratyev */ @State(name = "FileEditorManager", storages = { @Storage(StoragePathMacros.PRODUCT_WORKSPACE_FILE), @Storage(value = StoragePathMacros.WORKSPACE_FILE, deprecated = true) }) public class FileEditorManagerImpl extends FileEditorManagerEx implements PersistentStateComponent<Element>, Disposable { private static final Logger LOG = Logger.getInstance(FileEditorManagerImpl.class); protected static final Key<Boolean> DUMB_AWARE = Key.create("DUMB_AWARE"); public static final Key<Boolean> NOTHING_WAS_OPENED_ON_START = Key.create("NOTHING_WAS_OPENED_ON_START"); private static final FileEditorProvider[] EMPTY_PROVIDER_ARRAY = {}; public static final Key<Boolean> CLOSING_TO_REOPEN = Key.create("CLOSING_TO_REOPEN"); public static final Key<Boolean> OPEN_IN_PREVIEW_TAB = Key.create("OPEN_IN_PREVIEW_TAB"); public static final String FILE_EDITOR_MANAGER = "FileEditorManager"; public enum OpenMode { NEW_WINDOW, RIGHT_SPLIT, DEFAULT } private EditorsSplitters mySplitters; private final Project myProject; private final List<Pair<VirtualFile, EditorWindow>> mySelectionHistory = new ArrayList<>(); private Reference<EditorComposite> myLastSelectedComposite = new WeakReference<>(null); private final MergingUpdateQueue myQueue = new MergingUpdateQueue("FileEditorManagerUpdateQueue", 50, true, MergingUpdateQueue.ANY_COMPONENT, this); private final BusyObject.Impl.Simple myBusyObject = new BusyObject.Impl.Simple(); /** * Removes invalid myEditor and updates "modified" status. */ private final PropertyChangeListener myEditorPropertyChangeListener = new MyEditorPropertyChangeListener(); private final DockManager myDockManager; private DockableEditorContainerFactory myContentFactory; private static final AtomicInteger ourOpenFilesSetModificationCount = new AtomicInteger(); static final ModificationTracker OPEN_FILE_SET_MODIFICATION_COUNT = ourOpenFilesSetModificationCount::get; private final List<EditorComposite> myOpenedEditors = new CopyOnWriteArrayList<>(); private final MessageListenerList<FileEditorManagerListener> myListenerList; public FileEditorManagerImpl(@NotNull Project project) { myProject = project; myDockManager = DockManager.getInstance(myProject); myListenerList = new MessageListenerList<>(myProject.getMessageBus(), FileEditorManagerListener.FILE_EDITOR_MANAGER); if (FileEditorAssociateFinder.EP_NAME.hasAnyExtensions()) { myListenerList.add(new FileEditorManagerListener() { @Override public void selectionChanged(@NotNull FileEditorManagerEvent event) { EditorsSplitters splitters = getSplitters(); openAssociatedFile(event.getNewFile(), splitters.getCurrentWindow(), splitters); } }); } myQueue.setTrackUiActivity(true); MessageBusConnection connection = project.getMessageBus().connect(this); connection.subscribe(DumbService.DUMB_MODE, new DumbService.DumbModeListener() { @Override public void exitDumbMode() { // can happen under write action, so postpone to avoid deadlock on FileEditorProviderManager.getProviders() ApplicationManager.getApplication().invokeLater(() -> dumbModeFinished(myProject), myProject.getDisposed()); } }); connection.subscribe(ProjectManager.TOPIC, new ProjectManagerListener() { @Override public void projectOpened(@NotNull Project project) { if (project == myProject) { FileEditorManagerImpl.this.projectOpened(connection); } } @Override public void projectClosing(@NotNull Project project) { if (project == myProject) { // Dispose created editors. We do not use use closeEditor method because // it fires event and changes history. closeAllFiles(); } } }); closeFilesOnFileEditorRemoval(); EditorFactory editorFactory = EditorFactory.getInstance(); for (Editor editor : editorFactory.getAllEditors()) { registerEditor(editor); } editorFactory.addEditorFactoryListener(new EditorFactoryListener() { @Override public void editorCreated(@NotNull EditorFactoryEvent event) { registerEditor(event.getEditor()); } }, myProject); } private void registerEditor(Editor editor) { Project project = editor.getProject(); if (project == null || project.isDisposed()) { return; } if (editor instanceof EditorEx) { ((EditorEx)editor).addFocusListener(new FocusChangeListener() { @Override public void focusGained(@NotNull Editor editor1) { if (!Registry.is("editor.maximize.on.focus.gained.if.collapsed.in.split")) return; Component comp = editor1.getComponent(); while (comp != getMainSplitters() && comp != null) { Component parent = comp.getParent(); if (parent instanceof Splitter) { Splitter splitter = (Splitter)parent; if ((splitter.getFirstComponent() == comp && (splitter.getProportion() == splitter.getMinProportion(true) || splitter.getProportion() == splitter.getMinimumProportion())) || (splitter.getProportion() == splitter.getMinProportion(false) || splitter.getProportion() == splitter.getMaximumProportion())) { Set<kotlin.Pair<Splitter, Boolean>> pairs = HideAllToolWindowsAction.Companion.getSplittersToMaximize(project, editor1); for (kotlin.Pair<Splitter, Boolean> pair : pairs) { Splitter s = pair.getFirst(); s.setProportion(pair.getSecond() ? s.getMaximumProportion() : s.getMinimumProportion()); } break; } } comp = parent; } } }); } } private void closeFilesOnFileEditorRemoval() { FileEditorProvider.EP_FILE_EDITOR_PROVIDER.addExtensionPointListener(new ExtensionPointListener<>() { @Override public void extensionRemoved(@NotNull FileEditorProvider extension, @NotNull PluginDescriptor pluginDescriptor) { for (EditorComposite editor : myOpenedEditors) { for (FileEditorProvider provider : editor.getProviders()) { if (provider.equals(extension)) { closeFile(editor.getFile()); break; } } } } }, this); } @Override public void dispose() { } private void dumbModeFinished(Project project) { VirtualFile[] files = getOpenFiles(); for (VirtualFile file : files) { Set<FileEditorProvider> providers = new HashSet<>(); List<EditorWithProviderComposite> composites = getEditorComposites(file); for (EditorWithProviderComposite composite : composites) { ContainerUtil.addAll(providers, composite.getProviders()); } FileEditorProvider[] newProviders = FileEditorProviderManager.getInstance().getProviders(project, file); List<FileEditorProvider> toOpen = new ArrayList<>(Arrays.asList(newProviders)); toOpen.removeAll(providers); // need to open additional non dumb-aware editors for (EditorWithProviderComposite composite : composites) { for (FileEditorProvider provider : toOpen) { FileEditor editor = provider.createEditor(myProject, file); composite.addEditor(editor, provider); } } updateFileBackgroundColor(file); } // update for non-dumb-aware EditorTabTitleProviders updateFileName(null); } public void initDockableContentFactory() { if (myContentFactory != null) { return; } myContentFactory = new DockableEditorContainerFactory(myProject, this); myDockManager.register(DockableEditorContainerFactory.TYPE, myContentFactory, this); } public static boolean isDumbAware(@NotNull FileEditor editor) { return Boolean.TRUE.equals(editor.getUserData(DUMB_AWARE)) && (!(editor instanceof PossiblyDumbAware) || ((PossiblyDumbAware)editor).isDumbAware()); } //------------------------------------------------------------------------------- @Override public JComponent getComponent() { return initUI(); } public @NotNull EditorsSplitters getMainSplitters() { return initUI(); } public @NotNull Set<EditorsSplitters> getAllSplitters() { Set<EditorsSplitters> all = new LinkedHashSet<>(); all.add(getMainSplitters()); Set<DockContainer> dockContainers = myDockManager.getContainers(); for (DockContainer each : dockContainers) { if (each instanceof DockableEditorTabbedContainer) { all.add(((DockableEditorTabbedContainer)each).getSplitters()); } } return Collections.unmodifiableSet(all); } private @NotNull Promise<EditorsSplitters> getActiveSplittersAsync() { AsyncPromise<EditorsSplitters> result = new AsyncPromise<>(); IdeFocusManager fm = IdeFocusManager.getInstance(myProject); TransactionGuard.getInstance().assertWriteSafeContext(ModalityState.defaultModalityState()); fm.doWhenFocusSettlesDown(() -> { if (myProject.isDisposed()) { result.cancel(); return; } Component focusOwner = fm.getFocusOwner(); DockContainer container = myDockManager.getContainerFor(focusOwner); if (container instanceof DockableEditorTabbedContainer) { result.setResult(((DockableEditorTabbedContainer)container).getSplitters()); } else { result.setResult(getMainSplitters()); } }, ModalityState.defaultModalityState()); return result; } private EditorsSplitters getActiveSplittersSync() { assertDispatchThread(); if (Registry.is("ide.navigate.to.recently.focused.editor", false)) { ArrayList<EditorsSplitters> splitters = new ArrayList<>(getAllSplitters()); if (!splitters.isEmpty()) { splitters.sort((o1, o2) -> Long.compare(o2.getLastFocusGainedTime(), o1.getLastFocusGainedTime())); return splitters.get(0); } } IdeFocusManager fm = IdeFocusManager.getInstance(myProject); Component focusOwner = fm.getFocusOwner(); if (focusOwner == null) { focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); } if (focusOwner == null) { focusOwner = fm.getLastFocusedFor(fm.getLastFocusedIdeWindow()); } DockContainer container = myDockManager.getContainerFor(focusOwner); if (container == null) { focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow(); container = myDockManager.getContainerFor(focusOwner); } if (container instanceof DockableEditorTabbedContainer) { return ((DockableEditorTabbedContainer)container).getSplitters(); } return getMainSplitters(); } private final Object myInitLock = new Object(); private @NotNull EditorsSplitters initUI() { EditorsSplitters result = mySplitters; if (result != null) { return result; } synchronized (myInitLock) { result = mySplitters; if (result == null) { result = new EditorsSplitters(this, true, this); mySplitters = result; } } return result; } @Override public JComponent getPreferredFocusedComponent() { assertReadAccess(); EditorWindow window = getSplitters().getCurrentWindow(); if (window != null) { EditorWithProviderComposite editor = window.getSelectedEditor(); if (editor != null) { return editor.getPreferredFocusedComponent(); } } return null; } //------------------------------------------------------- /** * @return color of the {@code file} which corresponds to the * file's status */ @NotNull Color getFileColor(@NotNull VirtualFile file) { FileStatusManager fileStatusManager = FileStatusManager.getInstance(myProject); Color statusColor = fileStatusManager != null ? fileStatusManager.getStatus(file).getColor() : UIUtil.getLabelForeground(); if (statusColor == null) statusColor = UIUtil.getLabelForeground(); return statusColor; } public boolean isProblem(@NotNull VirtualFile file) { return false; } public @NotNull @NlsContexts.Tooltip String getFileTooltipText(@NotNull VirtualFile file) { List<EditorTabTitleProvider> availableProviders = DumbService.getDumbAwareExtensions(myProject, EditorTabTitleProvider.EP_NAME); for (EditorTabTitleProvider provider : availableProviders) { String text = provider.getEditorTabTooltipText(myProject, file); if (text != null) { return text; } } return FileUtil.getLocationRelativeToUserHome(file.getPresentableUrl()); } @Override public void updateFilePresentation(@NotNull VirtualFile file) { if (!isFileOpen(file)) return; updateFileName(file); queueUpdateFile(file); } /** * Updates tab color for the specified {@code file}. The {@code file} * should be opened in the myEditor, otherwise the method throws an assertion. */ private void updateFileColor(@NotNull VirtualFile file) { Set<EditorsSplitters> all = getAllSplitters(); for (EditorsSplitters each : all) { each.updateFileColor(file); } } private void updateFileBackgroundColor(@NotNull VirtualFile file) { Set<EditorsSplitters> all = getAllSplitters(); for (EditorsSplitters each : all) { each.updateFileBackgroundColor(file); } } /** * Updates tab icon for the specified {@code file}. The {@code file} * should be opened in the myEditor, otherwise the method throws an assertion. */ protected void updateFileIcon(@NotNull VirtualFile file) { updateFileIcon(file, false); } /** * Reset the preview tab flag if an internal document change is made. */ private void resetPreviewFlag(@NotNull VirtualFile file) { if (!FileDocumentManager.getInstance().isFileModified(file)) { return; } for (EditorsSplitters splitter : getAllSplitters()) { splitter.findEditorComposites(file).stream() .filter(EditorComposite::isPreview) .forEach(c -> c.setPreview(false)); splitter.updateFileColor(file); } } /** * Updates tab icon for the specified {@code file}. The {@code file} * should be opened in the myEditor, otherwise the method throws an assertion. */ protected void updateFileIcon(@NotNull VirtualFile file, boolean immediately) { Set<EditorsSplitters> all = getAllSplitters(); for (EditorsSplitters each : all) { if (immediately) { each.updateFileIconImmediately(file, IconUtil.computeFileIcon(file, Iconable.ICON_FLAG_READ_STATUS, myProject)); } else { each.updateFileIcon(file); } } } /** * Updates tab title and tab tool tip for the specified {@code file} */ void updateFileName(@Nullable VirtualFile file) { // Queue here is to prevent title flickering when tab is being closed and two events arriving: with component==null and component==next focused tab // only the last event makes sense to handle myQueue.queue(new Update("UpdateFileName " + (file == null ? "" : file.getPath())) { @Override public boolean isExpired() { return myProject.isDisposed() || !myProject.isOpen() || (file == null ? super.isExpired() : !file.isValid()); } @Override public void run() { SlowOperations.allowSlowOperations(() -> { for (EditorsSplitters each : getAllSplitters()) { each.updateFileName(file); } }); } }); } private void updateFrameTitle() { getActiveSplittersAsync().onSuccess(splitters -> splitters.updateFileName(null)); } @Override public VirtualFile getFile(@NotNull FileEditor editor) { EditorComposite editorComposite = getEditorComposite(editor); VirtualFile tabFile = editorComposite == null ? null : editorComposite.getFile(); VirtualFile editorFile = editor.getFile(); if (!Objects.equals(editorFile, tabFile)) { if (editorFile == null) { LOG.warn(editor.getClass().getName() + ".getFile() shall not return null"); } else if (tabFile == null) { //todo DaemonCodeAnalyzerImpl#getSelectedEditors calls it for any Editor //LOG.warn(editor.getClass().getName() + ".getFile() shall be used, fileEditor is not opened in a tab."); } else { LOG.warn("fileEditor.getFile=" + editorFile + " != fileEditorManager.getFile=" + tabFile + ", fileEditor.class=" + editor.getClass().getName()); } } return tabFile; } @Override public void unsplitWindow() { EditorWindow currentWindow = getActiveSplittersSync().getCurrentWindow(); if (currentWindow != null) { currentWindow.unsplit(true); } } @Override public void unsplitAllWindow() { EditorWindow currentWindow = getActiveSplittersSync().getCurrentWindow(); if (currentWindow != null) { currentWindow.unsplitAll(); } } @Override public int getWindowSplitCount() { return getActiveSplittersSync().getSplitCount(); } @Override public boolean hasSplitOrUndockedWindows() { Set<EditorsSplitters> splitters = getAllSplitters(); if (splitters.size() > 1) return true; return getWindowSplitCount() > 1; } @Override public EditorWindow @NotNull [] getWindows() { List<EditorWindow> windows = new ArrayList<>(); Set<EditorsSplitters> all = getAllSplitters(); for (EditorsSplitters each : all) { EditorWindow[] eachList = each.getWindows(); ContainerUtil.addAll(windows, eachList); } return windows.toArray(new EditorWindow[0]); } @Override public EditorWindow getNextWindow(@NotNull EditorWindow window) { List<EditorWindow> windows = getSplitters().getOrderedWindows(); for (int i = 0; i != windows.size(); ++i) { if (windows.get(i).equals(window)) { return windows.get((i + 1) % windows.size()); } } LOG.error("Not window found"); return null; } @Override public EditorWindow getPrevWindow(@NotNull EditorWindow window) { List<EditorWindow> windows = getSplitters().getOrderedWindows(); for (int i = 0; i != windows.size(); ++i) { if (windows.get(i).equals(window)) { return windows.get((i + windows.size() - 1) % windows.size()); } } LOG.error("Not window found"); return null; } @Override public void createSplitter(int orientation, @Nullable EditorWindow window) { // window was available from action event, for example when invoked from the tab menu of an editor that is not the 'current' if (window != null) { window.split(orientation, true, null, false); } // otherwise we'll split the current window, if any else { EditorWindow currentWindow = getSplitters().getCurrentWindow(); if (currentWindow != null) { currentWindow.split(orientation, true, null, false); } } } @Override public void changeSplitterOrientation() { EditorWindow currentWindow = getSplitters().getCurrentWindow(); if (currentWindow != null) { currentWindow.changeOrientation(); } } @Override public boolean isInSplitter() { EditorWindow currentWindow = getSplitters().getCurrentWindow(); return currentWindow != null && currentWindow.inSplitter(); } @Override public boolean hasOpenedFile() { EditorWindow currentWindow = getSplitters().getCurrentWindow(); return currentWindow != null && currentWindow.getSelectedEditor() != null; } @Override public VirtualFile getCurrentFile() { return getActiveSplittersSync().getCurrentFile(); } @Override public @NotNull Promise<EditorWindow> getActiveWindow() { return getActiveSplittersAsync() .then(EditorsSplitters::getCurrentWindow); } @Override public EditorWindow getCurrentWindow() { if (!ApplicationManager.getApplication().isDispatchThread()) return null; EditorsSplitters splitters = getActiveSplittersSync(); return splitters == null ? null : splitters.getCurrentWindow(); } @Override public void setCurrentWindow(EditorWindow window) { getActiveSplittersSync().setCurrentWindow(window, true); } public void closeFile(@NotNull VirtualFile file, @NotNull EditorWindow window, boolean transferFocus) { assertDispatchThread(); ourOpenFilesSetModificationCount.incrementAndGet(); CommandProcessor.getInstance().executeCommand(myProject, () -> { if (window.isFileOpen(file)) { window.closeFile(file, true, transferFocus); } }, IdeBundle.message("command.close.active.editor"), null); removeSelectionRecord(file, window); } @Override public void closeFile(@NotNull VirtualFile file, @NotNull EditorWindow window) { closeFile(file, window, true); } //============================= EditorManager methods ================================ @Override public void closeFile(@NotNull VirtualFile file) { closeFile(file, true, false); } public void closeFile(@NotNull VirtualFile file, boolean moveFocus, boolean closeAllCopies) { assertDispatchThread(); CommandProcessor.getInstance().executeCommand(myProject, () -> { ourOpenFilesSetModificationCount.incrementAndGet(); runChange(splitters -> splitters.closeFile(file, moveFocus), closeAllCopies ? null : getActiveSplittersSync()); }, "", null); } //-------------------------------------- Open File ---------------------------------------- @Override public @NotNull Pair<FileEditor[], FileEditorProvider[]> openFileWithProviders(@NotNull VirtualFile file, boolean focusEditor, boolean searchForSplitter) { if (!file.isValid()) { throw new IllegalArgumentException("file is not valid: " + file); } assertDispatchThread(); OpenMode mode = getOpenMode(IdeEventQueue.getInstance().getTrueCurrentEvent()); if (mode == OpenMode.NEW_WINDOW) { return openFileInNewWindow(file); } if (mode == OpenMode.RIGHT_SPLIT) { Pair<FileEditor[], FileEditorProvider[]> pair = openInRightSplit(file); if (pair != null) return pair; } EditorWindow wndToOpenIn = null; if (searchForSplitter && UISettings.getInstance().getEditorTabPlacement() != UISettings.TABS_NONE) { Set<EditorsSplitters> all = getAllSplitters(); EditorsSplitters active = getActiveSplittersSync(); if (active.getCurrentWindow() != null && active.getCurrentWindow().isFileOpen(file)) { wndToOpenIn = active.getCurrentWindow(); } else { for (EditorsSplitters splitters : all) { EditorWindow window = splitters.getCurrentWindow(); if (window == null) continue; if (window.isFileOpen(file)) { wndToOpenIn = window; break; } } } } FileEditor selectedEditor = getSelectedEditor(); EditorsSplitters splitters; if (FileEditorManager.USE_MAIN_WINDOW.isIn(selectedEditor)) { boolean useCurrentWindow = selectedEditor != null && !FileEditorManager.USE_MAIN_WINDOW.get(selectedEditor, false); splitters = useCurrentWindow ? getSplitters() : getMainSplitters(); } else { splitters = UISettings.getInstance().getOpenTabsInMainWindow() ? getMainSplitters() : getSplitters(); } if (wndToOpenIn == null) { EditorWindow currentWindow = splitters.getCurrentWindow(); wndToOpenIn = currentWindow != null && UISettings.getInstance().getEditorTabPlacement() == UISettings.TABS_NONE ? currentWindow : splitters.getOrCreateCurrentWindow(file); } openAssociatedFile(file, wndToOpenIn, splitters); return openFileImpl2(wndToOpenIn, file, focusEditor); } public Pair<FileEditor[], FileEditorProvider[]> openFileInNewWindow(@NotNull VirtualFile file) { if (forbidSplitFor(file)) { closeFile(file); } return ((DockManagerImpl)DockManager.getInstance(getProject())).createNewDockContainerFor(file, this); } @Nullable private Pair<FileEditor[], FileEditorProvider[]> openInRightSplit(@NotNull VirtualFile file) { EditorsSplitters active = getSplitters(); EditorWindow window = active.getCurrentWindow(); if (window != null) { if (window.inSplitter() && file.equals(window.getSelectedFile()) && file.equals(ArrayUtil.getLastElement(window.getFiles()))) { //already in right splitter return null; } EditorWindow split = active.openInRightSplit(file); if (split != null) { Ref<Pair<FileEditor[], FileEditorProvider[]>> ref = Ref.create(); CommandProcessor.getInstance().executeCommand(myProject, () -> { EditorWithProviderComposite[] editorsWithProvider = split.getEditors(); FileEditor[] editors = Arrays.stream(editorsWithProvider) .map(el -> el.getEditors()) .flatMap(el -> Arrays.stream(el)) .toArray(FileEditor[]::new); FileEditorProvider[] providers = Arrays.stream(editorsWithProvider) .map(el -> el.getProviders()) .flatMap(el -> Arrays.stream(el)) .toArray(FileEditorProvider[]::new); ref.set(Pair.create(editors, providers)); }, "", null); return ref.get(); } } return null; } @NotNull public static OpenMode getOpenMode(@NotNull AWTEvent event) { if (event instanceof MouseEvent) { boolean isMouseClick = event.getID() == MouseEvent.MOUSE_CLICKED || event.getID() == MouseEvent.MOUSE_PRESSED || event.getID() == MouseEvent.MOUSE_RELEASED; int modifiers = ((MouseEvent)event).getModifiersEx(); if (modifiers == InputEvent.SHIFT_DOWN_MASK && isMouseClick) { return OpenMode.NEW_WINDOW; } } if (event instanceof KeyEvent) { KeyEvent ke = (KeyEvent)event; KeymapManager keymapManager = KeymapManager.getInstance(); if (keymapManager != null) { Keymap keymap = keymapManager.getActiveKeymap(); String[] ids = keymap.getActionIds(KeyStroke.getKeyStroke(ke.getKeyCode(), ke.getModifiers())); List<String> strings = Arrays.asList(ids); if (strings.contains(ACTION_OPEN_IN_NEW_WINDOW)) return OpenMode.NEW_WINDOW; if (strings.contains(ACTION_OPEN_IN_RIGHT_SPLIT)) return OpenMode.RIGHT_SPLIT; } } return OpenMode.DEFAULT; } private void openAssociatedFile(VirtualFile file, EditorWindow wndToOpenIn, @NotNull EditorsSplitters splitters) { EditorWindow[] windows = splitters.getWindows(); if (file != null && windows.length == 2) { for (FileEditorAssociateFinder finder : FileEditorAssociateFinder.EP_NAME.getExtensionList()) { VirtualFile associatedFile = finder.getAssociatedFileToOpen(myProject, file); if (associatedFile != null) { EditorWindow currentWindow = splitters.getCurrentWindow(); int idx = windows[0] == wndToOpenIn ? 1 : 0; openFileImpl2(windows[idx], associatedFile, false); if (currentWindow != null) { splitters.setCurrentWindow(currentWindow, false); } break; } } } } public static boolean forbidSplitFor(@NotNull VirtualFile file) { return Boolean.TRUE.equals(file.getUserData(SplitAction.FORBID_TAB_SPLIT)); } @Override public @NotNull Pair<FileEditor[], FileEditorProvider[]> openFileWithProviders(@NotNull VirtualFile file, boolean focusEditor, @NotNull EditorWindow window) { if (!file.isValid()) { throw new IllegalArgumentException("file is not valid: " + file); } assertDispatchThread(); return openFileImpl2(window, file, focusEditor); } public @NotNull Pair<FileEditor[], FileEditorProvider[]> openFileImpl2(@NotNull EditorWindow window, @NotNull VirtualFile file, boolean focusEditor) { Ref<Pair<FileEditor[], FileEditorProvider[]>> result = new Ref<>(); CommandProcessor.getInstance().executeCommand(myProject, () -> result.set(openFileImpl3(window, file, focusEditor, null)), "", null); return result.get(); } /** * @param file to be opened. Unlike openFile method, file can be * invalid. For example, all file were invalidate and they are being * removed one by one. If we have removed one invalid file, then another * invalid file become selected. That's why we do not require that * passed file is valid. * @param entry map between FileEditorProvider and FileEditorState. If this parameter */ @NotNull Pair<FileEditor[], FileEditorProvider[]> openFileImpl3(@NotNull EditorWindow window, @NotNull VirtualFile file, boolean focusEditor, @Nullable HistoryEntry entry) { if (file instanceof BackedVirtualFile) { file = ((BackedVirtualFile)file).getOriginFile(); } return openFileImpl4(window, file, entry, new FileEditorOpenOptions().withCurrentTab(true).withFocusEditor(focusEditor)); } /** * This method can be invoked from background thread. Of course, UI for returned editors should be accessed from EDT in any case. */ protected @NotNull Pair<FileEditor @NotNull [], FileEditorProvider @NotNull []> openFileImpl4(@NotNull EditorWindow window, @NotNull VirtualFile file, @Nullable HistoryEntry entry, @NotNull FileEditorOpenOptions options) { assert ApplicationManager.getApplication().isDispatchThread() || !ApplicationManager.getApplication().isReadAccessAllowed() : "must not open files under read action since we are doing a lot of invokeAndWaits here"; Ref<EditorWithProviderComposite> compositeRef = new Ref<>(); if (!options.isReopeningEditorsOnStartup()) { EdtInvocationManager.invokeAndWaitIfNeeded(() -> compositeRef.set(window.findFileComposite(file))); } FileEditorProvider[] newProviders; AsyncFileEditorProvider.Builder[] builders; if (compositeRef.isNull()) { // File is not opened yet. In this case we have to create editors // and select the created EditorComposite. newProviders = FileEditorProviderManager.getInstance().getProviders(myProject, file); if (newProviders.length == 0) { return Pair.createNonNull(FileEditor.EMPTY_ARRAY, EMPTY_PROVIDER_ARRAY); } builders = new AsyncFileEditorProvider.Builder[newProviders.length]; for (int i = 0; i < newProviders.length; i++) { try { FileEditorProvider provider = newProviders[i]; LOG.assertTrue(provider != null, "Provider for file "+file+" is null. All providers: "+Arrays.asList(newProviders)); builders[i] = ReadAction.compute(() -> { if (myProject.isDisposed() || !file.isValid()) { return null; } LOG.assertTrue(provider.accept(myProject, file), "Provider " + provider + " doesn't accept file " + file); return provider instanceof AsyncFileEditorProvider ? ((AsyncFileEditorProvider)provider).createEditorAsync(myProject, file) : null; }); } catch (ProcessCanceledException e) { throw e; } catch (Exception | AssertionError e) { LOG.error(e); } } } else { newProviders = null; builders = null; } ApplicationManager.getApplication().invokeAndWait(() -> runBulkTabChange(window.getOwner(), splitters -> openFileImpl4Edt(window, file, entry, options, compositeRef, newProviders, builders))); EditorWithProviderComposite composite = compositeRef.get(); return new Pair<>(composite == null ? FileEditor.EMPTY_ARRAY : composite.getEditors(), composite == null ? EMPTY_PROVIDER_ARRAY : composite.getProviders()); } private void openFileImpl4Edt(@NotNull EditorWindow window, @NotNull VirtualFile file, @Nullable HistoryEntry entry, @NotNull FileEditorOpenOptions options, @NotNull Ref<EditorWithProviderComposite> compositeRef, FileEditorProvider [] newProviders, AsyncFileEditorProvider.Builder [] builders) { if (myProject.isDisposed() || !file.isValid()) { return; } ((TransactionGuardImpl)TransactionGuard.getInstance()).assertWriteActionAllowed(); compositeRef.set(window.findFileComposite(file)); boolean newEditor = compositeRef.isNull(); if (newEditor) { getProject().getMessageBus().syncPublisher(FileEditorManagerListener.Before.FILE_EDITOR_MANAGER).beforeFileOpened(this, file); FileEditor[] newEditors = new FileEditor[newProviders.length]; for (int i = 0; i < newProviders.length; i++) { try { FileEditorProvider provider = newProviders[i]; FileEditor editor = builders[i] == null ? provider.createEditor(myProject, file) : builders[i].build(); LOG.assertTrue(editor.isValid(), "Invalid editor created by provider " + (provider == null ? null : provider.getClass().getName())); newEditors[i] = editor; // Register PropertyChangeListener into editor editor.addPropertyChangeListener(myEditorPropertyChangeListener); editor.putUserData(DUMB_AWARE, DumbService.isDumbAware(provider)); } catch (ProcessCanceledException e) { throw e; } catch (Exception | AssertionError e) { LOG.error(e); } } // Now we have to create EditorComposite and insert it into the TabbedEditorComponent. // After that we have to select opened editor. EditorWithProviderComposite composite = createComposite(file, newEditors, newProviders); if (composite == null) return; if (options.getIndex() >= 0) { composite.getFile().putUserData(EditorWindow.INITIAL_INDEX_KEY, options.getIndex()); } compositeRef.set(composite); myOpenedEditors.add(composite); } EditorWithProviderComposite composite = compositeRef.get(); FileEditor[] editors = composite.getEditors(); FileEditorProvider[] providers = composite.getProviders(); window.setEditor(composite, options.isCurrentTab(), options.isFocusEditor()); for (int i = 0; i < editors.length; i++) { restoreEditorState(file, providers[i], editors[i], entry, newEditor, options.isExactState()); } // Restore selected editor FileEditorProvider selectedProvider; if (entry == null) { selectedProvider = ((FileEditorProviderManagerImpl)FileEditorProviderManager.getInstance()) .getSelectedFileEditorProvider(EditorHistoryManager.getInstance(myProject), file, providers); } else { selectedProvider = entry.getSelectedProvider(); } if (selectedProvider != null) { for (int i = editors.length - 1; i >= 0; i--) { FileEditorProvider provider = providers[i]; if (provider.equals(selectedProvider)) { composite.setSelectedEditor(i); break; } } } // Notify editors about selection changes window.getOwner().setCurrentWindow(window, options.isFocusEditor()); window.getOwner().afterFileOpen(file); addSelectionRecord(file, window); composite.getSelectedEditor().selectNotify(); // transfer focus into editor if (!ApplicationManager.getApplication().isUnitTestMode() && options.isFocusEditor()) { //myFirstIsActive = myTabbedContainer1.equals(tabbedContainer); window.setAsCurrentWindow(true); Window windowAncestor = SwingUtilities.getWindowAncestor(window.myPanel); if (windowAncestor != null && windowAncestor.equals(KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow())) { JComponent component = composite.getPreferredFocusedComponent(); if (component != null) { component.requestFocus(); } IdeFocusManager.getInstance(myProject).toFront(window.getOwner()); } } if (newEditor) { ourOpenFilesSetModificationCount.incrementAndGet(); } //[jeka] this is a hack to support back-forward navigation // previously here was incorrect call to fireSelectionChanged() with a side-effect ((IdeDocumentHistoryImpl)IdeDocumentHistory.getInstance(myProject)).onSelectionChanged(); // Update frame and tab title updateFileName(file); // Make back/forward work IdeDocumentHistory.getInstance(myProject).includeCurrentCommandAsNavigation(); if (options.getPin() != null) { window.setFilePinned(file, options.getPin()); } if (newEditor) { getProject().getMessageBus().syncPublisher(FileEditorManagerListener.FILE_EDITOR_MANAGER) .fileOpenedSync(this, file, Pair.pair(editors, providers)); notifyPublisher(() -> { if (isFileOpen(file)) { getProject().getMessageBus().syncPublisher(FileEditorManagerListener.FILE_EDITOR_MANAGER) .fileOpened(this, file); } }); } } protected final @Nullable EditorWithProviderComposite createComposite(@NotNull VirtualFile file, FileEditor @NotNull [] editors, FileEditorProvider @NotNull [] providers) { if (ArrayUtil.contains(null, editors) || ArrayUtil.contains(null, providers)) { List<FileEditor> editorList = new ArrayList<>(editors.length); List<FileEditorProvider> providerList = new ArrayList<>(providers.length); for (int i = 0; i < editors.length; i++) { FileEditor editor = editors[i]; FileEditorProvider provider = providers[i]; if (editor != null && provider != null) { editorList.add(editor); providerList.add(provider); } } if (editorList.isEmpty()) return null; editors = editorList.toArray(FileEditor.EMPTY_ARRAY); providers = providerList.toArray(new FileEditorProvider[0]); } return new EditorWithProviderComposite(file, editors, providers, this); } private void restoreEditorState(@NotNull VirtualFile file, @NotNull FileEditorProvider provider, @NotNull FileEditor editor, HistoryEntry entry, boolean newEditor, boolean exactState) { FileEditorState state = null; if (entry != null) { state = entry.getState(provider); } if (state == null && newEditor) { // We have to try to get state from the history only in case // if editor is not opened. Otherwise history entry might have a state // out of sync with the current editor state. state = EditorHistoryManager.getInstance(myProject).getState(file, provider); } if (state != null) { if (!isDumbAware(editor)) { FileEditorState finalState = state; DumbService.getInstance(getProject()).runWhenSmart(() -> editor.setState(finalState, exactState)); } else { editor.setState(state, exactState); } } } @Override public @NotNull ActionCallback notifyPublisher(@NotNull Runnable runnable) { IdeFocusManager focusManager = IdeFocusManager.getInstance(myProject); ActionCallback done = new ActionCallback(); return myBusyObject.execute(new ActiveRunnable() { @Override public @NotNull ActionCallback run() { focusManager.doWhenFocusSettlesDown(ExpirableRunnable.forProject(myProject, () -> { runnable.run(); done.setDone(); }), ModalityState.current()); return done; } }); } @Override public void setSelectedEditor(@NotNull VirtualFile file, @NotNull String fileEditorProviderId) { ApplicationManager.getApplication().assertIsDispatchThread(); EditorWithProviderComposite composite = getCurrentEditorWithProviderComposite(file); if (composite == null) { List<EditorWithProviderComposite> composites = getEditorComposites(file); if (composites.isEmpty()) return; composite = composites.get(0); } FileEditorProvider[] editorProviders = composite.getProviders(); FileEditorProvider selectedProvider = composite.getSelectedWithProvider().getProvider(); for (int i = 0; i < editorProviders.length; i++) { if (editorProviders[i].getEditorTypeId().equals(fileEditorProviderId) && !selectedProvider.equals(editorProviders[i])) { composite.setSelectedEditor(i); composite.getSelectedEditor().selectNotify(); } } } @Nullable EditorWithProviderComposite newEditorComposite(@NotNull VirtualFile file) { FileEditorProviderManager editorProviderManager = FileEditorProviderManager.getInstance(); FileEditorProvider[] providers = editorProviderManager.getProviders(myProject, file); if (providers.length == 0) return null; FileEditor[] editors = new FileEditor[providers.length]; for (int i = 0; i < providers.length; i++) { FileEditorProvider provider = providers[i]; LOG.assertTrue(provider != null); LOG.assertTrue(provider.accept(myProject, file)); FileEditor editor = provider.createEditor(myProject, file); editors[i] = editor; LOG.assertTrue(editor.isValid()); editor.addPropertyChangeListener(myEditorPropertyChangeListener); } EditorWithProviderComposite newComposite = new EditorWithProviderComposite(file, editors, providers, this); EditorHistoryManager editorHistoryManager = EditorHistoryManager.getInstance(myProject); for (int i = 0; i < editors.length; i++) { FileEditor editor = editors[i]; FileEditorProvider provider = providers[i]; // Restore myEditor state FileEditorState state = editorHistoryManager.getState(file, provider); if (state != null) { editor.setState(state); } } return newComposite; } @Override public @NotNull List<FileEditor> openFileEditor(@NotNull FileEditorNavigatable descriptor, boolean focusEditor) { return openEditorImpl(descriptor, focusEditor).first; } /** * @return the list of opened editors, and the one of them that was selected (if any) */ private Pair<List<FileEditor>, FileEditor> openEditorImpl(@NotNull FileEditorNavigatable descriptor, boolean focusEditor) { assertDispatchThread(); FileEditorNavigatable realDescriptor; if (descriptor instanceof OpenFileDescriptor && descriptor.getFile() instanceof VirtualFileWindow) { OpenFileDescriptor openFileDescriptor = (OpenFileDescriptor)descriptor; VirtualFileWindow delegate = (VirtualFileWindow)descriptor.getFile(); int hostOffset = delegate.getDocumentWindow().injectedToHost(openFileDescriptor.getOffset()); OpenFileDescriptor fixedDescriptor = new OpenFileDescriptor(openFileDescriptor.getProject(), delegate.getDelegate(), hostOffset); fixedDescriptor.setUseCurrentWindow(openFileDescriptor.isUseCurrentWindow()); realDescriptor = fixedDescriptor; } else { realDescriptor = descriptor; } List<FileEditor> result = new SmartList<>(); Ref<FileEditor> selectedEditor = new Ref<>(); CommandProcessor.getInstance().executeCommand(myProject, () -> { VirtualFile file = realDescriptor.getFile(); FileEditor[] editors = openFile(file, focusEditor, !realDescriptor.isUseCurrentWindow()); ContainerUtil.addAll(result, editors); boolean navigated = false; for (FileEditor editor : editors) { if (editor instanceof NavigatableFileEditor && getSelectedEditor(realDescriptor.getFile()) == editor) { // try to navigate opened editor navigated = navigateAndSelectEditor((NavigatableFileEditor)editor, realDescriptor); if (navigated) { selectedEditor.set(editor); break; } } } if (!navigated) { for (FileEditor editor : editors) { if (editor instanceof NavigatableFileEditor && getSelectedEditor(realDescriptor.getFile()) != editor) { // try other editors if (navigateAndSelectEditor((NavigatableFileEditor)editor, realDescriptor)) { selectedEditor.set(editor); break; } } } } }, "", null); return Pair.create(result, selectedEditor.get()); } private boolean navigateAndSelectEditor(@NotNull NavigatableFileEditor editor, @NotNull Navigatable descriptor) { if (editor.canNavigateTo(descriptor)) { setSelectedEditor(editor); editor.navigateTo(descriptor); return true; } return false; } private void setSelectedEditor(@NotNull FileEditor editor) { EditorWithProviderComposite composite = getEditorComposite(editor); if (composite == null) return; FileEditor[] editors = composite.getEditors(); for (int i = 0; i < editors.length; i++) { FileEditor each = editors[i]; if (editor == each) { composite.setSelectedEditor(i); composite.getSelectedEditor().selectNotify(); break; } } } @Override public @NotNull Project getProject() { return myProject; } @Override public @Nullable Editor openTextEditor(@NotNull OpenFileDescriptor descriptor, boolean focusEditor) { TextEditor textEditor = doOpenTextEditor(descriptor, focusEditor); return textEditor == null ? null : textEditor.getEditor(); } private @Nullable TextEditor doOpenTextEditor(@NotNull FileEditorNavigatable descriptor, boolean focusEditor) { Pair<List<FileEditor>, FileEditor> editorsWithSelected = openEditorImpl(descriptor, focusEditor); Collection<FileEditor> fileEditors = editorsWithSelected.first; FileEditor selectedEditor = editorsWithSelected.second; if (fileEditors.isEmpty()) return null; else if (fileEditors.size() == 1) return ObjectUtils.tryCast(ContainerUtil.getFirstItem(fileEditors), TextEditor.class); List<TextEditor> textEditors = ContainerUtil.mapNotNull(fileEditors, e -> ObjectUtils.tryCast(e, TextEditor.class)); if (textEditors.isEmpty()) return null; TextEditor target = selectedEditor instanceof TextEditor ? (TextEditor)selectedEditor : textEditors.get(0); if (textEditors.size() > 1) { EditorWithProviderComposite composite = getEditorComposite(target); assert composite != null; FileEditor[] editors = composite.getEditors(); FileEditorProvider[] providers = composite.getProviders(); String textProviderId = TextEditorProvider.getInstance().getEditorTypeId(); for (int i = 0; i < editors.length; i++) { FileEditor editor = editors[i]; if (editor instanceof TextEditor && providers[i].getEditorTypeId().equals(textProviderId)) { target = (TextEditor)editor; break; } } } setSelectedEditor(target); return target; } @Override public Editor getSelectedTextEditor() { return getSelectedTextEditor(false); } public Editor getSelectedTextEditor(boolean lockfree) { if (!lockfree) { assertDispatchThread(); } EditorWindow currentWindow = lockfree ? getMainSplitters().getCurrentWindow() : getSplitters().getCurrentWindow(); if (currentWindow != null) { EditorWithProviderComposite selectedEditor = currentWindow.getSelectedEditor(); if (selectedEditor != null && selectedEditor.getSelectedEditor() instanceof TextEditor) { return ((TextEditor)selectedEditor.getSelectedEditor()).getEditor(); } } return null; } @Override public boolean isFileOpen(@NotNull VirtualFile file) { for (EditorComposite editor : myOpenedEditors) { if (editor.getFile().equals(file)) { return true; } } return false; } @Override public VirtualFile @NotNull [] getOpenFiles() { Set<VirtualFile> files = new LinkedHashSet<>(); for (EditorComposite composite : myOpenedEditors) { files.add(composite.getFile()); } return VfsUtilCore.toVirtualFileArray(files); } @Override public boolean hasOpenFiles() { return !myOpenedEditors.isEmpty(); } @Override public VirtualFile @NotNull [] getSelectedFiles() { Set<VirtualFile> selectedFiles = new LinkedHashSet<>(); EditorsSplitters activeSplitters = getSplitters(); ContainerUtil.addAll(selectedFiles, activeSplitters.getSelectedFiles()); for (EditorsSplitters each : getAllSplitters()) { if (each != activeSplitters) { ContainerUtil.addAll(selectedFiles, each.getSelectedFiles()); } } return VfsUtilCore.toVirtualFileArray(selectedFiles); } @Override public FileEditor @NotNull [] getSelectedEditors() { Set<FileEditor> selectedEditors = new SmartHashSet<>(); for (EditorsSplitters splitters : getAllSplitters()) { splitters.addSelectedEditorsTo(selectedEditors); } return selectedEditors.toArray(FileEditor.EMPTY_ARRAY); } @Override public @NotNull EditorsSplitters getSplitters() { EditorsSplitters active = null; if (ApplicationManager.getApplication().isDispatchThread()) active = getActiveSplittersSync(); return active == null ? getMainSplitters() : active; } @Override public @Nullable FileEditor getSelectedEditor() { EditorWindow window = getSplitters().getCurrentWindow(); if (window != null) { EditorComposite selected = window.getSelectedEditor(); if (selected != null) return selected.getSelectedEditor(); } return super.getSelectedEditor(); } @Override public @Nullable FileEditor getSelectedEditor(@NotNull VirtualFile file) { FileEditorWithProvider editorWithProvider = getSelectedEditorWithProvider(file); return editorWithProvider == null ? null : editorWithProvider.getFileEditor(); } @Override public @Nullable FileEditorWithProvider getSelectedEditorWithProvider(@NotNull VirtualFile file) { ApplicationManager.getApplication().assertIsDispatchThread(); if (file instanceof VirtualFileWindow) file = ((VirtualFileWindow)file).getDelegate(); file = BackedVirtualFile.getOriginFileIfBacked(file); EditorWithProviderComposite composite = getCurrentEditorWithProviderComposite(file); if (composite != null) { return composite.getSelectedWithProvider(); } List<EditorWithProviderComposite> composites = getEditorComposites(file); return composites.isEmpty() ? null : composites.get(0).getSelectedWithProvider(); } @Override public @NotNull Pair<FileEditor[], FileEditorProvider[]> getEditorsWithProviders(@NotNull VirtualFile file) { ApplicationManager.getApplication().assertIsDispatchThread(); EditorWithProviderComposite composite = getCurrentEditorWithProviderComposite(file); if (composite != null) { return new Pair<>(composite.getEditors(), composite.getProviders()); } List<EditorWithProviderComposite> composites = getEditorComposites(file); if (!composites.isEmpty()) { return new Pair<>(composites.get(0).getEditors(), composites.get(0).getProviders()); } return new Pair<>(FileEditor.EMPTY_ARRAY, EMPTY_PROVIDER_ARRAY); } @Override public FileEditor @NotNull [] getEditors(@NotNull VirtualFile file) { ApplicationManager.getApplication().assertIsDispatchThread(); if (file instanceof VirtualFileWindow) { file = ((VirtualFileWindow)file).getDelegate(); } file = BackedVirtualFile.getOriginFileIfBacked(file); EditorWithProviderComposite composite = getCurrentEditorWithProviderComposite(file); if (composite != null) { return composite.getEditors(); } List<EditorWithProviderComposite> composites = getEditorComposites(file); if (!composites.isEmpty()) { return composites.get(0).getEditors(); } return FileEditor.EMPTY_ARRAY; } @Override public FileEditor @NotNull [] getAllEditors(@NotNull VirtualFile file) { List<FileEditor> result = new ArrayList<>(); myOpenedEditors.forEach(composite -> { if (composite.getFile().equals(file)) ContainerUtil.addAll(result, composite.myEditors); }); return result.toArray(FileEditor.EMPTY_ARRAY); } private @Nullable EditorWithProviderComposite getCurrentEditorWithProviderComposite(@NotNull VirtualFile virtualFile) { EditorWindow editorWindow = getSplitters().getCurrentWindow(); if (editorWindow != null) { return editorWindow.findFileComposite(virtualFile); } return null; } private @NotNull List<EditorWithProviderComposite> getEditorComposites(@NotNull VirtualFile file) { List<EditorWithProviderComposite> result = new ArrayList<>(); Set<EditorsSplitters> all = getAllSplitters(); for (EditorsSplitters each : all) { result.addAll(each.findEditorComposites(file)); } return result; } @Override public FileEditor @NotNull [] getAllEditors() { List<FileEditor> result = new ArrayList<>(); myOpenedEditors.forEach(composite -> ContainerUtil.addAll(result, composite.myEditors)); return result.toArray(FileEditor.EMPTY_ARRAY); } public @NotNull List<JComponent> getTopComponents(@NotNull FileEditor editor) { ApplicationManager.getApplication().assertIsDispatchThread(); EditorComposite composite = getEditorComposite(editor); return composite != null ? composite.getTopComponents(editor) : Collections.emptyList(); } @Override public void addTopComponent(@NotNull FileEditor editor, @NotNull JComponent component) { ApplicationManager.getApplication().assertIsDispatchThread(); EditorComposite composite = getEditorComposite(editor); if (composite != null) { composite.addTopComponent(editor, component); } } @Override public void removeTopComponent(@NotNull FileEditor editor, @NotNull JComponent component) { ApplicationManager.getApplication().assertIsDispatchThread(); EditorComposite composite = getEditorComposite(editor); if (composite != null) { composite.removeTopComponent(editor, component); } } @Override public void addBottomComponent(@NotNull FileEditor editor, @NotNull JComponent component) { ApplicationManager.getApplication().assertIsDispatchThread(); EditorComposite composite = getEditorComposite(editor); if (composite != null) { composite.addBottomComponent(editor, component); } } @Override public void removeBottomComponent(@NotNull FileEditor editor, @NotNull JComponent component) { ApplicationManager.getApplication().assertIsDispatchThread(); EditorComposite composite = getEditorComposite(editor); if (composite != null) { composite.removeBottomComponent(editor, component); } } @Override public void addFileEditorManagerListener(@NotNull FileEditorManagerListener listener) { myListenerList.add(listener); } @Override public void removeFileEditorManagerListener(@NotNull FileEditorManagerListener listener) { myListenerList.remove(listener); } protected void projectOpened(@NotNull MessageBusConnection connection) { //myFocusWatcher.install(myWindows.getComponent ()); getMainSplitters().startListeningFocus(); FileStatusManager fileStatusManager = FileStatusManager.getInstance(myProject); if (fileStatusManager != null) { // updates tabs colors fileStatusManager.addFileStatusListener(new MyFileStatusListener(), myProject); } connection.subscribe(FileTypeManager.TOPIC, new MyFileTypeListener()); connection.subscribe(ProjectTopics.PROJECT_ROOTS, new MyRootsListener()); // updates tabs names connection.subscribe(VirtualFileManager.VFS_CHANGES, new MyVirtualFileListener()); // extends/cuts number of opened tabs. Also updates location of tabs connection.subscribe(UISettingsListener.TOPIC, new MyUISettingsListener()); StartupManager.getInstance(myProject).runAfterOpened(() -> { if (myProject.isDisposed()) { return; } ApplicationManager.getApplication().invokeLater(() -> CommandProcessor.getInstance().executeCommand(myProject, () -> { ApplicationManager.getApplication().invokeLater(() -> { Long startTime = myProject.getUserData(ProjectImpl.CREATION_TIME); if (startTime != null) { long time = TimeoutUtil.getDurationMillis(startTime.longValue()); LifecycleUsageTriggerCollector.onProjectOpenFinished(myProject, time); LOG.info("Project opening took " + time + " ms"); } }, myProject.getDisposed()); // group 1 }, "", null), myProject.getDisposed()); }); } @Override public @Nullable Element getState() { if (mySplitters == null) { // do not save if not initialized yet return null; } Element state = new Element("state"); getMainSplitters().writeExternal(state); return state; } @Override public void loadState(@NotNull Element state) { getMainSplitters().readExternal(state); } protected @Nullable EditorWithProviderComposite getEditorComposite(@NotNull FileEditor editor) { for (EditorsSplitters splitters : getAllSplitters()) { List<EditorWithProviderComposite> editorsComposites = splitters.getEditorComposites(); for (int i = editorsComposites.size() - 1; i >= 0; i--) { EditorWithProviderComposite composite = editorsComposites.get(i); FileEditor[] editors = composite.getEditors(); for (int j = editors.length - 1; j >= 0; j--) { FileEditor _editor = editors[j]; LOG.assertTrue(_editor != null); if (editor.equals(_editor)) { return composite; } } } } return null; } private static void assertDispatchThread() { ApplicationManager.getApplication().assertIsDispatchThread(); } private static void assertReadAccess() { ApplicationManager.getApplication().assertReadAccessAllowed(); } public void fireSelectionChanged(@Nullable EditorComposite newSelectedComposite) { Trinity<VirtualFile, FileEditor, FileEditorProvider> oldData = extract(SoftReference.dereference(myLastSelectedComposite)); Trinity<VirtualFile, FileEditor, FileEditorProvider> newData = extract(newSelectedComposite); myLastSelectedComposite = newSelectedComposite == null ? null : new WeakReference<>(newSelectedComposite); boolean filesEqual = Objects.equals(oldData.first, newData.first); boolean editorsEqual = Objects.equals(oldData.second, newData.second); if (!filesEqual || !editorsEqual) { if (oldData.first != null && newData.first != null) { for (FileEditorAssociateFinder finder : FileEditorAssociateFinder.EP_NAME.getExtensionList()) { VirtualFile associatedFile = finder.getAssociatedFileToOpen(myProject, oldData.first); if (Comparing.equal(associatedFile, newData.first)) { return; } } } FileEditorManagerEvent event = new FileEditorManagerEvent(this, oldData.first, oldData.second, oldData.third, newData.first, newData.second, newData.third); FileEditorManagerListener publisher = getProject().getMessageBus().syncPublisher(FileEditorManagerListener.FILE_EDITOR_MANAGER); if (newData.first != null) { JComponent component = newData.second.getComponent(); EditorWindowHolder holder = ComponentUtil.getParentOfType((Class<? extends EditorWindowHolder>)EditorWindowHolder.class, (Component)component); if (holder != null) { addSelectionRecord(newData.first, holder.getEditorWindow()); } } notifyPublisher(() -> publisher.selectionChanged(event)); } } private static @NotNull Trinity<VirtualFile, FileEditor, FileEditorProvider> extract(@Nullable EditorComposite composite) { VirtualFile file; FileEditor editor; FileEditorProvider provider; if (composite == null) { file = null; editor = null; provider = null; } else { file = composite.getFile(); FileEditorWithProvider pair = composite.getSelectedWithProvider(); editor = pair.getFileEditor(); provider = pair.getProvider(); } return new Trinity<>(file, editor, provider); } @Override public boolean isChanged(@NotNull EditorComposite editor) { FileStatusManager fileStatusManager = FileStatusManager.getInstance(myProject); if (fileStatusManager == null) { return false; } FileStatus status = fileStatusManager.getStatus(editor.getFile()); return status != FileStatus.UNKNOWN && status != FileStatus.NOT_CHANGED; } void disposeComposite(@NotNull EditorWithProviderComposite editor) { myOpenedEditors.remove(editor); if (getAllEditors().length == 0) { setCurrentWindow(null); } if (editor.equals(getLastSelected())) { editor.getSelectedEditor().deselectNotify(); getSplitters().setCurrentWindow(null, false); } FileEditor[] editors = editor.getEditors(); FileEditorProvider[] providers = editor.getProviders(); FileEditor selectedEditor = editor.getSelectedEditor(); for (int i = editors.length - 1; i >= 0; i--) { FileEditor editor1 = editors[i]; FileEditorProvider provider = providers[i]; // we already notified the myEditor (when fire event) if (selectedEditor.equals(editor1)) { editor1.deselectNotify(); } editor1.removePropertyChangeListener(myEditorPropertyChangeListener); provider.disposeEditor(editor1); } Disposer.dispose(editor); } private @Nullable EditorComposite getLastSelected() { EditorWindow currentWindow = getActiveSplittersSync().getCurrentWindow(); if (currentWindow != null) { return currentWindow.getSelectedEditor(); } return null; } /** * @param splitters - taken getAllSplitters() value if parameter is null */ private void runChange(@NotNull FileEditorManagerChange change, @Nullable EditorsSplitters splitters) { Set<EditorsSplitters> target = new HashSet<>(); if (splitters == null) { target.addAll(getAllSplitters()); } else { target.add(splitters); } for (EditorsSplitters each : target) { runBulkTabChange(each, change); } } static void runBulkTabChange(@NotNull EditorsSplitters splitters, @NotNull FileEditorManagerChange change) { if (!ApplicationManager.getApplication().isDispatchThread()) { change.run(splitters); } else { splitters.myInsideChange++; try { change.run(splitters); } finally { splitters.myInsideChange--; if (!splitters.isInsideChange()) { splitters.validate(); for (EditorWindow window : splitters.getWindows()) { ((JBTabsImpl)window.getTabbedPane().getTabs()).revalidateAndRepaint(); } } } } } /** * Closes deleted files. Closes file which are in the deleted directories. */ private final class MyVirtualFileListener implements BulkFileListener { @Override public void before(@NotNull List<? extends VFileEvent> events) { for (VFileEvent event : events) { if (event instanceof VFileDeleteEvent) { beforeFileDeletion((VFileDeleteEvent)event); } } } @Override public void after(@NotNull List<? extends VFileEvent> events) { for (VFileEvent event : events) { if (event instanceof VFilePropertyChangeEvent) { propertyChanged((VFilePropertyChangeEvent)event); } else if (event instanceof VFileMoveEvent) { fileMoved((VFileMoveEvent)event); } } } private void beforeFileDeletion(@NotNull VFileDeleteEvent event) { assertDispatchThread(); VirtualFile file = event.getFile(); VirtualFile[] openFiles = getOpenFiles(); for (int i = openFiles.length - 1; i >= 0; i--) { if (VfsUtilCore.isAncestor(file, openFiles[i], false)) { closeFile(openFiles[i],true, true); } } } private void propertyChanged(@NotNull VFilePropertyChangeEvent event) { if (VirtualFile.PROP_NAME.equals(event.getPropertyName())) { assertDispatchThread(); VirtualFile file = event.getFile(); if (isFileOpen(file)) { updateFileName(file); updateFileIcon(file); // file type can change after renaming updateFileBackgroundColor(file); } } else if (VirtualFile.PROP_WRITABLE.equals(event.getPropertyName()) || VirtualFile.PROP_ENCODING.equals(event.getPropertyName())) { updateIcon(event); } } private void updateIcon(@NotNull VFilePropertyChangeEvent event) { assertDispatchThread(); VirtualFile file = event.getFile(); if (isFileOpen(file)) { updateFileIcon(file); } } private void fileMoved(@NotNull VFileMoveEvent e) { VirtualFile file = e.getFile(); for (VirtualFile openFile : getOpenFiles()) { if (VfsUtilCore.isAncestor(file, openFile, false)) { updateFileName(openFile); updateFileBackgroundColor(openFile); } } } } @Override public boolean isInsideChange() { return getSplitters().isInsideChange(); } private final class MyEditorPropertyChangeListener implements PropertyChangeListener { @Override public void propertyChange(@NotNull PropertyChangeEvent e) { assertDispatchThread(); String propertyName = e.getPropertyName(); if (FileEditor.PROP_MODIFIED.equals(propertyName)) { FileEditor editor = (FileEditor)e.getSource(); EditorComposite composite = getEditorComposite(editor); if (composite != null) { updateFileIcon(composite.getFile()); } } else if (FileEditor.PROP_VALID.equals(propertyName)) { boolean valid = ((Boolean)e.getNewValue()).booleanValue(); if (!valid) { FileEditor editor = (FileEditor)e.getSource(); LOG.assertTrue(editor != null); EditorComposite composite = getEditorComposite(editor); if (composite != null) { closeFile(composite.getFile()); } } } } } /** * Gets events from VCS and updates color of myEditor tabs */ private final class MyFileStatusListener implements FileStatusListener { @Override public void fileStatusesChanged() { // update color of all open files assertDispatchThread(); LOG.debug("FileEditorManagerImpl.MyFileStatusListener.fileStatusesChanged()"); VirtualFile[] openFiles = getOpenFiles(); for (int i = openFiles.length - 1; i >= 0; i--) { VirtualFile file = openFiles[i]; LOG.assertTrue(file != null); ApplicationManager.getApplication().invokeLater(() -> { if (LOG.isDebugEnabled()) { LOG.debug("updating file status in tab for " + file.getPath()); } updateFileStatus(file); }, ModalityState.NON_MODAL, myProject.getDisposed()); } } @Override public void fileStatusChanged(@NotNull VirtualFile file) { // update color of the file (if necessary) assertDispatchThread(); if (isFileOpen(file)) { updateFileStatus(file); } } private void updateFileStatus(VirtualFile file) { updateFileColor(file); updateFileIcon(file); } } /** * Gets events from FileTypeManager and updates icons on tabs */ private final class MyFileTypeListener implements FileTypeListener { @Override public void fileTypesChanged(@NotNull FileTypeEvent event) { assertDispatchThread(); VirtualFile[] openFiles = getOpenFiles(); for (int i = openFiles.length - 1; i >= 0; i--) { VirtualFile file = openFiles[i]; LOG.assertTrue(file != null); updateFileIcon(file, true); } } } private class MyRootsListener implements ModuleRootListener { @Override public void rootsChanged(@NotNull ModuleRootEvent event) { AppUIExecutor .onUiThread(ModalityState.any()) .expireWith(myProject) .submit(() -> StreamEx.of(getWindows()).flatArray(EditorWindow::getEditors).toList()) .onSuccess(allEditors -> ReadAction .nonBlocking(() -> calcEditorReplacements(allEditors)) .inSmartMode(myProject) .finishOnUiThread(ModalityState.defaultModalityState(), this::replaceEditors) .coalesceBy(this) .submit(AppExecutorUtil.getAppExecutorService())); } private Map<EditorWithProviderComposite, Pair<VirtualFile, Integer>> calcEditorReplacements(List<EditorWithProviderComposite> allEditors) { List<EditorFileSwapper> swappers = EditorFileSwapper.EP_NAME.getExtensionList(); return StreamEx.of(allEditors).mapToEntry(editor -> { if (editor.getFile().isValid()) { for (EditorFileSwapper each : swappers) { Pair<VirtualFile, Integer> fileAndOffset = each.getFileToSwapTo(myProject, editor); if (fileAndOffset != null) return fileAndOffset; } } return null; }).nonNullValues().toMap(); } private void replaceEditors(Map<EditorWithProviderComposite, Pair<VirtualFile, Integer>> replacements) { if (replacements.isEmpty()) return; for (EditorWindow eachWindow : getWindows()) { EditorWithProviderComposite selected = eachWindow.getSelectedEditor(); EditorWithProviderComposite[] editors = eachWindow.getEditors(); for (int i = 0; i < editors.length; i++) { EditorWithProviderComposite editor = editors[i]; VirtualFile file = editor.getFile(); if (!file.isValid()) continue; Pair<VirtualFile, Integer> newFilePair = replacements.get(editor); if (newFilePair == null) continue; VirtualFile newFile = newFilePair.first; if (newFile == null) continue; // already open if (eachWindow.findFileIndex(newFile) != -1) continue; try { newFile.putUserData(EditorWindow.INITIAL_INDEX_KEY, i); Pair<FileEditor[], FileEditorProvider[]> pair = openFileImpl2(eachWindow, newFile, editor == selected); if (newFilePair.second != null) { TextEditorImpl openedEditor = EditorFileSwapper.findSinglePsiAwareEditor(pair.first); if (openedEditor != null) { openedEditor.getEditor().getCaretModel().moveToOffset(newFilePair.second); openedEditor.getEditor().getScrollingModel().scrollToCaret(ScrollType.CENTER); } } } finally { newFile.putUserData(EditorWindow.INITIAL_INDEX_KEY, null); } closeFile(file, eachWindow); } } } } /** * Gets notifications from UISetting component to track changes of RECENT_FILES_LIMIT * and EDITOR_TAB_LIMIT, etc values. */ private final class MyUISettingsListener implements UISettingsListener { @Override public void uiSettingsChanged(@NotNull UISettings uiSettings) { assertDispatchThread(); mySplitters.revalidate(); for (EditorsSplitters each : getAllSplitters()) { each.setTabsPlacement(uiSettings.getEditorTabPlacement()); each.trimToSize(); if (JBTabsImpl.NEW_TABS) { TabsLayoutInfo tabsLayoutInfo = TabsLayoutSettingsManager.getInstance().getSelectedTabsLayoutInfo(); each.updateTabsLayout(tabsLayoutInfo); } else { // Tab layout policy if (uiSettings.getScrollTabLayoutInEditor()) { each.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); } else { each.setTabLayoutPolicy(JTabbedPane.WRAP_TAB_LAYOUT); } } } // "Mark modified files with asterisk" VirtualFile[] openFiles = getOpenFiles(); for (int i = openFiles.length - 1; i >= 0; i--) { VirtualFile file = openFiles[i]; updateFileIcon(file); updateFileName(file); updateFileBackgroundColor(file); } // "Show full paths in window header" updateFrameTitle(); } } @Override public void closeAllFiles() { runBulkTabChange(getSplitters(), splitters -> { for (VirtualFile openFile : splitters.getOpenFileList()) { closeFile(openFile); } }); } @Override public VirtualFile @NotNull [] getSiblings(@NotNull VirtualFile file) { return getOpenFiles(); } void queueUpdateFile(@NotNull VirtualFile file) { myQueue.queue(new Update(file) { @Override public void run() { if (isFileOpen(file)) { updateFileIcon(file); updateFileColor(file); updateFileBackgroundColor(file); resetPreviewFlag(file); } } }); } @Override public EditorsSplitters getSplittersFor(Component c) { EditorsSplitters splitters = null; DockContainer dockContainer = myDockManager.getContainerFor(c); if (dockContainer instanceof DockableEditorTabbedContainer) { splitters = ((DockableEditorTabbedContainer)dockContainer).getSplitters(); } if (splitters == null) { splitters = getMainSplitters(); } return splitters; } public @NotNull List<Pair<VirtualFile, EditorWindow>> getSelectionHistory() { List<Pair<VirtualFile, EditorWindow>> copy = new ArrayList<>(); for (Pair<VirtualFile, EditorWindow> pair : mySelectionHistory) { if (pair.second.getFiles().length == 0) { EditorWindow[] windows = pair.second.getOwner().getWindows(); if (windows.length > 0 && windows[0] != null && windows[0].getFiles().length > 0) { Pair<VirtualFile, EditorWindow> p = Pair.create(pair.first, windows[0]); if (!copy.contains(p)) { copy.add(p); } } } else { if (!copy.contains(pair)) { copy.add(pair); } } } mySelectionHistory.clear(); mySelectionHistory.addAll(copy); return mySelectionHistory; } public void addSelectionRecord(@NotNull VirtualFile file, @NotNull EditorWindow window) { Pair<VirtualFile, EditorWindow> record = Pair.create(file, window); mySelectionHistory.remove(record); mySelectionHistory.add(0, record); } void removeSelectionRecord(@NotNull VirtualFile file, @NotNull EditorWindow window) { mySelectionHistory.remove(Pair.create(file, window)); updateFileName(file); } @Override public @NotNull ActionCallback getReady(@NotNull Object requestor) { return myBusyObject.getReady(requestor); } }
IDEA-239838 Duplicated file opened in split mode when we are paused on a breakpoint in debug mode (Tabs are disabled) GitOrigin-RevId: c4f9462b2e44be85deff11eb9f425929e346bba3
platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileEditorManagerImpl.java
IDEA-239838 Duplicated file opened in split mode when we are paused on a breakpoint in debug mode (Tabs are disabled)
Java
apache-2.0
4d3e43fa061be9f08f7cbcd90dbf38c5d32c5746
0
arthurdm/microprofile-open-api
/** * Copyright (c) 2017 Contributors to the Eclipse Foundation * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations * under the License. */ package org.eclipse.microprofile.openapi.apps.petstore.resource; import org.eclipse.microprofile.openapi.annotations.Operation; import org.eclipse.microprofile.openapi.annotations.ExternalDocumentation; import org.eclipse.microprofile.openapi.annotations.parameters.Parameter; import org.eclipse.microprofile.openapi.annotations.enums.SecuritySchemeIn; import org.eclipse.microprofile.openapi.annotations.enums.SecuritySchemeType; import org.eclipse.microprofile.openapi.annotations.enums.SchemaType; import org.eclipse.microprofile.openapi.annotations.security.SecurityScheme; import org.eclipse.microprofile.openapi.annotations.security.SecuritySchemes; import org.eclipse.microprofile.openapi.annotations.security.SecurityRequirement; import org.eclipse.microprofile.openapi.annotations.security.OAuthFlow; import org.eclipse.microprofile.openapi.annotations.security.OAuthFlows; import org.eclipse.microprofile.openapi.annotations.callbacks.Callback; import org.eclipse.microprofile.openapi.annotations.extensions.Extension; import org.eclipse.microprofile.openapi.annotations.extensions.Extensions; import org.eclipse.microprofile.openapi.annotations.media.Content; import org.eclipse.microprofile.openapi.annotations.media.Schema; import org.eclipse.microprofile.openapi.annotations.parameters.RequestBody; import org.eclipse.microprofile.openapi.annotations.media.ExampleObject; import org.eclipse.microprofile.openapi.annotations.responses.APIResponse; import org.eclipse.microprofile.openapi.annotations.responses.APIResponses; import org.eclipse.microprofile.openapi.annotations.callbacks.CallbackOperation; import org.eclipse.microprofile.openapi.apps.petstore.data.PetData; import org.eclipse.microprofile.openapi.apps.petstore.model.Pet; import org.eclipse.microprofile.openapi.apps.petstore.model.ApiResponse; import org.eclipse.microprofile.openapi.apps.petstore.model.Cat; import org.eclipse.microprofile.openapi.apps.petstore.model.Dog; import org.eclipse.microprofile.openapi.apps.petstore.model.Lizard; import org.eclipse.microprofile.openapi.apps.petstore.exception.NotFoundException; import java.io.*; import javax.ws.rs.core.Response; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.StreamingOutput; import javax.ws.rs.GET; import javax.ws.rs.DELETE; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.HeaderParam; import javax.ws.rs.QueryParam; import javax.ws.rs.FormParam; import javax.ws.rs.Produces; import javax.ws.rs.Consumes; @Path("/pet") @Schema( name = "pet", description = "Operations on pets resource") @SecuritySchemes( value = { @SecurityScheme( securitySchemeName = "petsApiKey", type = SecuritySchemeType.APIKEY, description = "authentication needed to create a new pet profile for the store", apiKeyName = "createPetProfile", in = SecuritySchemeIn.HEADER ), @SecurityScheme( securitySchemeName = "petsOAuth2", type = SecuritySchemeType.OAUTH2, description = "authentication needed to delete a pet profile", flows = @OAuthFlows( implicit = @OAuthFlow( authorizationUrl = "https://example.com/api/oauth/dialog" ), authorizationCode = @OAuthFlow( authorizationUrl = "https://example.com/api/oauth/dialog", tokenUrl = "https://example.com/api/oauth/token" ) ) ), @SecurityScheme( securitySchemeName = "petsHttp", type = SecuritySchemeType.HTTP, description = "authentication needed to update an exsiting record of a pet in the store", scheme = "bearer", bearerFormat = "jwt" ) } ) public class PetResource { static PetData petData = new PetData(); @GET @Path("/{petId}") @APIResponses(value={ @APIResponse( responseCode = "400", description = "Invalid ID supplied", content = @Content( mediaType = "none") ), @APIResponse( responseCode = "404", description = "Pet not found", content = @Content( mediaType = "none") ), @APIResponse( responseCode = "200", content = @Content( mediaType = "application/json", schema = @Schema(type = SchemaType.OBJECT, implementation = Pet.class, oneOf = { Cat.class, Dog.class, Lizard.class }, readOnly = true)) ) }) @Operation( summary = "Find pet by ID", description = "Returns a pet when ID is less than or equal to 10" ) public Response getPetById( @Parameter( name = "petId", description = "ID of pet that needs to be fetched", required = true, example = "1", schema = @Schema( implementation = Long.class, maximum = "101", exclusiveMaximum = true, minimum = "9", exclusiveMinimum = true, multipleOf = 10)) @PathParam("petId") Long petId) throws NotFoundException { Pet pet = petData.getPetById(petId); if (pet != null) { return Response.ok().entity(pet).build(); } else { throw new NotFoundException(404, "Pet not found"); } } @GET @Path("/{petId}/download") @APIResponses(value={ @APIResponse( responseCode = "400", description = "Invalid ID supplied", content = @Content(mediaType = "none") ), @APIResponse( responseCode = "404", description = "Pet not found", content = @Content(mediaType = "none") ) }) @Operation( summary = "Find pet by ID and download it", description = "Returns a pet when ID is less than or equal to 10" ) public Response downloadFile( @Parameter( name = "petId", description = "ID of pet that needs to be fetched", required = true, schema = @Schema( implementation = Long.class, maximum = "10", minimum = "1") ) @PathParam("petId") Long petId) throws NotFoundException { StreamingOutput stream = new StreamingOutput() { @Override public void write(OutputStream output) throws IOException { try { // TODO: write file content to output; output.write("hello, world".getBytes()); } catch (Exception e) { e.printStackTrace(); } } }; return Response.ok(stream, "application/force-download") .header("Content-Disposition", "attachment; filename = foo.bar") .build(); } @DELETE @Path("/{petId}") @SecurityRequirement( name = "petsOAuth2", scopes = "write:pets" ) @APIResponses(value = { @APIResponse( responseCode = "400", description = "Invalid ID supplied" ), @APIResponse( responseCode = "404", description = "Pet not found" ) }) @Operation( summary = "Deletes a pet by ID", description = "Returns a pet when ID is less than or equal to 10" ) public Response deletePet( @Parameter( name = "apiKey", description = "authentication key to access this method", schema = @Schema(type = SchemaType.STRING, implementation = String.class, maxLength = 256, minLength = 32)) @HeaderParam("api_key") String apiKey, @Parameter( name = "petId", description = "ID of pet that needs to be fetched", required = true, schema = @Schema( implementation = Long.class, maximum = "10", minimum = "1")) @PathParam("petId") Long petId) { if (petData.deletePet(petId)) { return Response.ok().build(); } else { return Response.status(Response.Status.NOT_FOUND).build(); } } @POST @Consumes({"application/json", "application/xml"}) @Produces({"application/json", "application/xml"}) @SecurityRequirement( name = "petsApiKey" ) @APIResponse( responseCode = "400", description = "Invalid input", content = @Content( mediaType = "application/json", schema = @Schema(implementation = ApiResponse.class)) ) @RequestBody( name="pet", content = @Content( mediaType = "application/json", schema = @Schema(implementation = Pet.class), examples = @ExampleObject(ref = "http://example.org/petapi-examples/openapi.json#/components/examples/pet-example") ), required = true, description = "example of a new pet to add" ) @Operation( summary = "Add pet to store", description = "Add a new pet to the store" ) public Response addPet(Pet pet) { Pet updatedPet = petData.addPet(pet); return Response.ok().entity(updatedPet).build(); } @PUT @Consumes({"application/json", "application/xml"}) @SecurityRequirement( name = "petsHttp" ) @APIResponses(value={ @APIResponse( responseCode = "400", description = "Invalid ID supplied", content = @Content(mediaType = "application/json") ), @APIResponse( responseCode = "404", description = "Pet not found", content = @Content(mediaType = "application/json") ), @APIResponse( responseCode = "405", description = "Validation exception", content = @Content(mediaType = "application/json") ) }) @Operation( summary = "Update an existing pet", description = "Update an existing pet with the given new attributes" ) public Response updatePet( @Parameter( name ="petAttribute", description = "Attribute to update existing pet record", required = true, schema = @Schema(implementation = Pet.class)) Pet pet) { Pet updatedPet = petData.addPet(pet); return Response.ok().entity(updatedPet).build(); } @GET @Path("/findByStatus") @APIResponse( responseCode = "400", description = "Invalid status value", content = @Content(mediaType = "none") ) @APIResponse( responseCode = "200", content = @Content( mediaType = "application/json", schema = @Schema(type = SchemaType.ARRAY, implementation = Pet.class)) ) @Operation( summary = "Finds Pets by status", description = "Find all the Pets with the given status; Multiple status values can be provided with comma seperated strings" ) @Extension(name = "x-mp-method1", value = "true") @Extensions( { @Extension(name = "x-mp-method2", value = "true"), @Extension(value = "false", name = "x-mp-method3") } ) public Response findPetsByStatus( @Parameter( name = "status", description = "Status values that need to be considered for filter", required = true, schema = @Schema(implementation = String.class), content = { @Content( examples = { @ExampleObject( name = "Available", value = "available", summary = "Retrieves all the pets that are available"), @ExampleObject( name = "Pending", value = "pending", summary = "Retrieves all the pets that are pending to be sold"), @ExampleObject( name = "Sold", value = "sold", summary = "Retrieves all the pets that are sold") } ) }, allowEmptyValue = true) @Extension(name = "x-mp-parm1", value = "true") String status) { return Response.ok(petData.findPetByStatus(status)).build(); } @GET @Path("/findByTags") @Callback( name = "tagsCallback", callbackUrlExpression = "http://petstoreapp.com/pet", operations = @CallbackOperation( method = "GET", summary = "Finds Pets by tags", description = "Find Pets by tags; Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", responses = { @APIResponse( responseCode = "400", description = "Invalid tag value", content = @Content(mediaType = "none") ), @APIResponse( responseCode = "200", content = @Content( mediaType = "application/json", schema = @Schema(type = SchemaType.ARRAY, implementation = Pet.class)) ) } ) ) @Deprecated public Response findPetsByTags( @HeaderParam("apiKey") String apiKey, @Parameter( name = "tags", description = "Tags to filter by", required = true, deprecated = true, schema = @Schema(implementation = String.class, deprecated = true, externalDocs = @ExternalDocumentation(description = "Pet Types", url = "http://example.com/pettypes"), enumeration = { "Cat", "Dog", "Lizard" }, defaultValue = "Dog" )) @QueryParam("tags") String tags) { return Response.ok(petData.findPetByTags(tags)).build(); } @POST @Path("/{petId}") @Consumes({MediaType.APPLICATION_FORM_URLENCODED}) @APIResponse( responseCode = "405", description = "Validation exception", content = @Content(mediaType = "none") ) @Operation( summary = "Updates a pet in the store with form data" ) public Response updatePetWithForm ( @Parameter( name = "petId", description = "ID of pet that needs to be updated", required = true) @PathParam("petId") Long petId, @Parameter( name = "name", description = "Updated name of the pet") @FormParam("name") String name, @Parameter( name = "status", description = "Updated status of the pet") @FormParam("status") String status) { Pet pet = petData.getPetById(petId); if(pet != null) { if(name != null && !"".equals(name)){ pet.setName(name); } if(status != null && !"".equals(status)){ pet.setStatus(status); } petData.addPet(pet); return Response.ok().build(); } else{ return Response.status(404).build(); } } }
tck/src/main/java/org/eclipse/microprofile/openapi/apps/petstore/resource/PetResource.java
/** * Copyright (c) 2017 Contributors to the Eclipse Foundation * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations * under the License. */ package org.eclipse.microprofile.openapi.apps.petstore.resource; import org.eclipse.microprofile.openapi.annotations.Operation; import org.eclipse.microprofile.openapi.annotations.ExternalDocumentation; import org.eclipse.microprofile.openapi.annotations.parameters.Parameter; import org.eclipse.microprofile.openapi.annotations.enums.SecuritySchemeIn; import org.eclipse.microprofile.openapi.annotations.enums.SecuritySchemeType; import org.eclipse.microprofile.openapi.annotations.enums.SchemaType; import org.eclipse.microprofile.openapi.annotations.security.SecurityScheme; import org.eclipse.microprofile.openapi.annotations.security.SecuritySchemes; import org.eclipse.microprofile.openapi.annotations.security.SecurityRequirement; import org.eclipse.microprofile.openapi.annotations.security.OAuthFlow; import org.eclipse.microprofile.openapi.annotations.security.OAuthFlows; import org.eclipse.microprofile.openapi.annotations.callbacks.Callback; import org.eclipse.microprofile.openapi.annotations.extensions.Extension; import org.eclipse.microprofile.openapi.annotations.extensions.Extensions; import org.eclipse.microprofile.openapi.annotations.media.Content; import org.eclipse.microprofile.openapi.annotations.media.Schema; import org.eclipse.microprofile.openapi.annotations.parameters.RequestBody; import org.eclipse.microprofile.openapi.annotations.media.ExampleObject; import org.eclipse.microprofile.openapi.annotations.responses.APIResponse; import org.eclipse.microprofile.openapi.annotations.responses.APIResponses; import org.eclipse.microprofile.openapi.annotations.callbacks.CallbackOperation; import org.eclipse.microprofile.openapi.apps.petstore.data.PetData; import org.eclipse.microprofile.openapi.apps.petstore.model.Pet; import org.eclipse.microprofile.openapi.apps.petstore.model.ApiResponse; import org.eclipse.microprofile.openapi.apps.petstore.model.Cat; import org.eclipse.microprofile.openapi.apps.petstore.model.Dog; import org.eclipse.microprofile.openapi.apps.petstore.model.Lizard; import org.eclipse.microprofile.openapi.apps.petstore.exception.NotFoundException; import java.io.*; import javax.ws.rs.core.Response; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.StreamingOutput; import javax.ws.rs.GET; import javax.ws.rs.DELETE; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.HeaderParam; import javax.ws.rs.QueryParam; import javax.ws.rs.FormParam; import javax.ws.rs.Produces; import javax.ws.rs.Consumes; @Path("/pet") @Schema( name = "pet", description = "Operations on pets resource") @SecuritySchemes( value = { @SecurityScheme( securitySchemeName = "petsApiKey", type = SecuritySchemeType.APIKEY, description = "authentication needed to create a new pet profile for the store", apiKeyName = "createPetProfile", in = SecuritySchemeIn.HEADER ), @SecurityScheme( securitySchemeName = "petsOAuth2", type = SecuritySchemeType.OAUTH2, description = "authentication needed to delete a pet profile", flows = @OAuthFlows( implicit = @OAuthFlow( authorizationUrl = "https://example.com/api/oauth/dialog" ), authorizationCode = @OAuthFlow( authorizationUrl = "https://example.com/api/oauth/dialog", tokenUrl = "https://example.com/api/oauth/token" ) ) ), @SecurityScheme( securitySchemeName = "petsHttp", type = SecuritySchemeType.HTTP, description = "authentication needed to update an exsiting record of a pet in the store", scheme = "bearer", bearerFormat = "jwt" ) } ) public class PetResource { static PetData petData = new PetData(); @GET @Path("/{petId}") @APIResponses(value={ @APIResponse( responseCode = "400", description = "Invalid ID supplied", content = @Content( mediaType = "none") ), @APIResponse( responseCode = "404", description = "Pet not found", content = @Content( mediaType = "none") ), @APIResponse( responseCode = "200", content = @Content( mediaType = "application/json", schema = @Schema(type = SchemaType.ARRAY, implementation = Pet.class, oneOf = { Cat.class, Dog.class, Lizard.class }, readOnly = true)) ) }) @Operation( summary = "Find pet by ID", description = "Returns a pet when ID is less than or equal to 10" ) public Response getPetById( @Parameter( name = "petId", description = "ID of pet that needs to be fetched", required = true, example = "1", schema = @Schema( implementation = Long.class, maximum = "101", exclusiveMaximum = true, minimum = "9", exclusiveMinimum = true, multipleOf = 10)) @PathParam("petId") Long petId) throws NotFoundException { Pet pet = petData.getPetById(petId); if (pet != null) { return Response.ok().entity(pet).build(); } else { throw new NotFoundException(404, "Pet not found"); } } @GET @Path("/{petId}/download") @APIResponses(value={ @APIResponse( responseCode = "400", description = "Invalid ID supplied", content = @Content(mediaType = "none") ), @APIResponse( responseCode = "404", description = "Pet not found", content = @Content(mediaType = "none") ) }) @Operation( summary = "Find pet by ID and download it", description = "Returns a pet when ID is less than or equal to 10" ) public Response downloadFile( @Parameter( name = "petId", description = "ID of pet that needs to be fetched", required = true, schema = @Schema( implementation = Long.class, maximum = "10", minimum = "1") ) @PathParam("petId") Long petId) throws NotFoundException { StreamingOutput stream = new StreamingOutput() { @Override public void write(OutputStream output) throws IOException { try { // TODO: write file content to output; output.write("hello, world".getBytes()); } catch (Exception e) { e.printStackTrace(); } } }; return Response.ok(stream, "application/force-download") .header("Content-Disposition", "attachment; filename = foo.bar") .build(); } @DELETE @Path("/{petId}") @SecurityRequirement( name = "petsOAuth2", scopes = "write:pets" ) @APIResponses(value = { @APIResponse( responseCode = "400", description = "Invalid ID supplied" ), @APIResponse( responseCode = "404", description = "Pet not found" ) }) @Operation( summary = "Deletes a pet by ID", description = "Returns a pet when ID is less than or equal to 10" ) public Response deletePet( @Parameter( name = "apiKey", description = "authentication key to access this method", schema = @Schema(type = SchemaType.STRING, implementation = String.class, maxLength = 256, minLength = 32)) @HeaderParam("api_key") String apiKey, @Parameter( name = "petId", description = "ID of pet that needs to be fetched", required = true, schema = @Schema( implementation = Long.class, maximum = "10", minimum = "1")) @PathParam("petId") Long petId) { if (petData.deletePet(petId)) { return Response.ok().build(); } else { return Response.status(Response.Status.NOT_FOUND).build(); } } @POST @Consumes({"application/json", "application/xml"}) @Produces({"application/json", "application/xml"}) @SecurityRequirement( name = "petsApiKey" ) @APIResponse( responseCode = "400", description = "Invalid input", content = @Content( mediaType = "application/json", schema = @Schema(implementation = ApiResponse.class)) ) @RequestBody( name="pet", content = @Content( mediaType = "application/json", schema = @Schema(implementation = Pet.class), examples = @ExampleObject(ref = "http://example.org/petapi-examples/openapi.json#/components/examples/pet-example") ), required = true, description = "example of a new pet to add" ) @Operation( summary = "Add pet to store", description = "Add a new pet to the store" ) public Response addPet(Pet pet) { Pet updatedPet = petData.addPet(pet); return Response.ok().entity(updatedPet).build(); } @PUT @Consumes({"application/json", "application/xml"}) @SecurityRequirement( name = "petsHttp" ) @APIResponses(value={ @APIResponse( responseCode = "400", description = "Invalid ID supplied", content = @Content(mediaType = "application/json") ), @APIResponse( responseCode = "404", description = "Pet not found", content = @Content(mediaType = "application/json") ), @APIResponse( responseCode = "405", description = "Validation exception", content = @Content(mediaType = "application/json") ) }) @Operation( summary = "Update an existing pet", description = "Update an existing pet with the given new attributes" ) public Response updatePet( @Parameter( name ="petAttribute", description = "Attribute to update existing pet record", required = true, schema = @Schema(implementation = Pet.class)) Pet pet) { Pet updatedPet = petData.addPet(pet); return Response.ok().entity(updatedPet).build(); } @GET @Path("/findByStatus") @APIResponse( responseCode = "400", description = "Invalid status value", content = @Content(mediaType = "none") ) @APIResponse( responseCode = "200", content = @Content( mediaType = "application/json", schema = @Schema(type = SchemaType.ARRAY, implementation = Pet.class)) ) @Operation( summary = "Finds Pets by status", description = "Find all the Pets with the given status; Multiple status values can be provided with comma seperated strings" ) @Extension(name = "x-mp-method1", value = "true") @Extensions( { @Extension(name = "x-mp-method2", value = "true"), @Extension(value = "false", name = "x-mp-method3") } ) public Response findPetsByStatus( @Parameter( name = "status", description = "Status values that need to be considered for filter", required = true, schema = @Schema(implementation = String.class), content = { @Content( examples = { @ExampleObject( name = "Available", value = "available", summary = "Retrieves all the pets that are available"), @ExampleObject( name = "Pending", value = "pending", summary = "Retrieves all the pets that are pending to be sold"), @ExampleObject( name = "Sold", value = "sold", summary = "Retrieves all the pets that are sold") } ) }, allowEmptyValue = true) @Extension(name = "x-mp-parm1", value = "true") String status) { return Response.ok(petData.findPetByStatus(status)).build(); } @GET @Path("/findByTags") @Callback( name = "tagsCallback", callbackUrlExpression = "http://petstoreapp.com/pet", operations = @CallbackOperation( method = "GET", summary = "Finds Pets by tags", description = "Find Pets by tags; Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", responses = { @APIResponse( responseCode = "400", description = "Invalid tag value", content = @Content(mediaType = "none") ), @APIResponse( responseCode = "200", content = @Content( mediaType = "application/json", schema = @Schema(type = SchemaType.ARRAY, implementation = Pet.class)) ) } ) ) @Deprecated public Response findPetsByTags( @HeaderParam("apiKey") String apiKey, @Parameter( name = "tags", description = "Tags to filter by", required = true, deprecated = true, schema = @Schema(implementation = String.class, deprecated = true, externalDocs = @ExternalDocumentation(description = "Pet Types", url = "http://example.com/pettypes"), enumeration = { "Cat", "Dog", "Lizard" }, defaultValue = "Dog" )) @QueryParam("tags") String tags) { return Response.ok(petData.findPetByTags(tags)).build(); } @POST @Path("/{petId}") @Consumes({MediaType.APPLICATION_FORM_URLENCODED}) @APIResponse( responseCode = "405", description = "Validation exception", content = @Content(mediaType = "none") ) @Operation( summary = "Updates a pet in the store with form data" ) public Response updatePetWithForm ( @Parameter( name = "petId", description = "ID of pet that needs to be updated", required = true) @PathParam("petId") Long petId, @Parameter( name = "name", description = "Updated name of the pet") @FormParam("name") String name, @Parameter( name = "status", description = "Updated status of the pet") @FormParam("status") String status) { Pet pet = petData.getPetById(petId); if(pet != null) { if(name != null && !"".equals(name)){ pet.setName(name); } if(status != null && !"".equals(status)){ pet.setStatus(status); } petData.addPet(pet); return Response.ok().build(); } else{ return Response.status(404).build(); } } }
Fix array type. Signed-off-by: Paul Gooderham <[email protected]>
tck/src/main/java/org/eclipse/microprofile/openapi/apps/petstore/resource/PetResource.java
Fix array type.
Java
apache-2.0
c231831e7c5d49f69b220085caed94981ba56537
0
amith01994/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,signed/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,Distrotech/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,hurricup/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,caot/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,da1z/intellij-community,vvv1559/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,hurricup/intellij-community,holmes/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,izonder/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,ftomassetti/intellij-community,ibinti/intellij-community,allotria/intellij-community,izonder/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,dslomov/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,samthor/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,dslomov/intellij-community,semonte/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,samthor/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,allotria/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,signed/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,da1z/intellij-community,samthor/intellij-community,FHannes/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,kdwink/intellij-community,FHannes/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,supersven/intellij-community,Distrotech/intellij-community,allotria/intellij-community,robovm/robovm-studio,apixandru/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,clumsy/intellij-community,kool79/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,slisson/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,signed/intellij-community,supersven/intellij-community,holmes/intellij-community,tmpgit/intellij-community,signed/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,kdwink/intellij-community,caot/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,blademainer/intellij-community,kdwink/intellij-community,hurricup/intellij-community,fitermay/intellij-community,retomerz/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,da1z/intellij-community,petteyg/intellij-community,dslomov/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,izonder/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,FHannes/intellij-community,petteyg/intellij-community,fitermay/intellij-community,caot/intellij-community,hurricup/intellij-community,petteyg/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,samthor/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,slisson/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,da1z/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,jagguli/intellij-community,retomerz/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,allotria/intellij-community,petteyg/intellij-community,allotria/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,petteyg/intellij-community,fitermay/intellij-community,adedayo/intellij-community,jagguli/intellij-community,vladmm/intellij-community,caot/intellij-community,holmes/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,holmes/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,supersven/intellij-community,amith01994/intellij-community,slisson/intellij-community,jagguli/intellij-community,allotria/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,holmes/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,petteyg/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,hurricup/intellij-community,apixandru/intellij-community,vladmm/intellij-community,amith01994/intellij-community,semonte/intellij-community,clumsy/intellij-community,dslomov/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,Distrotech/intellij-community,allotria/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,caot/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,kool79/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,retomerz/intellij-community,caot/intellij-community,samthor/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,caot/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,retomerz/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,allotria/intellij-community,clumsy/intellij-community,da1z/intellij-community,holmes/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,kool79/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,robovm/robovm-studio,ryano144/intellij-community,dslomov/intellij-community,amith01994/intellij-community,izonder/intellij-community,clumsy/intellij-community,retomerz/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,clumsy/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,FHannes/intellij-community,FHannes/intellij-community,dslomov/intellij-community,caot/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,allotria/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,clumsy/intellij-community,semonte/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,supersven/intellij-community,ryano144/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,amith01994/intellij-community,nicolargo/intellij-community,da1z/intellij-community,wreckJ/intellij-community,da1z/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,vladmm/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,asedunov/intellij-community,petteyg/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,ryano144/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,caot/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,signed/intellij-community,adedayo/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,blademainer/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,dslomov/intellij-community,clumsy/intellij-community,ryano144/intellij-community,izonder/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,ryano144/intellij-community,signed/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,signed/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,kool79/intellij-community,fitermay/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,caot/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,holmes/intellij-community,gnuhub/intellij-community,samthor/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,hurricup/intellij-community,signed/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,fnouama/intellij-community,FHannes/intellij-community,kool79/intellij-community,xfournet/intellij-community,blademainer/intellij-community,semonte/intellij-community,petteyg/intellij-community,hurricup/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,supersven/intellij-community,holmes/intellij-community,FHannes/intellij-community,fitermay/intellij-community,ibinti/intellij-community,adedayo/intellij-community,blademainer/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,kdwink/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,hurricup/intellij-community,retomerz/intellij-community,supersven/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,slisson/intellij-community,robovm/robovm-studio,holmes/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,allotria/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,clumsy/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,retomerz/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,allotria/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,gnuhub/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community
package org.jetbrains.debugger.connection; import com.intellij.openapi.Disposable; import com.intellij.openapi.util.ActionCallback; import com.intellij.openapi.util.Disposer; import com.intellij.util.EventDispatcher; import com.intellij.util.io.socketConnection.ConnectionState; import com.intellij.util.io.socketConnection.ConnectionStatus; import com.intellij.util.io.socketConnection.SocketConnectionListener; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.debugger.DebugEventListener; import org.jetbrains.debugger.Vm; import javax.swing.event.HyperlinkListener; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; public abstract class VmConnection<T extends Vm> implements Disposable, BrowserConnection { private final AtomicReference<ConnectionState> state = new AtomicReference<ConnectionState>(new ConnectionState(ConnectionStatus.NOT_CONNECTED)); private final EventDispatcher<DebugEventListener> dispatcher = EventDispatcher.create(DebugEventListener.class); private final EventDispatcher<SocketConnectionListener> connectionDispatcher = EventDispatcher.create(SocketConnectionListener.class); protected volatile T vm; private final ActionCallback started = new ActionCallback(); private final AtomicBoolean closed = new AtomicBoolean(); public final Vm getVm() { return vm; } @NotNull @Override public ConnectionState getState() { return state.get(); } public void addDebugListener(@NotNull DebugEventListener listener, @NotNull Disposable parentDisposable) { dispatcher.addListener(listener, parentDisposable); } @Override public void executeOnStart(@NotNull Runnable runnable) { started.doWhenDone(runnable); } protected void setState(@NotNull ConnectionStatus status, @Nullable String message) { setState(status, message, null); } protected void setState(@NotNull ConnectionStatus status, @Nullable String message, @Nullable HyperlinkListener messageLinkListener) { ConnectionState oldState = state.getAndSet(new ConnectionState(status, message, messageLinkListener)); if (oldState == null || oldState.getStatus() != status) { connectionDispatcher.getMulticaster().statusChanged(status); } } @Override public void addListener(@NotNull SocketConnectionListener listener, @NotNull Disposable parentDisposable) { connectionDispatcher.addListener(listener, parentDisposable); } public DebugEventListener getDebugEventListener() { return dispatcher.getMulticaster(); } protected void startProcessing() { started.setDone(); } public final void close(@Nullable String message) { if (!closed.compareAndSet(false, true)) { return; } vm = null; if (!started.isProcessed()) { started.setRejected(); } setState(ConnectionStatus.DISCONNECTED, message); Disposer.dispose(this, false); } @Override public void dispose() { } public ActionCallback detachAndClose() { if (!started.isProcessed()) { started.setRejected(); } Vm currentVm = vm; ActionCallback callback; if (currentVm == null) { callback = new ActionCallback.Done(); } else { vm = null; callback = currentVm.detach(); } close(null); return callback; } }
platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/connection/VmConnection.java
package org.jetbrains.debugger.connection; import com.intellij.openapi.Disposable; import com.intellij.openapi.util.ActionCallback; import com.intellij.openapi.util.Disposer; import com.intellij.util.EventDispatcher; import com.intellij.util.io.socketConnection.ConnectionState; import com.intellij.util.io.socketConnection.ConnectionStatus; import com.intellij.util.io.socketConnection.SocketConnectionListener; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.debugger.DebugEventAdapter; import org.jetbrains.debugger.DebugEventListener; import org.jetbrains.debugger.Vm; import javax.swing.event.HyperlinkListener; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; public abstract class VmConnection<T extends Vm> implements Disposable, BrowserConnection { private final AtomicReference<ConnectionState> state = new AtomicReference<ConnectionState>(new ConnectionState(ConnectionStatus.NOT_CONNECTED)); private final EventDispatcher<DebugEventListener> dispatcher = EventDispatcher.create(DebugEventListener.class); private final EventDispatcher<SocketConnectionListener> connectionDispatcher = EventDispatcher.create(SocketConnectionListener.class); protected volatile T vm; private final ActionCallback started = new ActionCallback(); private final AtomicBoolean closed = new AtomicBoolean(); public final Vm getVm() { return vm; } @NotNull @Override public ConnectionState getState() { return state.get(); } public void addDebugListener(@NotNull DebugEventAdapter listener, @NotNull Disposable parentDisposable) { dispatcher.addListener(listener, parentDisposable); } @Override public void executeOnStart(@NotNull Runnable runnable) { started.doWhenDone(runnable); } protected void setState(@NotNull ConnectionStatus status, @Nullable String message) { setState(status, message, null); } protected void setState(@NotNull ConnectionStatus status, @Nullable String message, @Nullable HyperlinkListener messageLinkListener) { ConnectionState oldState = state.getAndSet(new ConnectionState(status, message, messageLinkListener)); if (oldState == null || oldState.getStatus() != status) { connectionDispatcher.getMulticaster().statusChanged(status); } } @Override public void addListener(@NotNull SocketConnectionListener listener, @NotNull Disposable parentDisposable) { connectionDispatcher.addListener(listener, parentDisposable); } public DebugEventListener getDebugEventListener() { return dispatcher.getMulticaster(); } protected void startProcessing() { started.setDone(); } public final void close(@Nullable String message) { if (!closed.compareAndSet(false, true)) { return; } vm = null; if (!started.isProcessed()) { started.setRejected(); } setState(ConnectionStatus.DISCONNECTED, message); Disposer.dispose(this, false); } @Override public void dispose() { } public ActionCallback detachAndClose() { if (!started.isProcessed()) { started.setRejected(); } Vm currentVm = vm; ActionCallback callback; if (currentVm == null) { callback = new ActionCallback.Done(); } else { vm = null; callback = currentVm.detach(); } close(null); return callback; } }
continue WEB-7303: reduce dependency on ExtBackedChromeConnection, move navigated() up
platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/connection/VmConnection.java
continue WEB-7303: reduce dependency on ExtBackedChromeConnection, move navigated() up
Java
apache-2.0
25e1fb4e8c8a167ac0f38e4d7e9a60d25c83f5ec
0
baldimir/droolsjbpm-integration,winklerm/droolsjbpm-integration,ge0ffrey/droolsjbpm-integration,droolsjbpm/droolsjbpm-integration,murador/droolsjbpm-integration,ibek/droolsjbpm-integration,ibek/droolsjbpm-integration,mrietveld/droolsjbpm-integration,ibek/droolsjbpm-integration,jesuino/droolsjbpm-integration,ge0ffrey/droolsjbpm-integration,drdaveg/droolsjbpm-integration,jakubschwan/droolsjbpm-integration,baldimir/droolsjbpm-integration,jesuino/droolsjbpm-integration,droolsjbpm/droolsjbpm-integration,muff1nman/droolsjbpm-integration,OnePaaS/droolsjbpm-integration,Multi-Support/droolsjbpm-integration,reynoldsm88/droolsjbpm-integration,markcoble/droolsjbpm-integration,jesuino/droolsjbpm-integration,murador/droolsjbpm-integration,jakubschwan/droolsjbpm-integration,markcoble/droolsjbpm-integration,murador/droolsjbpm-integration,baldimir/droolsjbpm-integration,kedzie/droolsjbpm-integration,muff1nman/droolsjbpm-integration,pokpitch/droolsjbpm-integration,murador/droolsjbpm-integration,pokpitch/droolsjbpm-integration,mrietveld/droolsjbpm-integration,reynoldsm88/droolsjbpm-integration,reynoldsm88/droolsjbpm-integration,Multi-Support/droolsjbpm-integration,jesuino/droolsjbpm-integration,drdaveg/droolsjbpm-integration,droolsjbpm/droolsjbpm-integration,ibek/droolsjbpm-integration,winklerm/droolsjbpm-integration,pokpitch/droolsjbpm-integration,Multi-Support/droolsjbpm-integration,kedzie/droolsjbpm-integration,BeatCoding/droolsjbpm-integration,jakubschwan/droolsjbpm-integration,reynoldsm88/droolsjbpm-integration,baldimir/droolsjbpm-integration,ge0ffrey/droolsjbpm-integration,mrietveld/droolsjbpm-integration,ge0ffrey/droolsjbpm-integration,BeatCoding/droolsjbpm-integration,droolsjbpm/droolsjbpm-integration,winklerm/droolsjbpm-integration,OnePaaS/droolsjbpm-integration,winklerm/droolsjbpm-integration,jakubschwan/droolsjbpm-integration,markcoble/droolsjbpm-integration,markcoble/droolsjbpm-integration,mrietveld/droolsjbpm-integration,Multi-Support/droolsjbpm-integration,pokpitch/droolsjbpm-integration
/* * Copyright 2012 Red Hat * * 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.karaf.itest; import static org.apache.karaf.tooling.exam.options.KarafDistributionOption.*; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.ops4j.pax.exam.CoreOptions.maven; import static org.ops4j.pax.exam.CoreOptions.scanFeatures; import java.io.File; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import javax.persistence.EntityManagerFactory; import org.apache.karaf.tooling.exam.options.LogLevelOption; import org.h2.tools.Server; import org.jbpm.process.instance.impl.demo.SystemOutWorkItemHandler; import org.jbpm.services.task.identity.JBossUserGroupCallbackImpl; import org.jbpm.test.JBPMHelper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.io.ResourceType; import org.kie.api.runtime.EnvironmentName; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.StatelessKieSession; import org.kie.api.runtime.manager.RuntimeEngine; import org.kie.api.runtime.manager.RuntimeEnvironment; import org.kie.api.runtime.manager.RuntimeEnvironmentBuilder; import org.kie.api.runtime.manager.RuntimeManager; import org.kie.api.runtime.manager.RuntimeManagerFactory; import org.kie.api.runtime.process.ProcessInstance; import org.kie.api.task.TaskService; import org.kie.api.task.model.TaskSummary; import org.kie.internal.runtime.manager.context.EmptyContext; import org.ops4j.pax.exam.MavenUtils; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.ExamReactorStrategy; import org.ops4j.pax.exam.junit.JUnit4TestRunner; import org.ops4j.pax.exam.spi.reactors.EagerSingleStagedReactorFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.osgi.context.support.OsgiBundleXmlApplicationContext; import org.springframework.transaction.PlatformTransactionManager; @RunWith(JUnit4TestRunner.class) @ExamReactorStrategy(EagerSingleStagedReactorFactory.class) public class KieSpringOnKarafTest extends KieSpringIntegrationTestSupport { protected static final transient Logger LOG = LoggerFactory.getLogger(KieSpringOnKarafTest.class); protected static final String DroolsVersion; static { Properties testProps = new Properties(); try { testProps.load(KieSpringOnKarafTest.class.getResourceAsStream("/test.properties")); } catch (Exception e) { throw new RuntimeException("Unable to initialize DroolsVersion property: " + e.getMessage(), e); } DroolsVersion = testProps.getProperty("project.version"); LOG.info("Drools Project Version : " + DroolsVersion); } @Before public void init() { applicationContext = createApplicationContext(); assertNotNull("Should have created a valid spring context", applicationContext); } @Test public void testKieBase() throws Exception { refresh(); KieBase kbase = (KieBase) applicationContext.getBean("drl_kiesample"); assertNotNull(kbase); } @Test public void testKieSession() throws Exception { refresh(); StatelessKieSession ksession = (StatelessKieSession) applicationContext.getBean("ksession9"); assertNotNull(ksession); } @Test public void testKieSessionDefaultType() throws Exception { refresh(); Object obj = applicationContext.getBean("ksession99"); assertNotNull(obj); assertTrue(obj instanceof KieSession); } @Test public void testJbpmRuntimeManager() { refresh(); RuntimeEnvironment environment = RuntimeEnvironmentBuilder.Factory.get().newEmptyBuilder() .addAsset( KieServices.Factory.get().getResources().newClassPathResource( "Evaluation.bpmn",getClass().getClassLoader()), ResourceType.BPMN2) .get(); RuntimeManager runtimeManager = RuntimeManagerFactory.Factory.get().newSingletonRuntimeManager(environment); KieSession ksession = runtimeManager.getRuntimeEngine(EmptyContext.get()).getKieSession(); ksession.getWorkItemManager().registerWorkItemHandler("Human Task", new SystemOutWorkItemHandler()); LOG.info("Start process Evaluation (bpmn2)"); Map<String, Object> params = new HashMap<String, Object>(); params.put("employee", "krisv"); params.put("reason", "Yearly performance evaluation"); ProcessInstance processInstance = ksession.startProcess("com.sample.evaluation", params); LOG.info("Started process instance " + processInstance.getId()); } @Test public void testJbpmRuntimeManagerWithPersistence() { Server server = startH2Server(); refresh(); Properties props = new Properties(); props.setProperty("krisv", "IT"); props.setProperty("john", "HR"); props.setProperty("mary", "PM"); EntityManagerFactory emf = (EntityManagerFactory) applicationContext.getBean("myEmf"); PlatformTransactionManager txManager = (PlatformTransactionManager) applicationContext.getBean("txManager"); RuntimeEnvironment environment = RuntimeEnvironmentBuilder.Factory.get().newDefaultBuilder() .entityManagerFactory(emf) .addEnvironmentEntry(EnvironmentName.TRANSACTION_MANAGER, txManager) .addAsset( KieServices.Factory.get().getResources().newClassPathResource( "Evaluation.bpmn",getClass().getClassLoader()), ResourceType.BPMN2) .userGroupCallback(new JBossUserGroupCallbackImpl(props)) .get(); RuntimeManager runtimeManager = RuntimeManagerFactory.Factory.get().newSingletonRuntimeManager(environment); RuntimeEngine runtimeEngine = runtimeManager.getRuntimeEngine(EmptyContext.get()); KieSession ksession = runtimeEngine.getKieSession(); TaskService taskService = runtimeEngine.getTaskService(); // start a new process instance Map<String, Object> params = new HashMap<String, Object>(); params.put("employee", "krisv"); params.put("reason", "Yearly performance evaluation"); ProcessInstance processInstance = ksession.startProcess("com.sample.evaluation", params); System.out.println("Process instance " + processInstance.getId() + " started ..."); ProcessInstance pi = ksession.getProcessInstance(processInstance.getId()); System.out.println(pi); // complete Self Evaluation List<TaskSummary> tasks = taskService.getTasksAssignedAsPotentialOwner("krisv", "en-UK"); TaskSummary task = tasks.get(0); System.out.println("'krisv' completing task " + task.getName() + ": " + task.getDescription()); taskService.start(task.getId(), "krisv"); Map<String, Object> vars = taskService.getTaskContent(task.getId()); Map<String, Object> results = new HashMap<String, Object>(); results.put("performance", "exceeding"); taskService.complete(task.getId(), "krisv", results); // john from HR tasks = taskService.getTasksAssignedAsPotentialOwner("john", "en-UK"); task = tasks.get(0); System.out.println("'john' completing task " + task.getName() + ": " + task.getDescription()); taskService.claim(task.getId(), "john"); taskService.start(task.getId(), "john"); results = new HashMap<String, Object>(); results.put("performance", "acceptable"); taskService.complete(task.getId(), "john", results); // mary from PM tasks = taskService.getTasksAssignedAsPotentialOwner("mary", "en-UK"); task = tasks.get(0); System.out.println("'mary' completing task " + task.getName() + ": " + task.getDescription()); taskService.claim(task.getId(), "mary"); taskService.start(task.getId(), "mary"); results = new HashMap<String, Object>(); results.put("performance", "outstanding"); taskService.complete(task.getId(), "mary", results); System.out.println("Process instance completed"); runtimeManager.disposeRuntimeEngine(runtimeEngine); runtimeManager.close(); server.shutdown(); } public static Server startH2Server() { try { // start h2 in memory database Server server = Server.createTcpServer(new String[0]); server.start(); return server; } catch (Throwable t) { throw new RuntimeException("Could not start H2 server", t); } } @Configuration public static Option[] configure() { return new Option[]{ // Install Karaf Container karafDistributionConfiguration().frameworkUrl( maven().groupId("org.apache.karaf").artifactId("apache-karaf").type("tar.gz").versionAsInProject()) .karafVersion(MavenUtils.getArtifactVersion("org.apache.karaf", "apache-karaf")).name("Apache Karaf") .unpackDirectory(new File("target/exam/unpack/")), // It is really nice if the container sticks around after the test so you can check the contents // of the data directory when things go wrong. keepRuntimeFolder(), // Don't bother with local console output as it just ends up cluttering the logs configureConsole().ignoreLocalConsole(), // Force the log level to INFO so we have more details during the test. It defaults to WARN. logLevel(LogLevelOption.LogLevel.INFO), // Option to be used to do remote debugging // debugConfiguration("5005", true), // Load Spring DM Karaf Feature scanFeatures( maven().groupId("org.apache.karaf.assemblies.features").artifactId("standard").type("xml").classifier("features").versionAsInProject(), "spring", "spring-dm" ), // Load Kie-Spring loadDroolsKieFeatures("jbpm-spring-persistent") }; } protected OsgiBundleXmlApplicationContext createApplicationContext() { return new OsgiBundleXmlApplicationContext(new String[]{"org/drools/karaf/itest/kie-beans-persistence.xml"}); } }
drools-osgi/drools-karaf-itest/src/test/java/org/drools/karaf/itest/KieSpringOnKarafTest.java
/* * Copyright 2012 Red Hat * * 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.karaf.itest; import static org.apache.karaf.tooling.exam.options.KarafDistributionOption.configureConsole; import static org.apache.karaf.tooling.exam.options.KarafDistributionOption.karafDistributionConfiguration; import static org.apache.karaf.tooling.exam.options.KarafDistributionOption.keepRuntimeFolder; import static org.apache.karaf.tooling.exam.options.KarafDistributionOption.logLevel; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.ops4j.pax.exam.CoreOptions.maven; import static org.ops4j.pax.exam.CoreOptions.scanFeatures; import java.io.File; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import javax.persistence.EntityManagerFactory; import org.apache.karaf.tooling.exam.options.LogLevelOption; import org.h2.tools.Server; import org.jbpm.process.instance.impl.demo.SystemOutWorkItemHandler; import org.jbpm.test.JBPMHelper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.io.ResourceType; import org.kie.api.runtime.EnvironmentName; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.StatelessKieSession; import org.kie.api.runtime.manager.RuntimeEngine; import org.kie.api.runtime.manager.RuntimeEnvironment; import org.kie.api.runtime.manager.RuntimeEnvironmentBuilder; import org.kie.api.runtime.manager.RuntimeManager; import org.kie.api.runtime.manager.RuntimeManagerFactory; import org.kie.api.runtime.process.ProcessInstance; import org.kie.api.task.TaskService; import org.kie.api.task.model.TaskSummary; import org.kie.internal.runtime.manager.context.EmptyContext; import org.ops4j.pax.exam.MavenUtils; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.ExamReactorStrategy; import org.ops4j.pax.exam.junit.JUnit4TestRunner; import org.ops4j.pax.exam.spi.reactors.EagerSingleStagedReactorFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.osgi.context.support.OsgiBundleXmlApplicationContext; import org.springframework.transaction.PlatformTransactionManager; @RunWith(JUnit4TestRunner.class) @ExamReactorStrategy(EagerSingleStagedReactorFactory.class) public class KieSpringOnKarafTest extends KieSpringIntegrationTestSupport { protected static final transient Logger LOG = LoggerFactory.getLogger(KieSpringOnKarafTest.class); protected static final String DroolsVersion; static { Properties testProps = new Properties(); try { testProps.load(KieSpringOnKarafTest.class.getResourceAsStream("/test.properties")); } catch (Exception e) { throw new RuntimeException("Unable to initialize DroolsVersion property: " + e.getMessage(), e); } DroolsVersion = testProps.getProperty("project.version"); LOG.info("Drools Project Version : " + DroolsVersion); } @Before public void init() { applicationContext = createApplicationContext(); assertNotNull("Should have created a valid spring context", applicationContext); } @Test public void testKieBase() throws Exception { refresh(); KieBase kbase = (KieBase) applicationContext.getBean("drl_kiesample"); assertNotNull(kbase); } @Test public void testKieSession() throws Exception { refresh(); StatelessKieSession ksession = (StatelessKieSession) applicationContext.getBean("ksession9"); assertNotNull(ksession); } @Test public void testKieSessionDefaultType() throws Exception { refresh(); Object obj = applicationContext.getBean("ksession99"); assertNotNull(obj); assertTrue(obj instanceof KieSession); } @Test public void testJbpmRuntimeManager() { refresh(); RuntimeEnvironment environment = RuntimeEnvironmentBuilder.Factory.get().newEmptyBuilder() .addAsset( KieServices.Factory.get().getResources().newClassPathResource( "Evaluation.bpmn",getClass().getClassLoader()), ResourceType.BPMN2) .get(); RuntimeManager runtimeManager = RuntimeManagerFactory.Factory.get().newSingletonRuntimeManager(environment); KieSession ksession = runtimeManager.getRuntimeEngine(EmptyContext.get()).getKieSession(); ksession.getWorkItemManager().registerWorkItemHandler("Human Task", new SystemOutWorkItemHandler()); LOG.info("Start process Evaluation (bpmn2)"); Map<String, Object> params = new HashMap<String, Object>(); params.put("employee", "krisv"); params.put("reason", "Yearly performance evaluation"); ProcessInstance processInstance = ksession.startProcess("com.sample.evaluation", params); LOG.info("Started process instance " + processInstance.getId()); } @Test public void testJbpmRuntimeManagerWithPersistence() { Server server = startH2Server(); refresh(); EntityManagerFactory emf = (EntityManagerFactory) applicationContext.getBean("myEmf"); PlatformTransactionManager txManager = (PlatformTransactionManager) applicationContext.getBean("txManager"); RuntimeEnvironment environment = RuntimeEnvironmentBuilder.Factory.get().newDefaultBuilder() .entityManagerFactory(emf) .addEnvironmentEntry(EnvironmentName.TRANSACTION_MANAGER, txManager) .addAsset( KieServices.Factory.get().getResources().newClassPathResource( "Evaluation.bpmn",getClass().getClassLoader()), ResourceType.BPMN2) .get(); RuntimeManager runtimeManager = RuntimeManagerFactory.Factory.get().newSingletonRuntimeManager(environment); RuntimeEngine runtimeEngine = runtimeManager.getRuntimeEngine(EmptyContext.get()); KieSession ksession = runtimeEngine.getKieSession(); TaskService taskService = runtimeEngine.getTaskService(); // start a new process instance Map<String, Object> params = new HashMap<String, Object>(); params.put("employee", "krisv"); params.put("reason", "Yearly performance evaluation"); ProcessInstance processInstance = ksession.startProcess("com.sample.evaluation", params); System.out.println("Process instance " + processInstance.getId() + " started ..."); // // complete Self Evaluation // List<TaskSummary> tasks = taskService.getTasksAssignedAsPotentialOwner("krisv", "en-UK"); // TaskSummary task = tasks.get(0); // System.out.println("'krisv' completing task " + task.getName() + ": " + task.getDescription()); // taskService.start(task.getId(), "krisv"); // Map<String, Object> results = new HashMap<String, Object>(); // results.put("performance", "exceeding"); // taskService.complete(task.getId(), "krisv", results); // // // john from HR // tasks = taskService.getTasksAssignedAsPotentialOwner("john", "en-UK"); // task = tasks.get(0); // System.out.println("'john' completing task " + task.getName() + ": " + task.getDescription()); // taskService.claim(task.getId(), "john"); // taskService.start(task.getId(), "john"); // results = new HashMap<String, Object>(); // results.put("performance", "acceptable"); // taskService.complete(task.getId(), "john", results); // // // mary from PM // tasks = taskService.getTasksAssignedAsPotentialOwner("mary", "en-UK"); // task = tasks.get(0); // System.out.println("'mary' completing task " + task.getName() + ": " + task.getDescription()); // taskService.claim(task.getId(), "mary"); // taskService.start(task.getId(), "mary"); // results = new HashMap<String, Object>(); // results.put("performance", "outstanding"); // taskService.complete(task.getId(), "mary", results); // // System.out.println("Process instance completed"); runtimeManager.disposeRuntimeEngine(runtimeEngine); runtimeManager.close(); server.shutdown(); } public static Server startH2Server() { try { // start h2 in memory database Server server = Server.createTcpServer(new String[0]); server.start(); return server; } catch (Throwable t) { throw new RuntimeException("Could not start H2 server", t); } } @Configuration public static Option[] configure() { return new Option[]{ // Install Karaf Container karafDistributionConfiguration().frameworkUrl( maven().groupId("org.apache.karaf").artifactId("apache-karaf").type("tar.gz").versionAsInProject()) .karafVersion(MavenUtils.getArtifactVersion("org.apache.karaf", "apache-karaf")).name("Apache Karaf") .unpackDirectory(new File("target/exam/unpack/")), // It is really nice if the container sticks around after the test so you can check the contents // of the data directory when things go wrong. keepRuntimeFolder(), // Don't bother with local console output as it just ends up cluttering the logs configureConsole().ignoreLocalConsole(), // Force the log level to INFO so we have more details during the test. It defaults to WARN. logLevel(LogLevelOption.LogLevel.INFO), // Option to be used to do remote debugging //debugConfiguration("5005", true), // Load Spring DM Karaf Feature scanFeatures( maven().groupId("org.apache.karaf.assemblies.features").artifactId("standard").type("xml").classifier("features").versionAsInProject(), "spring", "spring-dm" ), // Load Kie-Spring loadDroolsKieFeatures("jbpm-spring-persistent") }; } protected OsgiBundleXmlApplicationContext createApplicationContext() { return new OsgiBundleXmlApplicationContext(new String[]{"org/drools/karaf/itest/kie-beans-persistence.xml"}); } }
JBPM-4400 - Problems using persistences with human tasks in OSGi - added usergroupcallback to osgi persistence test
drools-osgi/drools-karaf-itest/src/test/java/org/drools/karaf/itest/KieSpringOnKarafTest.java
JBPM-4400 - Problems using persistences with human tasks in OSGi - added usergroupcallback to osgi persistence test
Java
apache-2.0
f8b5a6f27d9446c51a6a3a572b09740f7ae7477b
0
myrrix/myrrix-recommender,myrrix/myrrix-recommender
/* * Copyright Myrrix Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.myrrix.common; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.util.Iterator; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; import com.google.common.io.PatternFilenameFilter; import org.apache.commons.math3.random.RandomGenerator; import org.apache.mahout.cf.taste.common.TasteException; import org.apache.mahout.cf.taste.impl.common.FullRunningAverageAndStdDev; import org.apache.mahout.cf.taste.impl.common.RunningAverage; import org.apache.mahout.common.iterator.FileLineIterable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.myrrix.common.collection.CountingIterator; import net.myrrix.common.collection.FastIDSet; import net.myrrix.common.parallel.Paralleler; import net.myrrix.common.parallel.Processor; import net.myrrix.common.random.RandomManager; /** * Runs a mixed, concurrent load against a given recommender instance. This could be a * {@code ClientRecommender} configured to access a remote instance. * * @author Sean Owen */ public final class LoadRunner implements Callable<Void> { private static final Logger log = LoggerFactory.getLogger(LoadRunner.class); private final MyrrixRecommender client; private final long[] uniqueUserIDs; private final long[] uniqueItemIDs; private final int steps; /** * @param client recommender to load * @param dataDirectory a directory containing data files from which user and item IDs should be read * @param steps number of load steps to run */ public LoadRunner(MyrrixRecommender client, File dataDirectory, int steps) throws IOException { Preconditions.checkNotNull(client); Preconditions.checkNotNull(dataDirectory); Preconditions.checkArgument(steps > 0); log.info("Reading IDs..."); FastIDSet userIDsSet = new FastIDSet(); FastIDSet itemIDsSet = new FastIDSet(); Splitter comma = Splitter.on(','); for (File f : dataDirectory.listFiles(new PatternFilenameFilter(".+\\.csv(\\.(zip|gz))?"))) { for (CharSequence line : new FileLineIterable(f)) { Iterator<String> it = comma.split(line).iterator(); userIDsSet.add(Long.parseLong(it.next())); itemIDsSet.add(Long.parseLong(it.next())); } } this.client = client; this.uniqueUserIDs = userIDsSet.toArray(); this.uniqueItemIDs = itemIDsSet.toArray(); this.steps = steps; } /** * @param client recommender to load * @param uniqueUserIDs user IDs which may be used in test calls * @param uniqueItemIDs item IDs which may be used in test calls * @param steps number of load steps to run */ public LoadRunner(MyrrixRecommender client, long[] uniqueUserIDs, long[] uniqueItemIDs, int steps) { Preconditions.checkNotNull(client); Preconditions.checkNotNull(uniqueItemIDs); Preconditions.checkNotNull(uniqueItemIDs); Preconditions.checkArgument(steps > 0, "steps must be positive: {}", steps); this.client = client; this.uniqueUserIDs = uniqueUserIDs; this.uniqueItemIDs = uniqueItemIDs; this.steps = steps; } public int getSteps() { return steps; } @Override public Void call() throws Exception { runLoad(); return null; } public void runLoad() throws ExecutionException, InterruptedException { final RunningAverage recommendedBecause = new FullRunningAverageAndStdDev(); final RunningAverage setPreference = new FullRunningAverageAndStdDev(); final RunningAverage removePreference = new FullRunningAverageAndStdDev(); final RunningAverage setTag = new FullRunningAverageAndStdDev(); final RunningAverage ingest = new FullRunningAverageAndStdDev(); final RunningAverage refresh = new FullRunningAverageAndStdDev(); final RunningAverage estimatePreference = new FullRunningAverageAndStdDev(); final RunningAverage mostSimilarItems = new FullRunningAverageAndStdDev(); final RunningAverage similarityToItem = new FullRunningAverageAndStdDev(); final RunningAverage mostPopularItems = new FullRunningAverageAndStdDev(); final RunningAverage recommendToMany = new FullRunningAverageAndStdDev(); final RunningAverage recommend = new FullRunningAverageAndStdDev(); Processor<Integer> processor = new Processor<Integer>() { private final RandomGenerator random = RandomManager.getRandom(); @Override public void process(Integer step, long count) { double r; long userID; long itemID; long itemID2; float value; synchronized (random) { r = random.nextDouble(); userID = uniqueUserIDs[random.nextInt(uniqueUserIDs.length)]; itemID = uniqueItemIDs[random.nextInt(uniqueItemIDs.length)]; itemID2 = uniqueItemIDs[random.nextInt(uniqueItemIDs.length)]; value = random.nextInt(10); } long stepStart = System.currentTimeMillis(); try { if (r < 0.05) { client.recommendedBecause(userID, itemID, 10); recommendedBecause.addDatum(System.currentTimeMillis() - stepStart); } else if (r < 0.07) { client.setPreference(userID, itemID); setPreference.addDatum(System.currentTimeMillis() - stepStart); } else if (r < 0.08) { client.setPreference(userID, itemID, value); setPreference.addDatum(System.currentTimeMillis() - stepStart); } else if (r < 0.09) { client.setUserTag(userID, Long.toString(itemID)); setTag.addDatum(System.currentTimeMillis() - stepStart); } else if (r < 0.10) { client.setItemTag(Long.toString(userID), itemID); setTag.addDatum(System.currentTimeMillis() - stepStart); } else if (r < 0.11) { client.removePreference(userID, itemID); removePreference.addDatum(System.currentTimeMillis() - stepStart); } else if (r < 0.12) { StringReader reader = new StringReader(userID + "," + itemID + ',' + value + '\n'); client.ingest(reader); ingest.addDatum(System.currentTimeMillis() - stepStart); } else if (r < 0.13) { client.refresh(); refresh.addDatum(System.currentTimeMillis() - stepStart); } else if (r < 0.14) { client.similarityToItem(itemID, itemID2); similarityToItem.addDatum(System.currentTimeMillis() - stepStart); } else if (r < 0.15) { client.mostPopularItems(10); mostPopularItems.addDatum(System.currentTimeMillis() - stepStart); } else if (r < 0.19) { client.estimatePreference(userID, itemID); estimatePreference.addDatum(System.currentTimeMillis() - stepStart); } else if (r < 0.20) { client.estimateForAnonymous(itemID, new long[] {itemID2}); estimatePreference.addDatum(System.currentTimeMillis() - stepStart); } else if (r < 0.25) { client.mostSimilarItems(new long[]{itemID}, 10); mostSimilarItems.addDatum(System.currentTimeMillis() - stepStart); } else if (r < 0.30) { client.recommendToMany(new long[] { userID, userID }, 10, true, null); recommendToMany.addDatum(System.currentTimeMillis() - stepStart); } else { client.recommend(userID, 10); recommend.addDatum(System.currentTimeMillis() - stepStart); } } catch (TasteException te) { log.warn("Error during request", te); } if (count % 1000 == 0) { log.info("Finished {} load steps", count); } } }; log.info("Starting load test..."); long start = System.currentTimeMillis(); new Paralleler<Integer>(new CountingIterator(steps), processor, "Load").runInParallel(); long end = System.currentTimeMillis(); log.info("Finished {} steps in {}ms", steps, end - start); log.info("recommendedBecause: {}", recommendedBecause); log.info("setPreference: {}", setPreference); log.info("removePreference: {}", removePreference); log.info("setTag: {}", setTag); log.info("ingest: {}", ingest); log.info("refresh: {}", refresh); log.info("estimatePreference: {}", estimatePreference); log.info("mostSimilarItems: {}", mostSimilarItems); log.info("similarityToItem: {}", similarityToItem); log.info("mostPopularItems: {}", mostPopularItems); log.info("recommendToMany: {}", recommendToMany); log.info("recommend: {}", recommend); } }
common/test/net/myrrix/common/LoadRunner.java
/* * Copyright Myrrix Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.myrrix.common; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.util.Iterator; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; import com.google.common.io.PatternFilenameFilter; import org.apache.commons.math3.random.RandomGenerator; import org.apache.mahout.cf.taste.common.TasteException; import org.apache.mahout.cf.taste.impl.common.FullRunningAverageAndStdDev; import org.apache.mahout.cf.taste.impl.common.RunningAverage; import org.apache.mahout.common.iterator.FileLineIterable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.myrrix.common.collection.CountingIterator; import net.myrrix.common.collection.FastIDSet; import net.myrrix.common.parallel.Paralleler; import net.myrrix.common.parallel.Processor; import net.myrrix.common.random.RandomManager; /** * Runs a mixed, concurrent load against a given recommender instance. This could be a * {@code ClientRecommender} configured to access a remote instance. * * @author Sean Owen */ public final class LoadRunner implements Callable<Void> { private static final Logger log = LoggerFactory.getLogger(LoadRunner.class); private final MyrrixRecommender client; private final long[] uniqueUserIDs; private final long[] uniqueItemIDs; private final int steps; /** * @param client recommender to load * @param dataDirectory a directory containing data files from which user and item IDs should be read * @param steps number of load steps to run */ public LoadRunner(MyrrixRecommender client, File dataDirectory, int steps) throws IOException { Preconditions.checkNotNull(client); Preconditions.checkNotNull(dataDirectory); Preconditions.checkArgument(steps > 0); log.info("Reading IDs..."); FastIDSet userIDsSet = new FastIDSet(); FastIDSet itemIDsSet = new FastIDSet(); Splitter comma = Splitter.on(','); for (File f : dataDirectory.listFiles(new PatternFilenameFilter(".+\\.csv(\\.(zip|gz))?"))) { for (CharSequence line : new FileLineIterable(f)) { Iterator<String> it = comma.split(line).iterator(); userIDsSet.add(Long.parseLong(it.next())); itemIDsSet.add(Long.parseLong(it.next())); } } this.client = client; this.uniqueUserIDs = userIDsSet.toArray(); this.uniqueItemIDs = itemIDsSet.toArray(); this.steps = steps; } /** * @param client recommender to load * @param uniqueUserIDs user IDs which may be used in test calls * @param uniqueItemIDs item IDs which may be used in test calls * @param steps number of load steps to run */ public LoadRunner(MyrrixRecommender client, long[] uniqueUserIDs, long[] uniqueItemIDs, int steps) { Preconditions.checkNotNull(client); Preconditions.checkNotNull(uniqueItemIDs); Preconditions.checkNotNull(uniqueItemIDs); Preconditions.checkArgument(steps > 0, "steps must be positive: {}", steps); this.client = client; this.uniqueUserIDs = uniqueUserIDs; this.uniqueItemIDs = uniqueItemIDs; this.steps = steps; } public int getSteps() { return steps; } @Override public Void call() throws Exception { runLoad(); return null; } public void runLoad() throws ExecutionException, InterruptedException { final RunningAverage recommendedBecause = new FullRunningAverageAndStdDev(); final RunningAverage setPreference = new FullRunningAverageAndStdDev(); final RunningAverage removePreference = new FullRunningAverageAndStdDev(); final RunningAverage setTag = new FullRunningAverageAndStdDev(); final RunningAverage ingest = new FullRunningAverageAndStdDev(); final RunningAverage refresh = new FullRunningAverageAndStdDev(); final RunningAverage estimatePreference = new FullRunningAverageAndStdDev(); final RunningAverage mostSimilarItems = new FullRunningAverageAndStdDev(); final RunningAverage similarityToItem = new FullRunningAverageAndStdDev(); final RunningAverage mostPopularItems = new FullRunningAverageAndStdDev(); final RunningAverage recommendToMany = new FullRunningAverageAndStdDev(); final RunningAverage recommend = new FullRunningAverageAndStdDev(); Processor<Integer> processor = new Processor<Integer>() { private final RandomGenerator random = RandomManager.getRandom(); @Override public void process(Integer step, long count) throws ExecutionException { double r; long userID; long itemID; long itemID2; float value; synchronized (random) { r = random.nextDouble(); userID = uniqueUserIDs[random.nextInt(uniqueUserIDs.length)]; itemID = uniqueItemIDs[random.nextInt(uniqueItemIDs.length)]; itemID2 = uniqueItemIDs[random.nextInt(uniqueItemIDs.length)]; value = random.nextInt(10); } long stepStart = System.currentTimeMillis(); try { if (r < 0.05) { client.recommendedBecause(userID, itemID, 10); recommendedBecause.addDatum(System.currentTimeMillis() - stepStart); } else if (r < 0.07) { client.setPreference(userID, itemID); setPreference.addDatum(System.currentTimeMillis() - stepStart); } else if (r < 0.08) { client.setPreference(userID, itemID, value); setPreference.addDatum(System.currentTimeMillis() - stepStart); } else if (r < 0.09) { client.setUserTag(userID, Long.toString(itemID)); setTag.addDatum(System.currentTimeMillis() - stepStart); } else if (r < 0.10) { client.setItemTag(Long.toString(userID), itemID); setTag.addDatum(System.currentTimeMillis() - stepStart); } else if (r < 0.11) { client.removePreference(userID, itemID); removePreference.addDatum(System.currentTimeMillis() - stepStart); } else if (r < 0.12) { StringReader reader = new StringReader(userID + "," + itemID + ',' + value + '\n'); client.ingest(reader); ingest.addDatum(System.currentTimeMillis() - stepStart); } else if (r < 0.13) { client.refresh(); refresh.addDatum(System.currentTimeMillis() - stepStart); } else if (r < 0.14) { client.similarityToItem(itemID, itemID2); similarityToItem.addDatum(System.currentTimeMillis() - stepStart); } else if (r < 0.15) { client.mostPopularItems(10); mostPopularItems.addDatum(System.currentTimeMillis() - stepStart); } else if (r < 0.19) { client.estimatePreference(userID, itemID); estimatePreference.addDatum(System.currentTimeMillis() - stepStart); } else if (r < 0.20) { client.estimateForAnonymous(itemID, new long[] {itemID2}); estimatePreference.addDatum(System.currentTimeMillis() - stepStart); } else if (r < 0.25) { client.mostSimilarItems(new long[]{itemID}, 10); mostSimilarItems.addDatum(System.currentTimeMillis() - stepStart); } else if (r < 0.30) { client.recommendToMany(new long[] { userID, userID }, 10, true, null); recommendToMany.addDatum(System.currentTimeMillis() - stepStart); } else { client.recommend(userID, 10); recommend.addDatum(System.currentTimeMillis() - stepStart); } } catch (TasteException te) { throw new ExecutionException(te); } if (count % 1000 == 0) { log.info("Finished {} load steps", count); } } }; log.info("Starting load test..."); long start = System.currentTimeMillis(); new Paralleler<Integer>(new CountingIterator(steps), processor, "Load").runInParallel(); long end = System.currentTimeMillis(); log.info("Finished {} steps in {}ms", steps, end - start); log.info("recommendedBecause: {}", recommendedBecause); log.info("setPreference: {}", setPreference); log.info("removePreference: {}", removePreference); log.info("setTag: {}", setTag); log.info("ingest: {}", ingest); log.info("refresh: {}", refresh); log.info("estimatePreference: {}", estimatePreference); log.info("mostSimilarItems: {}", mostSimilarItems); log.info("similarityToItem: {}", similarityToItem); log.info("mostPopularItems: {}", mostPopularItems); log.info("recommendToMany: {}", recommendToMany); log.info("recommend: {}", recommend); } }
Log but don't stop on exception in a load test git-svn-id: f7ac9ee3e7208fd97c9a3deb5e52ce295d20494a@551 0d189622-dca1-7e23-9e30-e8815eb7bd2f
common/test/net/myrrix/common/LoadRunner.java
Log but don't stop on exception in a load test
Java
apache-2.0
1e122a84d9be8fdf9b85db1e99ee7a479e26fe72
0
Comcast/Oscar,Comcast/Oscar
package com.comcast.oscar.netsnmp; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.collections4.BidiMap; import org.apache.commons.collections4.bidimap.DualHashBidiMap; import com.comcast.oscar.utilities.DirectoryStructure; import com.comcast.oscar.utilities.Disk; import com.comcast.oscar.utilities.HexString; import com.comcast.oscar.utilities.PrettyPrint; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; /** * @bannerLicense Copyright 2015 Comcast Cable Communications Management, LLC<br> ___________________________________________________________________<br> 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<br> http://www.apache.org/licenses/LICENSE-2.0<br> Unless required by applicable law or agreed to in writing, software<br> 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.<br> * @author Maurice Garcia ([email protected]) */ public class NetSNMP { private static Boolean debug = Boolean.FALSE; private static ObjectMapper omNetSNMP = null; private static BidiMap<String, String> bmDotTextMap = null; private static final Pattern NETSNMP_DESCRIPTION = Pattern.compile("" + ".*DESCRIPTION\\s+\"(.*)\"", Pattern.CASE_INSENSITIVE); static { FixNullNetSNMPJSON(); omNetSNMP = new ObjectMapper(); bmDotTextMap = new DualHashBidiMap<String,String>(); try { bmDotTextMap = omNetSNMP.readValue(DirectoryStructureNetSNMP.fNetSNMPJSON(), new TypeReference<DualHashBidiMap<String, String>>() {}); } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * Convert: docsDevNmAccessIp.1 -> .1.3.6.1.2.1.69.1.2.1.2.1 * * @param sOID OID either Dotted or Textual OID * @return .1.3.6.x.x.x.x.x */ public static String toDottedOID(String sOID) { boolean localDebug = Boolean.FALSE; if (debug|localDebug) System.out.println("NetSNMP.toDottedOID(): " + sOID); if (isDottedOID(sOID)) { if (debug|localDebug) System.out.println("NetSNMP.toDottedOID() Is a DootedOID -> " + sOID); return sOID; } if (!CheckOIDDBLookup(sOID).isEmpty()) { return CheckOIDDBLookup(sOID); } /* If not installed, bypass and return input */ if (!isSnmptranslateInstalled()) { return sOID; } String sDottedOID = ""; /* Not a clean way to do it, but it works */ String sSnmpTranslate = Constants.SNMP_TRANSLATE_CMD + Constants.MIB_PARAMETER + Constants.SNMP_TRANSLATE_OID_NAME_2_OID_DEC + sOID.replaceAll("\\s+1", " .iso") .replaceAll("\\s+\\.1", " .iso"); if (debug|localDebug) System.out.println("NetSNMP.toDottedOID(): " + sSnmpTranslate); sDottedOID = runSnmpTranslate(sSnmpTranslate).get(0); /* Add Converted OIDS to Map for later Storage */ UpdateJsonDB(sOID,sDottedOID); if (debug|localDebug) System.out.println("NetSNMP.toDottedOID(): " + sDottedOID); return runSnmpTranslate(sSnmpTranslate).get(0); } /** * * Convert: .1.3.6.1.2.1.69.1.2.1.2.1 -> docsDevNmAccessIp.1 * * @param sOID OID either Dotted or Textual OID * @return Example: docsDevNmAccessIp.1 */ public static String toTextualOID(String sOID) { boolean localDebug = Boolean.FALSE; if (debug|localDebug) System.out.println("NetSNMP.toTextualOID(): " + sOID); if (!isDottedOID(sOID)) { return sOID; } if (!CheckOIDDBLookup(sOID).isEmpty()) { if (debug|localDebug) System.out.println("NetSNMP.toTextualOID(): (" + CheckOIDDBLookup(sOID) + ")"); return CheckOIDDBLookup(sOID); } /* If not installed, bypass and return input */ if (!isSnmptranslateInstalled()) { return sOID; } String sTextualOID = ""; String sSnmpTranslate = Constants.SNMP_TRANSLATE_CMD + Constants.MIB_PARAMETER + Constants.SNMP_TRANSLATE_OID_DEC_2_OID_NAME + sOID; if (debug|localDebug) System.out.println("NetSNMP.toTextualOID(): " + sSnmpTranslate); sTextualOID = runSnmpTranslate(sSnmpTranslate).get(0); /* Add Converted OIDS to Map for later Storage */ UpdateJsonDB(sOID,sTextualOID); if (debug|localDebug) System.out.println("NetSNMP.toTextualOID(): " + sTextualOID); return sTextualOID; } /** * * @param sOID OID either Dotted or Textual OID * @param boolDotTextFormat TRUE = Textual OID Output , FALSE = Dotted OID Output * @return Dotted or Textual OID */ public static String toOIDFormat(String sOID , boolean boolDotTextFormat) { /* Textual OID */ if (boolDotTextFormat) { return toTextualOID(sOID); } /* Dotted OID */ else { return toDottedOID(sOID); } } /** * * @return True = Install | False = Not-Install*/ public static boolean isSnmptranslateInstalled() { String sSnmpTranslate = Constants.SNMP_TRANSLATE_CMD + Constants.SNMP_TRANSLATE_VERSION; if (runSnmpTranslate(sSnmpTranslate) == null) { return false; } else { return true; } } /** * * If OID starts with .1.3.6 it is considered a DottedOID * * @param sOID * @return */ public static boolean isDottedOID(String sOID) { if (Constants.ISO_ORG_DOD_DOTTED.matcher(sOID).find()) { return true; } return false; } /** * * @param sOID .1.3.6.1.2.1.69.1.2.1.2.1 OR docsDevNmAccessIp.1 * @return Description of OID */ public static String getDescription(String sOID) { boolean localDebug = Boolean.FALSE; String sDescription = ""; String sSnmpTranslate = ""; if (debug|localDebug) System.out.println("NetSNMP.getDescription(): " + sOID); /* If not installed, bypass and return input */ if (!isSnmptranslateInstalled()) { return sOID; } if (isDottedOID(sOID)) { sSnmpTranslate = Constants.SNMP_TRANSLATE_CMD + Constants.MIB_PARAMETER + Constants.SNMP_TRANSLATE_DESCRIPTION_DOTTED_OID + sOID; } else { sSnmpTranslate = Constants.SNMP_TRANSLATE_CMD + Constants.MIB_PARAMETER + Constants.SNMP_TRANSLATE_DESCRIPTION_TEXTUAL_OID + sOID; } if (debug|localDebug) System.out.println("NetSNMP.getDescription() TRANSLATE-CLI: " + sSnmpTranslate); Matcher mDescription = NETSNMP_DESCRIPTION.matcher(runSnmpTranslate(sSnmpTranslate).toString()); if (mDescription.find()) { sDescription = "\n" + PrettyPrint.ToParagraphForm(mDescription.group(1).replaceAll("\\s+", " ")); } if (debug|localDebug) System.out.println("NetSNMP.getDescription() TRANSLATE-DESCRIPTION: " + sDescription); if (sDescription.isEmpty()) { sDescription = "\nVerify that MIBS are loaded for OID: " + sOID; } return sDescription; } /** * * @param sSnmpTranslateCMD * @return OID Translation - Null is snmptranslate is not installed*/ private static ArrayList<String> runSnmpTranslate(String sSnmpTranslateCMD) { boolean localDebug = Boolean.FALSE; if (debug|localDebug) System.out.println(sSnmpTranslateCMD); ArrayList<String> als = new ArrayList<String>(); Process p = null; try { p = Runtime.getRuntime().exec(sSnmpTranslateCMD); } catch (IOException e1) { /* If not found or installed */ return null; } BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream())); String sStd_IO = ""; /*Read the output from the command If Any */ int iCounter = 0; try { while ((sStd_IO = stdInput.readLine()) != null) { //Clean up White Space if (!sStd_IO.isEmpty()) als.add(sStd_IO); if (debug|localDebug) System.out.println(++iCounter + " IN: " + sStd_IO); } } catch (IOException e) { e.printStackTrace(); } try { while ((sStd_IO = stdError.readLine()) != null) { als.add(sStd_IO); if (debug|localDebug) System.out.println(++iCounter + " OUT: " + sStd_IO); } } catch (IOException e) { e.printStackTrace(); } return als; } /** * @bannerLicense Copyright 2015 Comcast Cable Communications Management, LLC<br> ___________________________________________________________________<br> 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<br> http://www.apache.org/licenses/LICENSE-2.0<br> Unless required by applicable law or agreed to in writing, software<br> 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.<br> * @author Maurice Garcia ([email protected]) */ public static class DirectoryStructureNetSNMP extends DirectoryStructure { /** * @return NetSNMP subdirectory*/ public static File fNetSNMPJSON() { return new File(fDbDir().getName() + File.separator + Constants.DOTTED_TEXTUAL_NetSNMP_MAP_FILE) ; } } /** * * @param sOIDKey * @param sOIDConvert */ private static void UpdateJsonDB(String sOIDKey, String sOIDConvert) { bmDotTextMap.put(sOIDKey, sOIDConvert); try { omNetSNMP.writeValue(DirectoryStructureNetSNMP.fNetSNMPJSON(), bmDotTextMap); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * * @param sOID * @return returns a lookup value, blank if nothing is found */ private static String CheckOIDDBLookup(String sOID) { String sReturn = ""; if (bmDotTextMap.containsKey(sOID)) { if (debug) System.out.println("CheckOIDDBLookup().containsKey " + sOID + " -> " + bmDotTextMap.get(sOID)); return bmDotTextMap.get(sOID); } else if (bmDotTextMap.containsValue(sOID)) { if (debug) System.out.println("CheckOIDDBLookup().containsValue " + sOID + " -> " + bmDotTextMap.getKey(sOID)); return bmDotTextMap.getKey(sOID); } return sReturn; } /** * Checks to see if the DB file is empty, if so put a single entry to prevent error */ private static void FixNullNetSNMPJSON() { if (!DirectoryStructureNetSNMP.fNetSNMPJSON().exists()) { Disk.writeToDisk("{\"1.3.6\":\"dod\"}", DirectoryStructureNetSNMP.fNetSNMPJSON()); } else if (HexString.fileToByteArray(DirectoryStructureNetSNMP.fNetSNMPJSON()).length == 0) { Disk.writeToDisk("{\"1.3.6\":\"dod\"}", DirectoryStructureNetSNMP.fNetSNMPJSON()); } } }
src/com/comcast/oscar/netsnmp/NetSNMP.java
package com.comcast.oscar.netsnmp; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.collections4.BidiMap; import org.apache.commons.collections4.bidimap.DualHashBidiMap; import com.comcast.oscar.utilities.DirectoryStructure; import com.comcast.oscar.utilities.Disk; import com.comcast.oscar.utilities.HexString; import com.comcast.oscar.utilities.PrettyPrint; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; /** * @bannerLicense Copyright 2015 Comcast Cable Communications Management, LLC<br> ___________________________________________________________________<br> 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<br> http://www.apache.org/licenses/LICENSE-2.0<br> Unless required by applicable law or agreed to in writing, software<br> 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.<br> * @author Maurice Garcia ([email protected]) */ public class NetSNMP { private static Boolean debug = Boolean.FALSE; private static ObjectMapper omNetSNMP = null; private static BidiMap<String, String> bmDotTextMap = null; private static final Pattern NETSNMP_DESCRIPTION = Pattern.compile("" + ".*DESCRIPTION\\s+\"(.*)\"", Pattern.CASE_INSENSITIVE); static { FixNullNetSNMPJSON(); omNetSNMP = new ObjectMapper(); bmDotTextMap = new DualHashBidiMap<String,String>(); try { bmDotTextMap = omNetSNMP.readValue(DirectoryStructureNetSNMP.fNetSNMPJSON(), new TypeReference<DualHashBidiMap<String, String>>() {}); } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * Convert: docsDevNmAccessIp.1 -> .1.3.6.1.2.1.69.1.2.1.2.1 * * @param sOID OID either Dotted or Textual OID * @return .1.3.6.x.x.x.x.x */ public static String toDottedOID(String sOID) { boolean localDebug = Boolean.FALSE; if (debug|localDebug) System.out.println("NetSNMP.toDottedOID(): " + sOID); if (isDottedOID(sOID)) { if (debug|localDebug) System.out.println("NetSNMP.toDottedOID() Is a DootedOID -> " + sOID); return sOID; } if (!CheckOIDDBLookup(sOID).isEmpty()) { return CheckOIDDBLookup(sOID); } /* If not installed, bypass and return input */ if (!isSnmptranslateInstalled()) { return sOID; } String sDottedOID = ""; /* Not a clean way to do it, but it works */ String sSnmpTranslate = Constants.SNMP_TRANSLATE_CMD + Constants.MIB_PARAMETER + Constants.SNMP_TRANSLATE_OID_NAME_2_OID_DEC + sOID.replaceAll("\\s+1", " .iso") .replaceAll("\\s+\\.1", " .iso"); if (debug|localDebug) System.out.println("NetSNMP.toDottedOID(): " + sSnmpTranslate); sDottedOID = runSnmpTranslate(sSnmpTranslate).get(0); /* Add Converted OIDS to Map for later Storage */ UpdateJsonDB(sOID,sDottedOID); if (debug|localDebug) System.out.println("NetSNMP.toDottedOID(): " + sDottedOID); return runSnmpTranslate(sSnmpTranslate).get(0); } /** * * Convert: .1.3.6.1.2.1.69.1.2.1.2.1 -> docsDevNmAccessIp.1 * * @param sOID OID either Dotted or Textual OID * @return Example: docsDevNmAccessIp.1 */ public static String toTextualOID(String sOID) { boolean localDebug = Boolean.FALSE; if (debug|localDebug) System.out.println("NetSNMP.toTextualOID(): " + sOID); if (!isDottedOID(sOID)) { return sOID; } if (!CheckOIDDBLookup(sOID).isEmpty()) { if (debug|localDebug) System.out.println("NetSNMP.toTextualOID(): (" + CheckOIDDBLookup(sOID) + ")"); return CheckOIDDBLookup(sOID); } /* If not installed, bypass and return input */ if (!isSnmptranslateInstalled()) { return sOID; } String sTextualOID = ""; String sSnmpTranslate = Constants.SNMP_TRANSLATE_CMD + Constants.MIB_PARAMETER + Constants.SNMP_TRANSLATE_OID_DEC_2_OID_NAME + sOID; if (debug|localDebug) System.out.println("NetSNMP.toTextualOID(): " + sSnmpTranslate); sTextualOID = runSnmpTranslate(sSnmpTranslate).get(0); /* Add Converted OIDS to Map for later Storage */ UpdateJsonDB(sOID,sTextualOID); if (debug|localDebug) System.out.println("NetSNMP.toTextualOID(): " + sTextualOID); return sTextualOID; } /** * * @param sOID OID either Dotted or Textual OID * @param boolDotTextFormat TRUE = Textual OID Output , FALSE = Dotted OID Output * @return Dotted or Textual OID */ public static String toOIDFormat(String sOID , boolean boolDotTextFormat) { /* Textual OID */ if (boolDotTextFormat) { return toTextualOID(sOID); } /* Dotted OID */ else { return toDottedOID(sOID); } } /** * * @return True = Install | False = Not-Install*/ public static boolean isSnmptranslateInstalled() { String sSnmpTranslate = Constants.SNMP_TRANSLATE_CMD + Constants.SNMP_TRANSLATE_VERSION; if (runSnmpTranslate(sSnmpTranslate) == null) { return false; } else { return true; } } /** * * If OID starts with .1.3.6 it is considered a DottedOID * * @param sOID * @return */ public static boolean isDottedOID(String sOID) { if (Constants.ISO_ORG_DOD_DOTTED.matcher(sOID).find()) { return true; } return false; } /** * * @param sOID * @return */ public static String getDescription(String sOID) { boolean localDebug = Boolean.FALSE; String sDescription = ""; String sSnmpTranslate = ""; if (debug|localDebug) System.out.println("NetSNMP.getDescription(): " + sOID); /* If not installed, bypass and return input */ if (!isSnmptranslateInstalled()) { return sOID; } if (isDottedOID(sOID)) { sSnmpTranslate = Constants.SNMP_TRANSLATE_CMD + Constants.MIB_PARAMETER + Constants.SNMP_TRANSLATE_DESCRIPTION_DOTTED_OID + sOID; } else { sSnmpTranslate = Constants.SNMP_TRANSLATE_CMD + Constants.MIB_PARAMETER + Constants.SNMP_TRANSLATE_DESCRIPTION_TEXTUAL_OID + sOID; } if (debug|localDebug) System.out.println("NetSNMP.getDescription() TRANSLATE-CLI: " + sSnmpTranslate); Matcher mDescription = NETSNMP_DESCRIPTION.matcher(runSnmpTranslate(sSnmpTranslate).toString()); if (mDescription.find()) { sDescription = PrettyPrint.ToParagraphForm(mDescription.group(1).replaceAll("\\s+", " ")); } if (debug|localDebug) System.out.println("NetSNMP.getDescription() TRANSLATE-DESCRIPTION: " + sDescription); if (sDescription.isEmpty()) { sDescription = "\nVerify that MIBS are loaded for OID: " + sOID; } return sDescription; } /** * * @param sSnmpTranslateCMD * @return OID Translation - Null is snmptranslate is not installed*/ private static ArrayList<String> runSnmpTranslate(String sSnmpTranslateCMD) { boolean localDebug = Boolean.FALSE; if (debug|localDebug) System.out.println(sSnmpTranslateCMD); ArrayList<String> als = new ArrayList<String>(); Process p = null; try { p = Runtime.getRuntime().exec(sSnmpTranslateCMD); } catch (IOException e1) { /* If not found or installed */ return null; } BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream())); String sStd_IO = ""; /*Read the output from the command If Any */ int iCounter = 0; try { while ((sStd_IO = stdInput.readLine()) != null) { //Clean up White Space if (!sStd_IO.isEmpty()) als.add(sStd_IO); if (debug|localDebug) System.out.println(++iCounter + " IN: " + sStd_IO); } } catch (IOException e) { e.printStackTrace(); } try { while ((sStd_IO = stdError.readLine()) != null) { als.add(sStd_IO); if (debug|localDebug) System.out.println(++iCounter + " OUT: " + sStd_IO); } } catch (IOException e) { e.printStackTrace(); } return als; } /** * @bannerLicense Copyright 2015 Comcast Cable Communications Management, LLC<br> ___________________________________________________________________<br> 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<br> http://www.apache.org/licenses/LICENSE-2.0<br> Unless required by applicable law or agreed to in writing, software<br> 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.<br> * @author Maurice Garcia ([email protected]) */ public static class DirectoryStructureNetSNMP extends DirectoryStructure { /** * @return NetSNMP subdirectory*/ public static File fNetSNMPJSON() { return new File(fDbDir().getName() + File.separator + Constants.DOTTED_TEXTUAL_NetSNMP_MAP_FILE) ; } } /** * * @param sOIDKey * @param sOIDConvert */ private static void UpdateJsonDB(String sOIDKey, String sOIDConvert) { bmDotTextMap.put(sOIDKey, sOIDConvert); try { omNetSNMP.writeValue(DirectoryStructureNetSNMP.fNetSNMPJSON(), bmDotTextMap); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * * @param sOID * @return returns a lookup value, blank if nothing is found */ private static String CheckOIDDBLookup(String sOID) { String sReturn = ""; if (bmDotTextMap.containsKey(sOID)) { if (debug) System.out.println("CheckOIDDBLookup().containsKey " + sOID + " -> " + bmDotTextMap.get(sOID)); return bmDotTextMap.get(sOID); } else if (bmDotTextMap.containsValue(sOID)) { if (debug) System.out.println("CheckOIDDBLookup().containsValue " + sOID + " -> " + bmDotTextMap.getKey(sOID)); return bmDotTextMap.getKey(sOID); } return sReturn; } /** * Checks to see if the DB file is empty, if so put a single entry to prevent error */ private static void FixNullNetSNMPJSON() { if (!DirectoryStructureNetSNMP.fNetSNMPJSON().exists()) { Disk.writeToDisk("{\"1.3.6\":\"dod\"}", DirectoryStructureNetSNMP.fNetSNMPJSON()); } else if (HexString.fileToByteArray(DirectoryStructureNetSNMP.fNetSNMPJSON()).length == 0) { Disk.writeToDisk("{\"1.3.6\":\"dod\"}", DirectoryStructureNetSNMP.fNetSNMPJSON()); } } }
Version 2.1 Signed-off-by: Maurice Garcia <[email protected]>
src/com/comcast/oscar/netsnmp/NetSNMP.java
Version 2.1
Java
apache-2.0
ba9d374cdf0abf42cd2c35194d31e57066ea2c47
0
javalite/activejdbc,javalite/activejdbc,javalite/activejdbc,javalite/activejdbc
/* Copyright 2009-2018 Igor Polevoy 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.javalite.activejdbc; import org.javalite.activejdbc.annotations.*; import org.javalite.activejdbc.associations.*; import org.javalite.activejdbc.cache.CacheManager; import org.javalite.activejdbc.cache.QueryCache; import org.javalite.activejdbc.logging.LogFilter; import org.javalite.activejdbc.logging.LogLevel; import org.javalite.activejdbc.statistics.StatisticsQueue; import java.lang.reflect.Method; import java.sql.DatabaseMetaData; import java.util.*; import java.sql.SQLException; import java.sql.Connection; import java.sql.ResultSet; import org.javalite.common.Inflector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Igor Polevoy * @author Eric Nielsen */ public enum Registry { //our singleton! INSTANCE; private static final Logger LOGGER = LoggerFactory.getLogger(Registry.class); private final MetaModels metaModels = new MetaModels(); private final Map<Class, ModelRegistry> modelRegistries = new HashMap<>(); private final Configuration configuration = new Configuration(); private final StatisticsQueue statisticsQueue; private final Set<String> initedDbs = new HashSet<>(); private Registry() { statisticsQueue = configuration.collectStatistics() ? new StatisticsQueue(configuration.collectStatisticsOnHold()) : null; } /** * @deprecated Not used anymore. */ @Deprecated public boolean initialized() { // This will return true if AT LEAST ONE DB was initialized, not if ALL were (if there are more than one). // Hopefully this is not used anywhere. return !initedDbs.isEmpty(); } public static Registry instance() { return INSTANCE; } public StatisticsQueue getStatisticsQueue() { if (statisticsQueue == null) { throw new InitException("cannot collect statistics if this was not configured in activejdbc.properties file. Add 'collectStatistics = true' to it."); } return statisticsQueue; } public Configuration getConfiguration(){ return configuration; } public static CacheManager cacheManager(){ return QueryCache.instance().getCacheManager(); } /** * Provides a MetaModel of a model representing a table. * * @param table name of table represented by this MetaModel. * @return MetaModel of a model representing a table. */ public MetaModel getMetaModel(String table) { return metaModels.getMetaModel(table); } public MetaModel getMetaModel(Class<? extends Model> modelClass) { String dbName = MetaModel.getDbName(modelClass); init(dbName); return metaModels.getMetaModel(modelClass); } ModelRegistry modelRegistryOf(Class<? extends Model> modelClass) { ModelRegistry registry = modelRegistries.get(modelClass); if (registry == null) { registry = new ModelRegistry(); modelRegistries.put(modelClass, registry); } return registry; } synchronized void init(String dbName) { if (initedDbs.contains(dbName)) { return; } else { initedDbs.add(dbName); } try { ModelFinder.findModels(dbName); Connection c = ConnectionsAccess.getConnection(dbName); if(c == null){ throw new DBException("Failed to retrieve metadata from DB, connection: '" + dbName + "' is not available"); } DatabaseMetaData databaseMetaData = c.getMetaData(); String dbType = c.getMetaData().getDatabaseProductName(); List<Class<? extends Model>> modelClasses = ModelFinder.getModelsForDb(dbName); registerModels(dbName, modelClasses, dbType); String[] tables = metaModels.getTableNames(dbName); for (String table : tables) { Map<String, ColumnMetadata> metaParams = fetchMetaParams(databaseMetaData, dbType, table); registerColumnMetadata(table, metaParams); } for (String table : tables) { discoverAssociationsFor(table, dbName); } processOverrides(modelClasses); } catch (Exception e) { initedDbs.remove(dbName); if (e instanceof InitException) { throw (InitException) e; } if (e instanceof DBException) { throw (DBException) e; } else { throw new InitException(e); } } } /** * Returns a hash keyed off a column name. */ private Map<String, ColumnMetadata> fetchMetaParams(DatabaseMetaData databaseMetaData, String dbType, String table) throws SQLException { /* * Valid table name format: tablename or schemaname.tablename */ String[] names = table.split("\\.", 3); String schema = null; String tableName; switch (names.length) { case 1: tableName = names[0]; break; case 2: schema = names[0]; tableName = names[1]; if (schema.isEmpty() || tableName.isEmpty()) { throw new DBException("invalid table name : " + table); } break; default: throw new DBException("invalid table name: " + table); } if (schema == null) { try { schema = databaseMetaData.getConnection().getSchema(); } catch (Error | Exception ignore ) {} } String catalog = null; if(dbType.equalsIgnoreCase("mysql")){ catalog = schema; } if(dbType.equalsIgnoreCase("h2")){ String url = databaseMetaData.getURL(); catalog = url.substring(url.lastIndexOf(":") + 1).toUpperCase(); schema = schema != null ? schema.toUpperCase() : null; // keep quoted table names as is, otherwise use uppercase if (!tableName.contains("\"")) { tableName = tableName.toUpperCase(); } else if(tableName.startsWith("\"") && tableName.endsWith("\"")) { tableName = tableName.substring(1, tableName.length() - 1); } } if(dbType.toLowerCase().contains("postgres") && tableName.startsWith("\"") && tableName.endsWith("\"")){ tableName = tableName.substring(1, tableName.length() - 1); } ResultSet rs = databaseMetaData.getColumns(catalog, schema, tableName, null); Map<String, ColumnMetadata> columns = getColumns(rs, dbType); rs.close(); //try upper case table name - Oracle uses upper case if (columns.isEmpty()) { rs = databaseMetaData.getColumns(null, schema, tableName.toUpperCase(), null); columns = getColumns(rs, dbType); rs.close(); } //if upper case not found, try lower case. if (columns.isEmpty()) { rs = databaseMetaData.getColumns(null, schema, tableName.toLowerCase(), null); columns = getColumns(rs, dbType); rs.close(); } if(columns.size() > 0){ LogFilter.log(LOGGER, LogLevel.INFO, "Fetched metadata for table: {}", table); } else{ LogFilter.log(LOGGER, LogLevel.WARNING, "Failed to retrieve metadata for table: '{}'." + " Are you sure this table exists? For some databases table names are case sensitive.", table); } return columns; } /** * * @param modelClasses * @param dbType this is a name of a DBMS as returned by JDBC driver, such as Oracle, MySQL, etc. */ private void registerModels(String dbName, List<Class<? extends Model>> modelClasses, String dbType) { for (Class<? extends Model> modelClass : modelClasses) { MetaModel mm = new MetaModel(dbName, modelClass, dbType); metaModels.addMetaModel(mm, modelClass); LogFilter.log(LOGGER, LogLevel.INFO, "Registered model: {}", modelClass); } } private void processOverrides(List<Class<? extends Model>> models) { for(Class<? extends Model> modelClass : models){ BelongsTo belongsToAnnotation = modelClass.getAnnotation(BelongsTo.class); processOverridesBelongsTo(modelClass, belongsToAnnotation); BelongsToParents belongsToParentAnnotation = modelClass.getAnnotation(BelongsToParents.class); if (belongsToParentAnnotation != null){ for (BelongsTo belongsTo : belongsToParentAnnotation.value()){ processOverridesBelongsTo(modelClass, belongsTo); } } HasMany hasManyAnnotation = modelClass.getAnnotation(HasMany.class); processOverridesHasMany(modelClass, hasManyAnnotation); Many2Manies many2ManiesAnnotation = modelClass.getAnnotation(Many2Manies.class); if (many2ManiesAnnotation != null) { for (Many2Many many2Many : many2ManiesAnnotation.value()) { processManyToManyOverrides(many2Many, modelClass); } } Many2Many many2manyAnnotation = modelClass.getAnnotation(Many2Many.class); if(many2manyAnnotation != null){ processManyToManyOverrides(many2manyAnnotation, modelClass); } BelongsToPolymorphic belongsToPolymorphic = modelClass.getAnnotation(BelongsToPolymorphic.class); if(belongsToPolymorphic != null){ processPolymorphic(belongsToPolymorphic, modelClass); } UnrelatedTo unrelatedTo = modelClass.getAnnotation(UnrelatedTo .class); if(unrelatedTo != null){ processUnrelatedTo(unrelatedTo, modelClass); } } } private void processUnrelatedTo(UnrelatedTo unrelatedTo, Class<? extends Model> modelClass) { Class<? extends Model>[] related = unrelatedTo.value(); for (Class<? extends Model> relatedClass : related) { MetaModel relatedMM = metaModels.getMetaModel(relatedClass); MetaModel thisMM = metaModels.getMetaModel(modelClass); if(relatedMM != null){ Association association = relatedMM.getAssociationForTarget(modelClass); relatedMM.removeAssociationForTarget(modelClass); if(association != null){ LogFilter.log(LOGGER, LogLevel.INFO, "Removed association: " + association); } } Association association = thisMM.getAssociationForTarget(relatedClass); thisMM.removeAssociationForTarget(relatedClass); if(association != null){ LogFilter.log(LOGGER, LogLevel.INFO, "Removed association: " + association); } } } private void processPolymorphic(BelongsToPolymorphic belongsToPolymorphic, Class<? extends Model> modelClass ) { Class<? extends Model>[] parentClasses = belongsToPolymorphic.parents(); String[] typeLabels = belongsToPolymorphic.typeLabels(); if (typeLabels.length > 0 && typeLabels.length != parentClasses.length) { throw new InitException("must provide all type labels for polymorphic associations"); } for (int i = 0, parentClassesLength = parentClasses.length; i < parentClassesLength; i++) { Class<? extends Model> parentClass = parentClasses[i]; String typeLabel = typeLabels.length > 0 ? typeLabels[i] : parentClass.getName(); BelongsToPolymorphicAssociation belongsToPolymorphicAssociation = new BelongsToPolymorphicAssociation(modelClass, parentClass, typeLabel, parentClass.getName()); metaModels.getMetaModel(modelClass).addAssociation(belongsToPolymorphicAssociation); OneToManyPolymorphicAssociation oneToManyPolymorphicAssociation = new OneToManyPolymorphicAssociation(parentClass, modelClass, typeLabel); metaModels.getMetaModel(parentClass).addAssociation(oneToManyPolymorphicAssociation); } } private void processManyToManyOverrides(Many2Many many2manyAnnotation, Class<? extends Model> modelClass){ Class<? extends Model> otherClass = many2manyAnnotation.other(); String source = getTableName(modelClass); String target = getTableName(otherClass); String join = many2manyAnnotation.join(); String sourceFKName = many2manyAnnotation.sourceFKName(); String targetFKName = many2manyAnnotation.targetFKName(); String otherPk; String thisPk; try { Method m = modelClass.getMethod("getMetaModel"); MetaModel mm = (MetaModel) m.invoke(modelClass); thisPk = mm.getIdName(); m = otherClass.getMethod("getMetaModel"); mm = (MetaModel) m.invoke(otherClass); otherPk = mm.getIdName(); } catch (Exception e) { throw new InitException("failed to determine PK name in many to many relationship", e); } Association many2many1 = new Many2ManyAssociation(modelClass, otherClass, join, sourceFKName, targetFKName, otherPk); metaModels.getMetaModel(source).addAssociation(many2many1); Association many2many2 = new Many2ManyAssociation(otherClass, modelClass, join, targetFKName, sourceFKName, thisPk); metaModels.getMetaModel(target).addAssociation(many2many2); } private void processOverridesBelongsTo(Class<? extends Model> modelClass, BelongsTo belongsToAnnotation) { if(belongsToAnnotation != null){ Class<? extends Model> parentClass = belongsToAnnotation.parent(); String foreignKeyName = belongsToAnnotation.foreignKeyName(); if (metaModels.getMetaModel(parentClass).hasAssociation(modelClass, OneToManyAssociation.class)) { LogFilter.log(LOGGER, LogLevel.WARNING, "Redundant annotations used: @BelongsTo and @HasMany on a " + "relationship between Model {} and Model {}.", modelClass.getName(), parentClass.getName()); return; } Association hasMany = new OneToManyAssociation(parentClass, modelClass, foreignKeyName); Association belongsTo = new BelongsToAssociation(modelClass, parentClass, foreignKeyName); metaModels.getMetaModel(parentClass).addAssociation(hasMany); metaModels.getMetaModel(modelClass).addAssociation(belongsTo); } } private void processOverridesHasMany(Class<? extends Model> modelClass, HasMany hasManyAnnotation) { if(hasManyAnnotation != null){ Class<? extends Model> childClass = hasManyAnnotation.child(); String foreignKeyName = hasManyAnnotation.foreignKeyName(); if (metaModels.getMetaModel(childClass).hasAssociation(modelClass, OneToManyAssociation.class)) { LogFilter.log(LOGGER, LogLevel.WARNING, "Redundant annotations used: @BelongsTo and @HasMany on a " + "relationship between Model {} and Model {}.", modelClass.getName(), childClass.getName()); return; } Association hasMany = new OneToManyAssociation(modelClass, childClass, foreignKeyName); Association belongsTo = new BelongsToAssociation(childClass, modelClass, foreignKeyName); metaModels.getMetaModel(modelClass).addAssociation(hasMany); metaModels.getMetaModel(childClass).addAssociation(belongsTo); } } private Map<String, ColumnMetadata> getColumns(ResultSet rs, String dbType) throws SQLException { Map<String, ColumnMetadata> columns = new CaseInsensitiveMap<>(); while (rs.next()) { // skip h2 INFORMATION_SCHEMA table columns. if (!"h2".equalsIgnoreCase(dbType) || !"INFORMATION_SCHEMA".equals(rs.getString("TABLE_SCHEM"))) { ColumnMetadata cm = new ColumnMetadata(rs.getString("COLUMN_NAME"), rs.getString("TYPE_NAME"), rs.getInt("COLUMN_SIZE")); columns.put(cm.getColumnName(), cm); } } return columns; } private void discoverAssociationsFor(String source, String dbName) { discoverOne2ManyAssociationsFor(source, dbName); discoverMany2ManyAssociationsFor(source, dbName); } private void discoverMany2ManyAssociationsFor(String source, String dbName) { for (String potentialJoinTable : metaModels.getTableNames(dbName)) { String target = Inflector.getOtherName(source, potentialJoinTable); if (target != null && getMetaModel(target) != null && hasForeignKeys(potentialJoinTable, source, target)) { Class<? extends Model> sourceModelClass = metaModels.getModelClass(source); Class<? extends Model> targetModelClass = metaModels.getModelClass(target); Association associationSource = new Many2ManyAssociation(sourceModelClass, targetModelClass, potentialJoinTable, getMetaModel(source).getFKName(), getMetaModel(target).getFKName()); getMetaModel(source).addAssociation(associationSource); } } } /** * Checks that the "join" table has foreign keys from "source" and "other" tables. Returns true * if "join" table exists and contains foreign keys of "source" and "other" tables, false otherwise. * * @param join - potential name of a join table. * @param source name of a "source" table * @param other name of "other" table. * @return true if "join" table exists and contains foreign keys of "source" and "other" tables, false otherwise. */ private boolean hasForeignKeys(String join, String source, String other) { String sourceFKName = getMetaModel(source).getFKName(); String otherFKName = getMetaModel(other).getFKName(); MetaModel joinMM = getMetaModel(join); return joinMM.hasAttribute(sourceFKName) && joinMM.hasAttribute(otherFKName); } /** * Discover many to many associations. * * @param source name of table for which associations are searched. */ private void discoverOne2ManyAssociationsFor(String source, String dbName) { MetaModel sourceMM = getMetaModel(source); for (String target : metaModels.getTableNames(dbName)) { MetaModel targetMM = getMetaModel(target); String sourceFKName = getMetaModel(source).getFKName(); if (targetMM != sourceMM && targetMM.hasAttribute(sourceFKName)) { Class<? extends Model> sourceModelClass = metaModels.getModelClass(source); Class<? extends Model> targetModelClass = metaModels.getModelClass(target); targetMM.addAssociation(new BelongsToAssociation(targetModelClass, sourceModelClass, sourceFKName)); sourceMM.addAssociation(new OneToManyAssociation(sourceModelClass, targetModelClass, sourceFKName)); } } } /** * Returns model class for a table name, null if not found. * * @param table table name * @param suppressException true to suppress exception * @return model class for a table name, null if not found.s */ protected Class<? extends Model> getModelClass(String table, boolean suppressException) { Class<? extends Model> modelClass = metaModels.getModelClass(table); if(modelClass == null && !suppressException){ throw new InitException("failed to locate meta model for: " + table + ", are you sure this is correct table name?"); }else{ return modelClass; } } protected String getTableName(Class<? extends Model> modelClass) { init(MetaModel.getDbName(modelClass)); String tableName = metaModels.getTableName(modelClass); if (tableName == null) { throw new DBException("failed to find metamodel for " + modelClass + ". Are you sure that a corresponding table exists in DB?"); } return tableName; } /** * Returns edges for a join. An edge is a table in a many to many relationship that is not a join. * * We have to go through all the associations here because join tables, (even if the model exists) will not * have associations to the edges. * * @param join name of join table; * @return edges for a join */ protected List<String> getEdges(String join) { return metaModels.getEdges(join); } private void registerColumnMetadata(String table, Map<String, ColumnMetadata> metaParams) { metaModels.setColumnMetadata(table, metaParams); } }
activejdbc/src/main/java/org/javalite/activejdbc/Registry.java
/* Copyright 2009-2018 Igor Polevoy 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.javalite.activejdbc; import org.javalite.activejdbc.annotations.*; import org.javalite.activejdbc.associations.*; import org.javalite.activejdbc.cache.CacheManager; import org.javalite.activejdbc.cache.QueryCache; import org.javalite.activejdbc.logging.LogFilter; import org.javalite.activejdbc.logging.LogLevel; import org.javalite.activejdbc.statistics.StatisticsQueue; import java.lang.reflect.Method; import java.sql.DatabaseMetaData; import java.util.*; import java.sql.SQLException; import java.sql.Connection; import java.sql.ResultSet; import org.javalite.common.Inflector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Igor Polevoy * @author Eric Nielsen */ public enum Registry { //our singleton! INSTANCE; private static final Logger LOGGER = LoggerFactory.getLogger(Registry.class); private final MetaModels metaModels = new MetaModels(); private final Map<Class, ModelRegistry> modelRegistries = new HashMap<>(); private final Configuration configuration = new Configuration(); private final StatisticsQueue statisticsQueue; private final Set<String> initedDbs = new HashSet<>(); private Registry() { statisticsQueue = configuration.collectStatistics() ? new StatisticsQueue(configuration.collectStatisticsOnHold()) : null; } /** * @deprecated Not used anymore. */ @Deprecated public boolean initialized() { // This will return true if AT LEAST ONE DB was initialized, not if ALL were (if there are more than one). // Hopefully this is not used anywhere. return !initedDbs.isEmpty(); } public static Registry instance() { return INSTANCE; } public StatisticsQueue getStatisticsQueue() { if (statisticsQueue == null) { throw new InitException("cannot collect statistics if this was not configured in activejdbc.properties file. Add 'collectStatistics = true' to it."); } return statisticsQueue; } public Configuration getConfiguration(){ return configuration; } public static CacheManager cacheManager(){ return QueryCache.instance().getCacheManager(); } /** * Provides a MetaModel of a model representing a table. * * @param table name of table represented by this MetaModel. * @return MetaModel of a model representing a table. */ public MetaModel getMetaModel(String table) { return metaModels.getMetaModel(table); } public MetaModel getMetaModel(Class<? extends Model> modelClass) { String dbName = MetaModel.getDbName(modelClass); init(dbName); return metaModels.getMetaModel(modelClass); } ModelRegistry modelRegistryOf(Class<? extends Model> modelClass) { ModelRegistry registry = modelRegistries.get(modelClass); if (registry == null) { registry = new ModelRegistry(); modelRegistries.put(modelClass, registry); } return registry; } synchronized void init(String dbName) { if (initedDbs.contains(dbName)) { return; } else { initedDbs.add(dbName); } try { ModelFinder.findModels(dbName); Connection c = ConnectionsAccess.getConnection(dbName); if(c == null){ throw new DBException("Failed to retrieve metadata from DB, connection: '" + dbName + "' is not available"); } DatabaseMetaData databaseMetaData = c.getMetaData(); String dbType = c.getMetaData().getDatabaseProductName(); List<Class<? extends Model>> modelClasses = ModelFinder.getModelsForDb(dbName); registerModels(dbName, modelClasses, dbType); String[] tables = metaModels.getTableNames(dbName); for (String table : tables) { Map<String, ColumnMetadata> metaParams = fetchMetaParams(databaseMetaData, dbType, table); registerColumnMetadata(table, metaParams); } for (String table : tables) { discoverAssociationsFor(table, dbName); } processOverrides(modelClasses); } catch (Exception e) { initedDbs.remove(dbName); if (e instanceof InitException) { throw (InitException) e; } if (e instanceof DBException) { throw (DBException) e; } else { throw new InitException(e); } } } /** * Returns a hash keyed off a column name. */ private Map<String, ColumnMetadata> fetchMetaParams(DatabaseMetaData databaseMetaData, String dbType, String table) throws SQLException { /* * Valid table name format: tablename or schemaname.tablename */ String[] names = table.split("\\.", 3); String schema = null; String tableName; switch (names.length) { case 1: tableName = names[0]; break; case 2: schema = names[0]; tableName = names[1]; if (schema.isEmpty() || tableName.isEmpty()) { throw new DBException("invalid table name : " + table); } break; default: throw new DBException("invalid table name: " + table); } if (schema == null) { try { schema = databaseMetaData.getConnection().getSchema(); } catch (Error | Exception ignore ) {} } String catalog = null; if(dbType.equalsIgnoreCase("mysql")){ catalog = schema; } if(dbType.equalsIgnoreCase("h2")){ String url = databaseMetaData.getURL(); catalog = url.substring(url.lastIndexOf(":") + 1).toUpperCase(); schema = schema != null ? schema.toUpperCase() : null; // keep quoted table names as is, otherwise use uppercase if (!tableName.contains("\"")) { tableName = tableName.toUpperCase(); } else if(tableName.startsWith("\"") && tableName.endsWith("\"")) { tableName = tableName.substring(1, tableName.length() - 1); } } if(dbType.toLowerCase().contains("postgres") && tableName.startsWith("\"") && tableName.endsWith("\"")){ tableName = tableName.substring(1, tableName.length() - 1); } ResultSet rs = databaseMetaData.getColumns(catalog, schema, tableName, null); Map<String, ColumnMetadata> columns = getColumns(rs, dbType); rs.close(); //try upper case table name - Oracle uses upper case if (columns.isEmpty()) { rs = databaseMetaData.getColumns(null, schema, tableName.toUpperCase(), null); columns = getColumns(rs, dbType); rs.close(); } //if upper case not found, try lower case. if (columns.isEmpty()) { rs = databaseMetaData.getColumns(null, schema, tableName.toLowerCase(), null); columns = getColumns(rs, dbType); rs.close(); } if(columns.size() > 0){ LogFilter.log(LOGGER, LogLevel.INFO, "Fetched metadata for table: {}", table); } else{ LogFilter.log(LOGGER, LogLevel.WARNING, "Failed to retrieve metadata for table: '{}'." + " Are you sure this table exists? For some databases table names are case sensitive.", table); } return columns; } /** * * @param modelClasses * @param dbType this is a name of a DBMS as returned by JDBC driver, such as Oracle, MySQL, etc. */ private void registerModels(String dbName, List<Class<? extends Model>> modelClasses, String dbType) { for (Class<? extends Model> modelClass : modelClasses) { MetaModel mm = new MetaModel(dbName, modelClass, dbType); metaModels.addMetaModel(mm, modelClass); LogFilter.log(LOGGER, LogLevel.INFO, "Registered model: {}", modelClass); } } private void processOverrides(List<Class<? extends Model>> models) { for(Class<? extends Model> modelClass : models){ BelongsTo belongsToAnnotation = modelClass.getAnnotation(BelongsTo.class); processOverridesBelongsTo(modelClass, belongsToAnnotation); BelongsToParents belongsToParentAnnotation = modelClass.getAnnotation(BelongsToParents.class); if (belongsToParentAnnotation != null){ for (BelongsTo belongsTo : belongsToParentAnnotation.value()){ processOverridesBelongsTo(modelClass, belongsTo); } } HasMany hasManyAnnotation = modelClass.getAnnotation(HasMany.class); processOverridesHasMany(modelClass, hasManyAnnotation); Many2Manies many2ManiesAnnotation = modelClass.getAnnotation(Many2Manies.class); if (many2ManiesAnnotation != null) { for (Many2Many many2Many : many2ManiesAnnotation.value()) { processManyToManyOverrides(many2Many, modelClass); } } Many2Many many2manyAnnotation = modelClass.getAnnotation(Many2Many.class); if(many2manyAnnotation != null){ processManyToManyOverrides(many2manyAnnotation, modelClass); } BelongsToPolymorphic belongsToPolymorphic = modelClass.getAnnotation(BelongsToPolymorphic.class); if(belongsToPolymorphic != null){ processPolymorphic(belongsToPolymorphic, modelClass); } UnrelatedTo unrelatedTo = modelClass.getAnnotation(UnrelatedTo .class); if(unrelatedTo != null){ processUnrelatedTo(unrelatedTo, modelClass); } } } private void processUnrelatedTo(UnrelatedTo unrelatedTo, Class<? extends Model> modelClass) { Class<? extends Model>[] related = unrelatedTo.value(); for (Class<? extends Model> relatedClass : related) { MetaModel relatedMM = metaModels.getMetaModel(relatedClass); MetaModel thisMM = metaModels.getMetaModel(modelClass); if(relatedMM != null){ Association association = relatedMM.getAssociationForTarget(modelClass); relatedMM.removeAssociationForTarget(modelClass); if(association != null){ LogFilter.log(LOGGER, LogLevel.INFO, "Removed association: " + association); } } Association association = thisMM.getAssociationForTarget(relatedClass); thisMM.removeAssociationForTarget(relatedClass); if(association != null){ LogFilter.log(LOGGER, LogLevel.INFO, "Removed association: " + association); } } } private void processPolymorphic(BelongsToPolymorphic belongsToPolymorphic, Class<? extends Model> modelClass ) { Class<? extends Model>[] parentClasses = belongsToPolymorphic.parents(); String[] typeLabels = belongsToPolymorphic.typeLabels(); if (typeLabels.length > 0 && typeLabels.length != parentClasses.length) { throw new InitException("must provide all type labels for polymorphic associations"); } for (int i = 0, parentClassesLength = parentClasses.length; i < parentClassesLength; i++) { Class<? extends Model> parentClass = parentClasses[i]; String typeLabel = typeLabels.length > 0 ? typeLabels[i] : parentClass.getName(); BelongsToPolymorphicAssociation belongsToPolymorphicAssociation = new BelongsToPolymorphicAssociation(modelClass, parentClass, typeLabel, parentClass.getName()); metaModels.getMetaModel(modelClass).addAssociation(belongsToPolymorphicAssociation); OneToManyPolymorphicAssociation oneToManyPolymorphicAssociation = new OneToManyPolymorphicAssociation(parentClass, modelClass, typeLabel); metaModels.getMetaModel(parentClass).addAssociation(oneToManyPolymorphicAssociation); } } private void processManyToManyOverrides(Many2Many many2manyAnnotation, Class<? extends Model> modelClass){ Class<? extends Model> otherClass = many2manyAnnotation.other(); String source = getTableName(modelClass); String target = getTableName(otherClass); String join = many2manyAnnotation.join(); String sourceFKName = many2manyAnnotation.sourceFKName(); String targetFKName = many2manyAnnotation.targetFKName(); String otherPk; String thisPk; try { Method m = modelClass.getMethod("getMetaModel"); MetaModel mm = (MetaModel) m.invoke(modelClass); thisPk = mm.getIdName(); m = otherClass.getMethod("getMetaModel"); mm = (MetaModel) m.invoke(otherClass); otherPk = mm.getIdName(); } catch (Exception e) { throw new InitException("failed to determine PK name in many to many relationship", e); } Association many2many1 = new Many2ManyAssociation(modelClass, otherClass, join, sourceFKName, targetFKName, otherPk); metaModels.getMetaModel(source).addAssociation(many2many1); Association many2many2 = new Many2ManyAssociation(otherClass, modelClass, join, targetFKName, sourceFKName, thisPk); metaModels.getMetaModel(target).addAssociation(many2many2); } private void processOverridesBelongsTo(Class<? extends Model> modelClass, BelongsTo belongsToAnnotation) { if(belongsToAnnotation != null){ Class<? extends Model> parentClass = belongsToAnnotation.parent(); String foreignKeyName = belongsToAnnotation.foreignKeyName(); if (metaModels.getMetaModel(parentClass).hasAssociation(modelClass, OneToManyAssociation.class)) { LogFilter.log(LOGGER, LogLevel.WARNING, "Redundant annotations used: @BelongsTo and @HasMany on a " + "relationship between Model {} and Model {}.", modelClass.getName(), parentClass.getName()); return; } Association hasMany = new OneToManyAssociation(parentClass, modelClass, foreignKeyName); Association belongsTo = new BelongsToAssociation(modelClass, parentClass, foreignKeyName); metaModels.getMetaModel(parentClass).addAssociation(hasMany); metaModels.getMetaModel(modelClass).addAssociation(belongsTo); } } private void processOverridesHasMany(Class<? extends Model> modelClass, HasMany hasManyAnnotation) { if(hasManyAnnotation != null){ Class<? extends Model> childClass = hasManyAnnotation.child(); String foreignKeyName = hasManyAnnotation.foreignKeyName(); if (metaModels.getMetaModel(childClass).hasAssociation(modelClass, OneToManyAssociation.class)) { LogFilter.log(LOGGER, LogLevel.WARNING, "Redundant annotations used: @BelongsTo and @HasMany on a " + "relationship between Model {} and Model {}.", modelClass.getName(), childClass.getName()); return; } Association hasMany = new OneToManyAssociation(modelClass, childClass, foreignKeyName); Association belongsTo = new BelongsToAssociation(childClass, modelClass, foreignKeyName); metaModels.getMetaModel(modelClass).addAssociation(hasMany); metaModels.getMetaModel(childClass).addAssociation(belongsTo); } } private Map<String, ColumnMetadata> getColumns(ResultSet rs, String dbType) throws SQLException { Map<String, ColumnMetadata> columns = new CaseInsensitiveMap<>(); while (rs.next()) { // skip h2 INFORMATION_SCHEMA table columns. if (!"h2".equals(dbType) || !"INFORMATION_SCHEMA".equals(rs.getString("TABLE_SCHEM"))) { ColumnMetadata cm = new ColumnMetadata(rs.getString("COLUMN_NAME"), rs.getString("TYPE_NAME"), rs.getInt("COLUMN_SIZE")); columns.put(cm.getColumnName(), cm); } } return columns; } private void discoverAssociationsFor(String source, String dbName) { discoverOne2ManyAssociationsFor(source, dbName); discoverMany2ManyAssociationsFor(source, dbName); } private void discoverMany2ManyAssociationsFor(String source, String dbName) { for (String potentialJoinTable : metaModels.getTableNames(dbName)) { String target = Inflector.getOtherName(source, potentialJoinTable); if (target != null && getMetaModel(target) != null && hasForeignKeys(potentialJoinTable, source, target)) { Class<? extends Model> sourceModelClass = metaModels.getModelClass(source); Class<? extends Model> targetModelClass = metaModels.getModelClass(target); Association associationSource = new Many2ManyAssociation(sourceModelClass, targetModelClass, potentialJoinTable, getMetaModel(source).getFKName(), getMetaModel(target).getFKName()); getMetaModel(source).addAssociation(associationSource); } } } /** * Checks that the "join" table has foreign keys from "source" and "other" tables. Returns true * if "join" table exists and contains foreign keys of "source" and "other" tables, false otherwise. * * @param join - potential name of a join table. * @param source name of a "source" table * @param other name of "other" table. * @return true if "join" table exists and contains foreign keys of "source" and "other" tables, false otherwise. */ private boolean hasForeignKeys(String join, String source, String other) { String sourceFKName = getMetaModel(source).getFKName(); String otherFKName = getMetaModel(other).getFKName(); MetaModel joinMM = getMetaModel(join); return joinMM.hasAttribute(sourceFKName) && joinMM.hasAttribute(otherFKName); } /** * Discover many to many associations. * * @param source name of table for which associations are searched. */ private void discoverOne2ManyAssociationsFor(String source, String dbName) { MetaModel sourceMM = getMetaModel(source); for (String target : metaModels.getTableNames(dbName)) { MetaModel targetMM = getMetaModel(target); String sourceFKName = getMetaModel(source).getFKName(); if (targetMM != sourceMM && targetMM.hasAttribute(sourceFKName)) { Class<? extends Model> sourceModelClass = metaModels.getModelClass(source); Class<? extends Model> targetModelClass = metaModels.getModelClass(target); targetMM.addAssociation(new BelongsToAssociation(targetModelClass, sourceModelClass, sourceFKName)); sourceMM.addAssociation(new OneToManyAssociation(sourceModelClass, targetModelClass, sourceFKName)); } } } /** * Returns model class for a table name, null if not found. * * @param table table name * @param suppressException true to suppress exception * @return model class for a table name, null if not found.s */ protected Class<? extends Model> getModelClass(String table, boolean suppressException) { Class<? extends Model> modelClass = metaModels.getModelClass(table); if(modelClass == null && !suppressException){ throw new InitException("failed to locate meta model for: " + table + ", are you sure this is correct table name?"); }else{ return modelClass; } } protected String getTableName(Class<? extends Model> modelClass) { init(MetaModel.getDbName(modelClass)); String tableName = metaModels.getTableName(modelClass); if (tableName == null) { throw new DBException("failed to find metamodel for " + modelClass + ". Are you sure that a corresponding table exists in DB?"); } return tableName; } /** * Returns edges for a join. An edge is a table in a many to many relationship that is not a join. * * We have to go through all the associations here because join tables, (even if the model exists) will not * have associations to the edges. * * @param join name of join table; * @return edges for a join */ protected List<String> getEdges(String join) { return metaModels.getEdges(join); } private void registerColumnMetadata(String table, Map<String, ColumnMetadata> metaParams) { metaModels.setColumnMetadata(table, metaParams); } }
small case fix, thanks Andrey
activejdbc/src/main/java/org/javalite/activejdbc/Registry.java
small case fix, thanks Andrey
Java
apache-2.0
1e6c1e46afbcfc8f0f3e4255f4dc14ae29fbdc60
0
stagemonitor/stagemonitor,stagemonitor/stagemonitor,stagemonitor/stagemonitor,stagemonitor/stagemonitor
package org.stagemonitor.configuration; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.core.type.TypeReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.stagemonitor.configuration.converter.BooleanValueConverter; import org.stagemonitor.configuration.converter.ClassInstanceValueConverter; import org.stagemonitor.configuration.converter.DoubleValueConverter; import org.stagemonitor.configuration.converter.EnumValueConverter; import org.stagemonitor.configuration.converter.IntegerValueConverter; import org.stagemonitor.configuration.converter.JsonValueConverter; import org.stagemonitor.configuration.converter.ListValueConverter; import org.stagemonitor.configuration.converter.LongValueConverter; import org.stagemonitor.configuration.converter.MapValueConverter; import org.stagemonitor.configuration.converter.OptionalValueConverter; import org.stagemonitor.configuration.converter.RegexValueConverter; import org.stagemonitor.configuration.converter.SetValueConverter; import org.stagemonitor.configuration.converter.StringValueConverter; import org.stagemonitor.configuration.converter.UrlValueConverter; import org.stagemonitor.configuration.converter.ValueConverter; import org.stagemonitor.configuration.source.ConfigurationSource; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.ServiceLoader; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.regex.Pattern; /** * Represents a configuration option * * @param <T> the type of the configuration value */ public class ConfigurationOption<T> { private final Logger logger = LoggerFactory.getLogger(getClass()); private final boolean dynamic; private final boolean sensitive; private final String key; private final List<String> aliasKeys; private final List<String> allKeys; private final String label; private final String description; private final T defaultValue; private final List<String> tags; private final List<Validator<T>> validators; private final List<ChangeListener<T>> changeListeners; private final boolean required; private final String defaultValueAsString; private final String configurationCategory; @JsonIgnore private final ValueConverter<T> valueConverter; private final Class<? super T> valueType; // key: validOptionAsString, value: label private final Map<String, String> validOptions; private volatile List<ConfigurationSource> configurationSources; private volatile ConfigurationRegistry configuration; private volatile String errorMessage; private volatile OptionValue<T> optionValue; public static class OptionValue<T> { private final T value; private final String valueAsString; private final String nameOfCurrentConfigurationSource; private final String usedKey; OptionValue(T value, String valueAsString, String nameOfCurrentConfigurationSource, String usedKey) { this.value = value; this.valueAsString = valueAsString; this.nameOfCurrentConfigurationSource = nameOfCurrentConfigurationSource; this.usedKey = usedKey; } public T getValue() { return value; } public String getValueAsString() { return valueAsString; } public String getNameOfCurrentConfigurationSource() { return nameOfCurrentConfigurationSource; } public String getUsedKey() { return usedKey; } } public static <T> ConfigurationOptionBuilder<T> builder(ValueConverter<T> valueConverter, Class<? super T> valueType) { return new ConfigurationOptionBuilder<T>(valueConverter, valueType); } /** * Constructs a {@link ConfigurationOptionBuilder} whose value is of type {@link String} * * @return a {@link ConfigurationOptionBuilder} whose value is of type {@link String} */ public static ConfigurationOptionBuilder<String> stringOption() { return new ConfigurationOptionBuilder<String>(StringValueConverter.INSTANCE, String.class); } public static <T> ConfigurationOptionBuilder<T> jsonOption(TypeReference<T> typeReference, Class<? super T> clazz) { return new ConfigurationOptionBuilder<T>(new JsonValueConverter<T>(typeReference), clazz); } /** * Constructs a {@link ConfigurationOptionBuilder} whose value is of type {@link Boolean} * * @return a {@link ConfigurationOptionBuilder} whose value is of type {@link Boolean} */ public static ConfigurationOptionBuilder<Boolean> booleanOption() { return new ConfigurationOptionBuilder<Boolean>(BooleanValueConverter.INSTANCE, Boolean.class); } /** * Constructs a {@link ConfigurationOptionBuilder} whose value is of type {@link Integer} * * @return a {@link ConfigurationOptionBuilder} whose value is of type {@link Integer} */ public static ConfigurationOptionBuilder<Integer> integerOption() { return new ConfigurationOptionBuilder<Integer>(IntegerValueConverter.INSTANCE, Integer.class); } /** * Constructs a {@link ConfigurationOptionBuilder} whose value is of type {@link Long} * * @return a {@link ConfigurationOptionBuilder} whose value is of type {@link Long} */ public static ConfigurationOptionBuilder<Long> longOption() { return new ConfigurationOptionBuilder<Long>(LongValueConverter.INSTANCE, Long.class); } /** * Constructs a {@link ConfigurationOptionBuilder} whose value is of type {@link Double} * * @return a {@link ConfigurationOptionBuilder} whose value is of type {@link Double} */ public static ConfigurationOptionBuilder<Double> doubleOption() { return new ConfigurationOptionBuilder<Double>(DoubleValueConverter.INSTANCE, Double.class); } /** * Constructs a {@link ConfigurationOptionBuilder} whose value is of type {@link List}&lt;{@link String}&gt; * * @return a {@link ConfigurationOptionBuilder} whose value is of type {@link List}&lt;{@link String}&gt; */ public static ConfigurationOptionBuilder<Collection<String>> stringsOption() { return new ConfigurationOptionBuilder<Collection<String>>(SetValueConverter.STRINGS_VALUE_CONVERTER, Collection.class) .defaultValue(Collections.<String>emptySet()); } /** * Constructs a {@link ConfigurationOptionBuilder} whose value is of type {@link List}&lt;{@link String}&gt; and all * Strings are converted to lower case. * * @return a {@link ConfigurationOptionBuilder} whose value is of type {@link List}&lt;{@link String}&gt; */ public static ConfigurationOptionBuilder<Collection<String>> lowerStringsOption() { return new ConfigurationOptionBuilder<Collection<String>>(SetValueConverter.LOWER_STRINGS_VALUE_CONVERTER, Collection.class) .defaultValue(Collections.<String>emptySet()); } /** * Constructs a {@link ConfigurationOptionBuilder} whose value is of type {@link Set}&lt;{@link Integer}&gt; * * @return a {@link ConfigurationOptionBuilder} whose value is of type {@link Set}&lt;{@link Integer}&gt; */ public static ConfigurationOption.ConfigurationOptionBuilder<Collection<Integer>> integersOption() { return ConfigurationOption.builder(SetValueConverter.INTEGERS, Collection.class); } /** * Constructs a {@link ConfigurationOptionBuilder} whose value is of type {@link List}&lt;{@link Pattern}&gt; * * @return a {@link ConfigurationOptionBuilder} whose value is of type {@link List}&lt;{@link Pattern}&gt; */ public static ConfigurationOptionBuilder<Collection<Pattern>> regexListOption() { return new ConfigurationOptionBuilder<Collection<Pattern>>(new SetValueConverter<Pattern>(RegexValueConverter.INSTANCE), Collection.class) .defaultValue(Collections.<Pattern>emptySet()); } /** * Constructs a {@link ConfigurationOptionBuilder} whose value is of type {@link Map}&lt;{@link Pattern}, {@link * String}&gt; * * @return a {@link ConfigurationOptionBuilder} whose value is of type {@link Map}&lt;{@link Pattern}, {@link * String}&gt; */ public static ConfigurationOptionBuilder<Map<Pattern, String>> regexMapOption() { return new ConfigurationOptionBuilder<Map<Pattern, String>>(MapValueConverter.REGEX_MAP_VALUE_CONVERTER, Map.class) .defaultValue(Collections.<Pattern, String>emptyMap()); } /** * Constructs a {@link ConfigurationOptionBuilder} whose value is of type {@link Map} * * @return a {@link ConfigurationOptionBuilder} whose value is of type {@link Map} */ public static <K, V> ConfigurationOptionBuilder<Map<K, V>> mapOption(ValueConverter<K> keyConverter, ValueConverter<V> valueConverter) { return new ConfigurationOptionBuilder<Map<K, V>>(new MapValueConverter<K, V>(keyConverter, valueConverter), Map.class) .defaultValue(Collections.<K, V>emptyMap()); } /** * Constructs a {@link ConfigurationOptionBuilder} whose value is an {@link Enum} * * @return a {@link ConfigurationOptionBuilder} whose value is an {@link Enum} */ public static <T extends Enum<T>> ConfigurationOptionBuilder<T> enumOption(Class<T> clazz) { final ConfigurationOptionBuilder<T> optionBuilder = new ConfigurationOptionBuilder<T>(new EnumValueConverter<T>(clazz), clazz); for (T enumConstant : clazz.getEnumConstants()) { optionBuilder.addValidOption(enumConstant); } optionBuilder.sealValidOptions(); return optionBuilder; } /** * Adds a configuration option for intended classes loaded by {@link ServiceLoader}s * * <p>Restricts the {@link #validOptions} to the class names of the {@link ServiceLoader} implementations of the * provided service loader interface.</p> * * <p> Note that the implementations have to be registered in {@code META-INF/services/{serviceLoaderInterface.getName()}}</p> */ public static <T> ConfigurationOptionBuilder<T> serviceLoaderStrategyOption(Class<T> serviceLoaderInterface) { final ConfigurationOptionBuilder<T> optionBuilder = new ConfigurationOptionBuilder<T>(ClassInstanceValueConverter.of(serviceLoaderInterface), serviceLoaderInterface); for (T impl : ServiceLoader.load(serviceLoaderInterface, ConfigurationOption.class.getClassLoader())) { optionBuilder.addValidOption(impl); } optionBuilder.sealValidOptions(); return optionBuilder; } /** * Constructs a {@link ConfigurationOptionBuilder} whose value is of type {@link String} * * @return a {@link ConfigurationOptionBuilder} whose value is of type {@link String} */ public static ConfigurationOptionBuilder<URL> urlOption() { return new ConfigurationOptionBuilder<URL>(UrlValueConverter.INSTANCE, URL.class); } /** * Constructs a {@link ConfigurationOptionBuilder} whose value is of type {@link String} * * @return a {@link ConfigurationOptionBuilder} whose value is of type {@link String} */ public static ConfigurationOptionBuilder<List<URL>> urlsOption() { return new ConfigurationOptionBuilder<List<URL>>(new ListValueConverter<URL>(UrlValueConverter.INSTANCE), List.class) .defaultValue(Collections.<URL>emptyList()); } private ConfigurationOption(boolean dynamic, boolean sensitive, String key, String label, String description, T defaultValue, String configurationCategory, final ValueConverter<T> valueConverter, Class<? super T> valueType, List<String> tags, boolean required, List<ChangeListener<T>> changeListeners, List<Validator<T>> validators, List<String> aliasKeys, final Map<String, String> validOptions) { this.dynamic = dynamic; this.key = key; this.aliasKeys = aliasKeys; this.label = label; this.description = description; this.defaultValue = defaultValue; this.tags = tags; validators = new ArrayList<Validator<T>>(validators); if (validOptions != null) { this.validOptions = Collections.unmodifiableMap(new LinkedHashMap<String, String>(validOptions)); validators.add(new ValidOptionValidator<T>(validOptions.keySet(), valueConverter)); } else { this.validOptions = null; } this.validators = Collections.unmodifiableList(new ArrayList<Validator<T>>(validators)); this.defaultValueAsString = valueConverter.toString(defaultValue); this.configurationCategory = configurationCategory; this.valueConverter = valueConverter; this.valueType = valueType; this.sensitive = sensitive; this.required = required; this.changeListeners = new CopyOnWriteArrayList<ChangeListener<T>>(changeListeners); setToDefault(); final ArrayList<String> tempAllKeys = new ArrayList<String>(aliasKeys.size() + 1); tempAllKeys.add(key); tempAllKeys.addAll(aliasKeys); this.allKeys = Collections.unmodifiableList(tempAllKeys); } /** * Returns <code>true</code>, if the value can dynamically be set, <code>false</code> otherwise. * * @return <code>true</code>, if the value can dynamically be set, <code>false</code> otherwise. */ public boolean isDynamic() { return dynamic; } /** * Returns the key of the configuration option that can for example be used in a properties file * * @return the config key */ public String getKey() { return key; } /** * Returns the alternate keys of the configuration option that can for example be used in a properties file * * @return the alternate config keys */ public List<String> getAliasKeys() { return Collections.unmodifiableList(aliasKeys); } /** * Returns the display name of this configuration option * * @return the display name of this configuration option */ public String getLabel() { return label; } /** * Returns the description of the configuration option * * @return the description of the configuration option */ public String getDescription() { return description; } /** * Returns the default value in its string representation * * @return the default value as string */ public String getDefaultValueAsString() { return defaultValueAsString; } /** * Returns the current in its string representation * * @return the current value as string */ public String getValueAsString() { return optionValue.valueAsString; } public String getValueAsSafeString() { return valueConverter.toSafeString(optionValue.value); } /** * Returns <code>true</code>, if the value is sensitive, <code>false</code> otherwise. If a value has sensitive * content (e.g. password), it should be rendered as an input of type="password", rather then as type="text". * * @return Returns <code>true</code>, if the value is sensitive, <code>false</code> otherwise. */ public boolean isSensitive() { return sensitive; } /** * Returns the current value * * @return the current value */ @JsonIgnore public T getValue() { return optionValue.value; } /** * Returns the current value * * @return the current value */ @JsonIgnore public T get() { return getValue(); } /** * Returns an immutable snapshot of the {@link OptionValue}. * This makes sure to get a consistent snapshot of all the related values without the risk of partially applied updates. * This means that {@link OptionValue#getValue()} and {@link OptionValue#getValueAsString()} are always in sync, * which is not guaranteed if subsequently calling {@link #getValue()} and {@link #getValueAsString()} * because there could be a concurrent update between those reads. * * @return an immutable snapshot of the {@link OptionValue} */ @JsonIgnore public OptionValue<T> getOptionValue() { return optionValue; } void setConfigurationSources(List<ConfigurationSource> configurationSources) { this.configurationSources = configurationSources; loadValue(); } void setConfiguration(ConfigurationRegistry configuration) { this.configuration = configuration; } /** * Returns the name of the configuration source that provided the current value * * @return the name of the configuration source that provided the current value */ public String getNameOfCurrentConfigurationSource() { return optionValue.nameOfCurrentConfigurationSource; } /** * Returns the category name of this configuration option * * @return the category name of this configuration option */ public String getConfigurationCategory() { return configurationCategory; } /** * Returns the tags associated with this configuration option * * @return the tags associated with this configuration option */ public List<String> getTags() { return Collections.unmodifiableList(tags); } /** * Returns the simple type name of the value * * @return the simple type name of the value */ public String getValueType() { return valueType.getSimpleName(); } public ValueConverter<T> getValueConverter() { return valueConverter; } /** * If there was a error while trying to set value from a {@link ConfigurationSource}, this error message contains * information about the error. * * @return a error message or null if there was no error */ public String getErrorMessage() { return errorMessage; } /** * Returns the valid values for this configuration option * * @return the valid values for this configuration option */ public Collection<String> getValidOptions() { if (validOptions == null) { return null; } return validOptions.keySet(); } public Map<String, String> getValidOptionsLabelMap() { return validOptions; } synchronized void reload(boolean reloadNonDynamicValues) { if (dynamic || reloadNonDynamicValues) { loadValue(); } } private void loadValue() { boolean success = false; for (String key : allKeys) { ConfigValueInfo configValueInfo = loadValueFromSources(key); success = trySetValue(configValueInfo, key); if (success) { break; } } if (!success) { setToDefault(); } } private ConfigValueInfo loadValueFromSources(String key) { for (ConfigurationSource configurationSource : configurationSources) { String newValueAsString = configurationSource.getValue(key); if (newValueAsString != null) { return new ConfigValueInfo(newValueAsString, configurationSource.getName()); } } return new ConfigValueInfo(); } private boolean trySetValue(ConfigValueInfo configValueInfo, String key) { final String newConfigurationSourceName = configValueInfo.getNewConfigurationSourceName(); String newValueAsString = configValueInfo.getNewValueAsString(); if (newValueAsString == null) { return false; } newValueAsString = newValueAsString.trim(); T oldValue = getValue(); if (hasChanges(newValueAsString)) { try { final T newValue = valueConverter.convert(newValueAsString); setValue(newValue, newValueAsString, newConfigurationSourceName, key); errorMessage = null; if (isInitialized()) { for (ChangeListener<T> changeListener : changeListeners) { try { changeListener.onChange(this, oldValue, getValue()); } catch (RuntimeException e) { logger.warn(e.getMessage() + " (this exception is ignored)", e); } } } return true; } catch (IllegalArgumentException e) { errorMessage = "Error in " + newConfigurationSourceName + ": " + e.getMessage(); logger.warn(errorMessage + " Default value '" + defaultValueAsString + "' for '" + key + "' will be applied."); return false; } } else { return true; } } private void setToDefault() { final String msg = "Missing required value for configuration option " + key; if (isInitialized() && required && defaultValue == null) { handleMissingRequiredValue(msg); } setValue(defaultValue, defaultValueAsString, "Default Value", key); } private boolean isInitialized() { return configuration != null; } private void handleMissingRequiredValue(String msg) { if (configuration.isFailOnMissingRequiredValues()) { throw new IllegalStateException(msg); } else { logger.warn(msg); } } private boolean hasChanges(String property) { return !property.equals(optionValue.valueAsString); } /** * Throws a {@link IllegalArgumentException} if the value is not valid * * @param valueAsString the configuration value as string * @throws IllegalArgumentException if there was a error while converting the value */ public void assertValid(String valueAsString) throws IllegalArgumentException { final T value = valueConverter.convert(valueAsString); for (Validator<T> validator : validators) { validator.assertValid(value); } } /** * Updates the existing value with a new one * * @param newValue the new value * @param configurationSourceName the name of the configuration source that the value should be saved to * @throws IOException if there was an error saving the key to the source * @throws IllegalArgumentException if there was a error processing the configuration key or value or the * configurationSourceName did not match any of the available configuration * sources * @throws UnsupportedOperationException if saving values is not possible with this configuration source */ public void update(T newValue, String configurationSourceName) throws IOException { final String newValueAsString = valueConverter.toString(newValue); configuration.save(key, newValueAsString, configurationSourceName); } private void setValue(T value, String valueAsString, String nameOfCurrentConfigurationSource, String key) { for (Validator<T> validator : validators) { validator.assertValid(value); } this.optionValue = new OptionValue<T>(value, valueAsString, nameOfCurrentConfigurationSource, key); } /** * Returns true if the current value is equal to the default value * * @return true if the current value is equal to the default value */ public boolean isDefault() { return (optionValue.valueAsString != null && optionValue.valueAsString.equals(defaultValueAsString)) || (optionValue.valueAsString == null && defaultValueAsString == null); } public void addChangeListener(ChangeListener<T> changeListener) { changeListeners.add(changeListener); } public boolean removeChangeListener(ChangeListener<T> changeListener) { return changeListeners.remove(changeListener); } /** * A {@link ConfigurationOption} can have multiple keys ({@link #key} and {@link #aliasKeys}). This method returns * the key which is used by the current configuration source ({@link OptionValue#nameOfCurrentConfigurationSource}). * * @return the used key of the current configuration source */ public String getUsedKey() { return optionValue.usedKey; } /** * Notifies about configuration changes */ public interface ChangeListener<T> { /** * @param configurationOption the configuration option which has just changed its value * @param oldValue the old value * @param newValue the new value */ void onChange(ConfigurationOption<?> configurationOption, T oldValue, T newValue); class OptionalChangeListenerAdapter<T> implements ChangeListener<Optional<T>> { private final ChangeListener<T> changeListener; public OptionalChangeListenerAdapter(ChangeListener<T> changeListener) { this.changeListener = changeListener; } @Override public void onChange(ConfigurationOption<?> configurationOption, Optional<T> oldValue, Optional<T> newValue) { changeListener.onChange(configurationOption, oldValue.orElse(null), newValue.orElse(null)); } } } public interface Validator<T> { /** * Validates a value * * @param value the value to be validated * @throws IllegalArgumentException if the value is invalid */ void assertValid(T value); class OptionalValidatorAdapter<T> implements Validator<Optional<T>> { private final Validator<T> validator; public OptionalValidatorAdapter(Validator<T> validator) { this.validator = validator; } @Override public void assertValid(Optional<T> value) { validator.assertValid(value.orElse(null)); } } } public static class ConfigurationOptionBuilder<T> { private boolean dynamic = false; private boolean sensitive = false; private String key; private String label; private String description; private T defaultValue; private String configurationCategory; private ValueConverter<T> valueConverter; private Class<? super T> valueType; private String[] tags = new String[0]; private boolean required = false; private List<ChangeListener<T>> changeListeners = new ArrayList<ChangeListener<T>>(); private List<Validator<T>> validators = new ArrayList<Validator<T>>(); private String[] aliasKeys = new String[0]; private Map<String, String> validOptions; private boolean validOptionsSealed = false; private ConfigurationOptionBuilder(ValueConverter<T> valueConverter, Class<? super T> valueType) { this.valueConverter = valueConverter; this.valueType = valueType; } /** * Be aware that when using this method you might have to deal with <code>null</code> values when calling {@link * #getValue()}. That's why this method is deprecated * * @deprecated use {@link #buildRequired()}, {@link #buildWithDefault(Object)} or {@link #buildOptional()}. The * only valid use of this method is if {@link #buildOptional()} would be the semantically correct option but you * are not using Java 8+. */ @Deprecated public ConfigurationOption<T> build() { return new ConfigurationOption<T>(dynamic, sensitive, key, label, description, defaultValue, configurationCategory, valueConverter, valueType, Arrays.asList(tags), required, changeListeners, validators, Arrays.asList(aliasKeys), validOptions); } /** * Builds the option and marks it as required. * * <p> Use this method if you don't want to provide a default value but setting a value is still required. You * will have to make sure to provide a value is present on startup. </p> * * <p> When a required option does not have a value the behavior depends on {@link * ConfigurationRegistry#failOnMissingRequiredValues}. Either an {@link IllegalStateException} is raised, which * can potentially prevent the application form starting or a warning gets logged. </p> */ public ConfigurationOption<T> buildRequired() { this.required = true; return build(); } /** * Builds the option with a default value so that {@link ConfigurationOption#getValue()} will never return * <code>null</code> * * @param defaultValue The default value which has to be non-<code>null</code> * @throws IllegalArgumentException When <code>null</code> was provided */ public ConfigurationOption<T> buildWithDefault(T defaultValue) { if (defaultValue == null) { throw new IllegalArgumentException("Default value must not be null"); } this.required = true; this.defaultValue = defaultValue; return build(); } /** * Builds the option and marks it as not required * * <p> Use this method if setting this option is not required and to express that it may be <code>null</code>. * </p> */ public ConfigurationOption<Optional<T>> buildOptional() { required = false; final List<ChangeListener<Optional<T>>> optionalChangeListeners = new ArrayList<ChangeListener<Optional<T>>>(changeListeners.size()); for (ChangeListener<T> changeListener : changeListeners) { optionalChangeListeners.add(new ChangeListener.OptionalChangeListenerAdapter<T>(changeListener)); } final List<Validator<Optional<T>>> optionalValidators = new ArrayList<Validator<Optional<T>>>(validators.size()); for (Validator<T> validator : validators) { optionalValidators.add(new Validator.OptionalValidatorAdapter<T>(validator)); } return new ConfigurationOption<Optional<T>>(dynamic, sensitive, key, label, description, java.util.Optional.ofNullable(defaultValue), configurationCategory, new OptionalValueConverter<T>(valueConverter), java.util.Optional.class, Arrays.asList(this.tags), required, optionalChangeListeners, optionalValidators, Arrays.asList(aliasKeys), validOptions); } public ConfigurationOptionBuilder<T> dynamic(boolean dynamic) { this.dynamic = dynamic; return this; } public ConfigurationOptionBuilder<T> key(String key) { this.key = key; return this; } /** * Sets alternate keys of the configuration option which act as an alias for the primary {@link #key(String)} * * @return <code>this</code>, for chaining. */ public ConfigurationOptionBuilder<T> aliasKeys(String... aliasKeys) { this.aliasKeys = aliasKeys; return this; } public ConfigurationOptionBuilder<T> label(String label) { this.label = label; return this; } public ConfigurationOptionBuilder<T> description(String description) { this.description = description; return this; } /** * @deprecated use {@link #buildWithDefault(Object)} */ @Deprecated public ConfigurationOptionBuilder<T> defaultValue(T defaultValue) { this.defaultValue = defaultValue; return this; } public ConfigurationOptionBuilder<T> configurationCategory(String configurationCategory) { this.configurationCategory = configurationCategory; return this; } public ConfigurationOptionBuilder<T> tags(String... tags) { this.tags = tags; return this; } /** * Marks this ConfigurationOption as sensitive. * * <p> If a value has sensitive content (e.g. password), it should be rendered as an input of type="password", * rather then as type="text". </p> * * @return <code>this</code>, for chaining. */ public ConfigurationOptionBuilder<T> sensitive() { this.sensitive = true; return this; } /** * Marks this option as required. * * <p> When a required option does not have a value the behavior depends on {@link * ConfigurationRegistry#failOnMissingRequiredValues}. Either an {@link IllegalStateException} is raised, which * can potentially prevent the application form starting or a warning gets logged. </p> * * @return <code>this</code>, for chaining. * @deprecated use {@link #buildRequired()} */ @Deprecated public ConfigurationOptionBuilder<T> required() { this.required = true; return this; } public ConfigurationOptionBuilder<T> addChangeListener(ChangeListener<T> changeListener) { this.changeListeners.add(changeListener); return this; } public ConfigurationOptionBuilder<T> addValidator(Validator<T> validator) { this.validators.add(validator); return this; } public ConfigurationOptionBuilder<T> validOptions(List<T> options) { for (T option : options) { addValidOption(option); } return this; } public ConfigurationOptionBuilder<T> addValidOptions(T... options) { for (T option : options) { addValidOption(option); } return this; } public ConfigurationOptionBuilder<T> addValidOption(T option) { if (option instanceof Collection) { throw new UnsupportedOperationException("Adding valid options to a collection option is not supported. " + "If you need this feature please raise an issue describing your use case."); } else { final String validOptionAsString = valueConverter.toString(option); addValidOptionAsString(validOptionAsString, getLabel(option, validOptionAsString)); } return this; } private String getLabel(Object option, String defaultLabel) { if (overridesToString(option)) { return option.toString(); } return defaultLabel; } private boolean overridesToString(Object o) { try { return o.getClass().getDeclaredMethod("toString").getDeclaringClass() != Object.class; } catch (NoSuchMethodException e) { return false; } } @SuppressWarnings("unchecked") private T getSingleValue(Object o) { return (T) Collections.singletonList(o); } private ConfigurationOptionBuilder<T> addValidOptionAsString(String validOptionAsString, String label) { if (validOptionsSealed) { throw new IllegalStateException("Options are sealed, you can't add any new ones"); } if (validOptions == null) { validOptions = new LinkedHashMap<String, String>(); } validOptions.put(validOptionAsString, label); return this; } /** * Makes sure that no more valid options can be added * * @return this, for chaining */ public ConfigurationOptionBuilder<T> sealValidOptions() { this.validOptionsSealed = true; if (validOptions != null) { validOptions = Collections.unmodifiableMap(validOptions); } return this; } } private static class ConfigValueInfo { private String newValueAsString; private String newConfigurationSourceName; private ConfigValueInfo() { } private ConfigValueInfo(String newValueAsString, String newConfigurationSourceName) { this.newValueAsString = newValueAsString; this.newConfigurationSourceName = newConfigurationSourceName; } private String getNewValueAsString() { return newValueAsString; } private String getNewConfigurationSourceName() { return newConfigurationSourceName; } } private static class ValidOptionValidator<T> implements Validator<T> { private final Set<String> validOptions; private final ValueConverter<T> valueConverter; ValidOptionValidator(Collection<String> validOptions, ValueConverter<T> valueConverter) { this.validOptions = new HashSet<String>(validOptions); this.valueConverter = valueConverter; } @Override public void assertValid(T value) { String valueAsString = valueConverter.toString(value); if (!validOptions.contains(valueAsString)) { throw new IllegalArgumentException("Invalid option '" + valueAsString + "' expecting one of " + validOptions); } } } }
stagemonitor-configuration/src/main/java/org/stagemonitor/configuration/ConfigurationOption.java
package org.stagemonitor.configuration; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.core.type.TypeReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.stagemonitor.configuration.converter.BooleanValueConverter; import org.stagemonitor.configuration.converter.ClassInstanceValueConverter; import org.stagemonitor.configuration.converter.DoubleValueConverter; import org.stagemonitor.configuration.converter.EnumValueConverter; import org.stagemonitor.configuration.converter.IntegerValueConverter; import org.stagemonitor.configuration.converter.JsonValueConverter; import org.stagemonitor.configuration.converter.ListValueConverter; import org.stagemonitor.configuration.converter.LongValueConverter; import org.stagemonitor.configuration.converter.MapValueConverter; import org.stagemonitor.configuration.converter.OptionalValueConverter; import org.stagemonitor.configuration.converter.RegexValueConverter; import org.stagemonitor.configuration.converter.SetValueConverter; import org.stagemonitor.configuration.converter.StringValueConverter; import org.stagemonitor.configuration.converter.UrlValueConverter; import org.stagemonitor.configuration.converter.ValueConverter; import org.stagemonitor.configuration.source.ConfigurationSource; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.ServiceLoader; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.regex.Pattern; /** * Represents a configuration option * * @param <T> the type of the configuration value */ public class ConfigurationOption<T> { private final Logger logger = LoggerFactory.getLogger(getClass()); private final boolean dynamic; private final boolean sensitive; private final String key; private final List<String> aliasKeys; private final List<String> allKeys; private final String label; private final String description; private final T defaultValue; private final List<String> tags; private final List<Validator<T>> validators; private final List<ChangeListener<T>> changeListeners; private final boolean required; private final String defaultValueAsString; private final String configurationCategory; @JsonIgnore private final ValueConverter<T> valueConverter; private final Class<? super T> valueType; // key: validOptionAsString, value: label private final Map<String, String> validOptions; private volatile List<ConfigurationSource> configurationSources; private volatile ConfigurationRegistry configuration; private volatile String errorMessage; private volatile OptionValue<T> optionValue; public static class OptionValue<T> { private final T value; private final String valueAsString; private final String nameOfCurrentConfigurationSource; private final String usedKey; OptionValue(T value, String valueAsString, String nameOfCurrentConfigurationSource, String usedKey) { this.value = value; this.valueAsString = valueAsString; this.nameOfCurrentConfigurationSource = nameOfCurrentConfigurationSource; this.usedKey = usedKey; } public T getValue() { return value; } public String getValueAsString() { return valueAsString; } public String getNameOfCurrentConfigurationSource() { return nameOfCurrentConfigurationSource; } public String getUsedKey() { return usedKey; } } public static <T> ConfigurationOptionBuilder<T> builder(ValueConverter<T> valueConverter, Class<? super T> valueType) { return new ConfigurationOptionBuilder<T>(valueConverter, valueType); } /** * Constructs a {@link ConfigurationOptionBuilder} whose value is of type {@link String} * * @return a {@link ConfigurationOptionBuilder} whose value is of type {@link String} */ public static ConfigurationOptionBuilder<String> stringOption() { return new ConfigurationOptionBuilder<String>(StringValueConverter.INSTANCE, String.class); } public static <T> ConfigurationOptionBuilder<T> jsonOption(TypeReference<T> typeReference, Class<? super T> clazz) { return new ConfigurationOptionBuilder<T>(new JsonValueConverter<T>(typeReference), clazz); } /** * Constructs a {@link ConfigurationOptionBuilder} whose value is of type {@link Boolean} * * @return a {@link ConfigurationOptionBuilder} whose value is of type {@link Boolean} */ public static ConfigurationOptionBuilder<Boolean> booleanOption() { return new ConfigurationOptionBuilder<Boolean>(BooleanValueConverter.INSTANCE, Boolean.class); } /** * Constructs a {@link ConfigurationOptionBuilder} whose value is of type {@link Integer} * * @return a {@link ConfigurationOptionBuilder} whose value is of type {@link Integer} */ public static ConfigurationOptionBuilder<Integer> integerOption() { return new ConfigurationOptionBuilder<Integer>(IntegerValueConverter.INSTANCE, Integer.class); } /** * Constructs a {@link ConfigurationOptionBuilder} whose value is of type {@link Long} * * @return a {@link ConfigurationOptionBuilder} whose value is of type {@link Long} */ public static ConfigurationOptionBuilder<Long> longOption() { return new ConfigurationOptionBuilder<Long>(LongValueConverter.INSTANCE, Long.class); } /** * Constructs a {@link ConfigurationOptionBuilder} whose value is of type {@link Double} * * @return a {@link ConfigurationOptionBuilder} whose value is of type {@link Double} */ public static ConfigurationOptionBuilder<Double> doubleOption() { return new ConfigurationOptionBuilder<Double>(DoubleValueConverter.INSTANCE, Double.class); } /** * Constructs a {@link ConfigurationOptionBuilder} whose value is of type {@link List}&lt;{@link String}&gt; * * @return a {@link ConfigurationOptionBuilder} whose value is of type {@link List}&lt;{@link String}&gt; */ public static ConfigurationOptionBuilder<Collection<String>> stringsOption() { return new ConfigurationOptionBuilder<Collection<String>>(SetValueConverter.STRINGS_VALUE_CONVERTER, Collection.class) .defaultValue(Collections.<String>emptySet()); } /** * Constructs a {@link ConfigurationOptionBuilder} whose value is of type {@link List}&lt;{@link String}&gt; and all * Strings are converted to lower case. * * @return a {@link ConfigurationOptionBuilder} whose value is of type {@link List}&lt;{@link String}&gt; */ public static ConfigurationOptionBuilder<Collection<String>> lowerStringsOption() { return new ConfigurationOptionBuilder<Collection<String>>(SetValueConverter.LOWER_STRINGS_VALUE_CONVERTER, Collection.class) .defaultValue(Collections.<String>emptySet()); } /** * Constructs a {@link ConfigurationOptionBuilder} whose value is of type {@link Set}&lt;{@link Integer}&gt; * * @return a {@link ConfigurationOptionBuilder} whose value is of type {@link Set}&lt;{@link Integer}&gt; */ public static ConfigurationOption.ConfigurationOptionBuilder<Collection<Integer>> integersOption() { return ConfigurationOption.builder(SetValueConverter.INTEGERS, Collection.class); } /** * Constructs a {@link ConfigurationOptionBuilder} whose value is of type {@link List}&lt;{@link Pattern}&gt; * * @return a {@link ConfigurationOptionBuilder} whose value is of type {@link List}&lt;{@link Pattern}&gt; */ public static ConfigurationOptionBuilder<Collection<Pattern>> regexListOption() { return new ConfigurationOptionBuilder<Collection<Pattern>>(new SetValueConverter<Pattern>(RegexValueConverter.INSTANCE), Collection.class) .defaultValue(Collections.<Pattern>emptySet()); } /** * Constructs a {@link ConfigurationOptionBuilder} whose value is of type {@link Map}&lt;{@link Pattern}, {@link * String}&gt; * * @return a {@link ConfigurationOptionBuilder} whose value is of type {@link Map}&lt;{@link Pattern}, {@link * String}&gt; */ public static ConfigurationOptionBuilder<Map<Pattern, String>> regexMapOption() { return new ConfigurationOptionBuilder<Map<Pattern, String>>(MapValueConverter.REGEX_MAP_VALUE_CONVERTER, Map.class) .defaultValue(Collections.<Pattern, String>emptyMap()); } /** * Constructs a {@link ConfigurationOptionBuilder} whose value is of type {@link Map} * * @return a {@link ConfigurationOptionBuilder} whose value is of type {@link Map} */ public static <K, V> ConfigurationOptionBuilder<Map<K, V>> mapOption(ValueConverter<K> keyConverter, ValueConverter<V> valueConverter) { return new ConfigurationOptionBuilder<Map<K, V>>(new MapValueConverter<K, V>(keyConverter, valueConverter), Map.class) .defaultValue(Collections.<K, V>emptyMap()); } /** * Constructs a {@link ConfigurationOptionBuilder} whose value is an {@link Enum} * * @return a {@link ConfigurationOptionBuilder} whose value is an {@link Enum} */ public static <T extends Enum<T>> ConfigurationOptionBuilder<T> enumOption(Class<T> clazz) { final ConfigurationOptionBuilder<T> optionBuilder = new ConfigurationOptionBuilder<T>(new EnumValueConverter<T>(clazz), clazz); for (T enumConstant : clazz.getEnumConstants()) { optionBuilder.addValidOption(enumConstant); } optionBuilder.sealValidOptions(); return optionBuilder; } /** * Adds a configuration option for intended classes loaded by {@link ServiceLoader}s * * <p>Restricts the {@link #validOptions} to the class names of the {@link ServiceLoader} implementations of the * provided service loader interface.</p> * * <p> Note that the implementations have to be registered in {@code META-INF/services/{serviceLoaderInterface.getName()}}</p> */ public static <T> ConfigurationOptionBuilder<T> serviceLoaderStrategyOption(Class<T> serviceLoaderInterface) { final ConfigurationOptionBuilder<T> optionBuilder = new ConfigurationOptionBuilder<T>(ClassInstanceValueConverter.of(serviceLoaderInterface), serviceLoaderInterface); for (T impl : ServiceLoader.load(serviceLoaderInterface, ConfigurationOption.class.getClassLoader())) { optionBuilder.addValidOption(impl); } optionBuilder.sealValidOptions(); return optionBuilder; } /** * Constructs a {@link ConfigurationOptionBuilder} whose value is of type {@link String} * * @return a {@link ConfigurationOptionBuilder} whose value is of type {@link String} */ public static ConfigurationOptionBuilder<URL> urlOption() { return new ConfigurationOptionBuilder<URL>(UrlValueConverter.INSTANCE, URL.class); } /** * Constructs a {@link ConfigurationOptionBuilder} whose value is of type {@link String} * * @return a {@link ConfigurationOptionBuilder} whose value is of type {@link String} */ public static ConfigurationOptionBuilder<List<URL>> urlsOption() { return new ConfigurationOptionBuilder<List<URL>>(new ListValueConverter<URL>(UrlValueConverter.INSTANCE), List.class) .defaultValue(Collections.<URL>emptyList()); } private ConfigurationOption(boolean dynamic, boolean sensitive, String key, String label, String description, T defaultValue, String configurationCategory, final ValueConverter<T> valueConverter, Class<? super T> valueType, List<String> tags, boolean required, List<ChangeListener<T>> changeListeners, List<Validator<T>> validators, List<String> aliasKeys, final Map<String, String> validOptions) { this.dynamic = dynamic; this.key = key; this.aliasKeys = aliasKeys; this.label = label; this.description = description; this.defaultValue = defaultValue; this.tags = tags; validators = new ArrayList<Validator<T>>(validators); if (validOptions != null) { this.validOptions = Collections.unmodifiableMap(new LinkedHashMap<String, String>(validOptions)); validators.add(new ValidOptionValidator<T>(validOptions.keySet(), valueConverter)); } else { this.validOptions = null; } this.validators = Collections.unmodifiableList(new ArrayList<Validator<T>>(validators)); this.defaultValueAsString = valueConverter.toString(defaultValue); this.configurationCategory = configurationCategory; this.valueConverter = valueConverter; this.valueType = valueType; this.sensitive = sensitive; this.required = required; this.changeListeners = new CopyOnWriteArrayList<ChangeListener<T>>(changeListeners); setToDefault(); final ArrayList<String> tempAllKeys = new ArrayList<String>(aliasKeys.size() + 1); tempAllKeys.add(key); tempAllKeys.addAll(aliasKeys); this.allKeys = Collections.unmodifiableList(tempAllKeys); } /** * Returns <code>true</code>, if the value can dynamically be set, <code>false</code> otherwise. * * @return <code>true</code>, if the value can dynamically be set, <code>false</code> otherwise. */ public boolean isDynamic() { return dynamic; } /** * Returns the key of the configuration option that can for example be used in a properties file * * @return the config key */ public String getKey() { return key; } /** * Returns the alternate keys of the configuration option that can for example be used in a properties file * * @return the alternate config keys */ public List<String> getAliasKeys() { return Collections.unmodifiableList(aliasKeys); } /** * Returns the display name of this configuration option * * @return the display name of this configuration option */ public String getLabel() { return label; } /** * Returns the description of the configuration option * * @return the description of the configuration option */ public String getDescription() { return description; } /** * Returns the default value in its string representation * * @return the default value as string */ public String getDefaultValueAsString() { return defaultValueAsString; } /** * Returns the current in its string representation * * @return the current value as string */ public String getValueAsString() { return optionValue.valueAsString; } public String getValueAsSafeString() { return valueConverter.toSafeString(optionValue.value); } /** * Returns <code>true</code>, if the value is sensitive, <code>false</code> otherwise. If a value has sensitive * content (e.g. password), it should be rendered as an input of type="password", rather then as type="text". * * @return Returns <code>true</code>, if the value is sensitive, <code>false</code> otherwise. */ public boolean isSensitive() { return sensitive; } /** * Returns the current value * * @return the current value */ @JsonIgnore public T getValue() { return optionValue.value; } /** * Returns the current value * * @return the current value */ @JsonIgnore public T get() { return getValue(); } /** * Returns an immutable snapshot of the {@link OptionValue}. * This makes sure to get a consistent snapshot of all the related values without the risk of partially applied updates. * This means that {@link OptionValue#getValue()} and {@link OptionValue#getValueAsString()} are always in sync, * which is not guaranteed if subsequently calling {@link #getValue()} and {@link #getValueAsString()} * because there could be a concurrent update between those reads. * * @return an immutable snapshot of the {@link OptionValue} */ @JsonIgnore public OptionValue<T> getOptionValue() { return optionValue; } void setConfigurationSources(List<ConfigurationSource> configurationSources) { this.configurationSources = configurationSources; loadValue(); } void setConfiguration(ConfigurationRegistry configuration) { this.configuration = configuration; } /** * Returns the name of the configuration source that provided the current value * * @return the name of the configuration source that provided the current value */ public String getNameOfCurrentConfigurationSource() { return optionValue.nameOfCurrentConfigurationSource; } /** * Returns the category name of this configuration option * * @return the category name of this configuration option */ public String getConfigurationCategory() { return configurationCategory; } /** * Returns the tags associated with this configuration option * * @return the tags associated with this configuration option */ public List<String> getTags() { return Collections.unmodifiableList(tags); } /** * Returns the simple type name of the value * * @return the simple type name of the value */ public String getValueType() { return valueType.getSimpleName(); } public ValueConverter<T> getValueConverter() { return valueConverter; } /** * If there was a error while trying to set value from a {@link ConfigurationSource}, this error message contains * information about the error. * * @return a error message or null if there was no error */ public String getErrorMessage() { return errorMessage; } /** * Returns the valid values for this configuration option * * @return the valid values for this configuration option */ public Collection<String> getValidOptions() { if (validOptions == null) { return null; } return validOptions.keySet(); } public Map<String, String> getValidOptionsLabelMap() { return validOptions; } synchronized void reload(boolean reloadNonDynamicValues) { if (dynamic || reloadNonDynamicValues) { loadValue(); } } private void loadValue() { boolean success = false; for (String key : allKeys) { ConfigValueInfo configValueInfo = loadValueFromSources(key); success = trySetValue(configValueInfo, key); if (success) { break; } } if (!success) { setToDefault(); } } private ConfigValueInfo loadValueFromSources(String key) { for (ConfigurationSource configurationSource : configurationSources) { String newValueAsString = configurationSource.getValue(key); if (newValueAsString != null) { return new ConfigValueInfo(newValueAsString, configurationSource.getName()); } } return new ConfigValueInfo(); } private boolean trySetValue(ConfigValueInfo configValueInfo, String key) { final String newConfigurationSourceName = configValueInfo.getNewConfigurationSourceName(); String newValueAsString = configValueInfo.getNewValueAsString(); if (newValueAsString == null) { return false; } newValueAsString = newValueAsString.trim(); T oldValue = getValue(); if (hasChanges(newValueAsString)) { try { final T newValue = valueConverter.convert(newValueAsString); setValue(newValue, newValueAsString, newConfigurationSourceName, key); errorMessage = null; if (isInitialized()) { for (ChangeListener<T> changeListener : changeListeners) { try { changeListener.onChange(this, oldValue, getValue()); } catch (RuntimeException e) { logger.warn(e.getMessage() + " (this exception is ignored)", e); } } } return true; } catch (IllegalArgumentException e) { errorMessage = "Error in " + newConfigurationSourceName + ": " + e.getMessage(); logger.warn(errorMessage + " Default value '" + defaultValueAsString + "' for '" + key + "' will be applied."); return false; } } else { //don't hide the name of the configuration source this.optionValue = new OptionValue<>(getValue(),getValueAsString(),newConfigurationSourceName, key); return true; } } private void setToDefault() { final String msg = "Missing required value for configuration option " + key; if (isInitialized() && required && defaultValue == null) { handleMissingRequiredValue(msg); } setValue(defaultValue, defaultValueAsString, "Default Value", key); } private boolean isInitialized() { return configuration != null; } private void handleMissingRequiredValue(String msg) { if (configuration.isFailOnMissingRequiredValues()) { throw new IllegalStateException(msg); } else { logger.warn(msg); } } private boolean hasChanges(String property) { return !property.equals(optionValue.valueAsString); } /** * Throws a {@link IllegalArgumentException} if the value is not valid * * @param valueAsString the configuration value as string * @throws IllegalArgumentException if there was a error while converting the value */ public void assertValid(String valueAsString) throws IllegalArgumentException { final T value = valueConverter.convert(valueAsString); for (Validator<T> validator : validators) { validator.assertValid(value); } } /** * Updates the existing value with a new one * * @param newValue the new value * @param configurationSourceName the name of the configuration source that the value should be saved to * @throws IOException if there was an error saving the key to the source * @throws IllegalArgumentException if there was a error processing the configuration key or value or the * configurationSourceName did not match any of the available configuration * sources * @throws UnsupportedOperationException if saving values is not possible with this configuration source */ public void update(T newValue, String configurationSourceName) throws IOException { final String newValueAsString = valueConverter.toString(newValue); configuration.save(key, newValueAsString, configurationSourceName); } private void setValue(T value, String valueAsString, String nameOfCurrentConfigurationSource, String key) { for (Validator<T> validator : validators) { validator.assertValid(value); } this.optionValue = new OptionValue<T>(value, valueAsString, nameOfCurrentConfigurationSource, key); } /** * Returns true if the current value is equal to the default value * * @return true if the current value is equal to the default value */ public boolean isDefault() { return (optionValue.valueAsString != null && optionValue.valueAsString.equals(defaultValueAsString)) || (optionValue.valueAsString == null && defaultValueAsString == null); } public void addChangeListener(ChangeListener<T> changeListener) { changeListeners.add(changeListener); } public boolean removeChangeListener(ChangeListener<T> changeListener) { return changeListeners.remove(changeListener); } /** * A {@link ConfigurationOption} can have multiple keys ({@link #key} and {@link #aliasKeys}). This method returns * the key which is used by the current configuration source ({@link OptionValue#nameOfCurrentConfigurationSource}). * * @return the used key of the current configuration source */ public String getUsedKey() { return optionValue.usedKey; } /** * Notifies about configuration changes */ public interface ChangeListener<T> { /** * @param configurationOption the configuration option which has just changed its value * @param oldValue the old value * @param newValue the new value */ void onChange(ConfigurationOption<?> configurationOption, T oldValue, T newValue); class OptionalChangeListenerAdapter<T> implements ChangeListener<Optional<T>> { private final ChangeListener<T> changeListener; public OptionalChangeListenerAdapter(ChangeListener<T> changeListener) { this.changeListener = changeListener; } @Override public void onChange(ConfigurationOption<?> configurationOption, Optional<T> oldValue, Optional<T> newValue) { changeListener.onChange(configurationOption, oldValue.orElse(null), newValue.orElse(null)); } } } public interface Validator<T> { /** * Validates a value * * @param value the value to be validated * @throws IllegalArgumentException if the value is invalid */ void assertValid(T value); class OptionalValidatorAdapter<T> implements Validator<Optional<T>> { private final Validator<T> validator; public OptionalValidatorAdapter(Validator<T> validator) { this.validator = validator; } @Override public void assertValid(Optional<T> value) { validator.assertValid(value.orElse(null)); } } } public static class ConfigurationOptionBuilder<T> { private boolean dynamic = false; private boolean sensitive = false; private String key; private String label; private String description; private T defaultValue; private String configurationCategory; private ValueConverter<T> valueConverter; private Class<? super T> valueType; private String[] tags = new String[0]; private boolean required = false; private List<ChangeListener<T>> changeListeners = new ArrayList<ChangeListener<T>>(); private List<Validator<T>> validators = new ArrayList<Validator<T>>(); private String[] aliasKeys = new String[0]; private Map<String, String> validOptions; private boolean validOptionsSealed = false; private ConfigurationOptionBuilder(ValueConverter<T> valueConverter, Class<? super T> valueType) { this.valueConverter = valueConverter; this.valueType = valueType; } /** * Be aware that when using this method you might have to deal with <code>null</code> values when calling {@link * #getValue()}. That's why this method is deprecated * * @deprecated use {@link #buildRequired()}, {@link #buildWithDefault(Object)} or {@link #buildOptional()}. The * only valid use of this method is if {@link #buildOptional()} would be the semantically correct option but you * are not using Java 8+. */ @Deprecated public ConfigurationOption<T> build() { return new ConfigurationOption<T>(dynamic, sensitive, key, label, description, defaultValue, configurationCategory, valueConverter, valueType, Arrays.asList(tags), required, changeListeners, validators, Arrays.asList(aliasKeys), validOptions); } /** * Builds the option and marks it as required. * * <p> Use this method if you don't want to provide a default value but setting a value is still required. You * will have to make sure to provide a value is present on startup. </p> * * <p> When a required option does not have a value the behavior depends on {@link * ConfigurationRegistry#failOnMissingRequiredValues}. Either an {@link IllegalStateException} is raised, which * can potentially prevent the application form starting or a warning gets logged. </p> */ public ConfigurationOption<T> buildRequired() { this.required = true; return build(); } /** * Builds the option with a default value so that {@link ConfigurationOption#getValue()} will never return * <code>null</code> * * @param defaultValue The default value which has to be non-<code>null</code> * @throws IllegalArgumentException When <code>null</code> was provided */ public ConfigurationOption<T> buildWithDefault(T defaultValue) { if (defaultValue == null) { throw new IllegalArgumentException("Default value must not be null"); } this.required = true; this.defaultValue = defaultValue; return build(); } /** * Builds the option and marks it as not required * * <p> Use this method if setting this option is not required and to express that it may be <code>null</code>. * </p> */ public ConfigurationOption<Optional<T>> buildOptional() { required = false; final List<ChangeListener<Optional<T>>> optionalChangeListeners = new ArrayList<ChangeListener<Optional<T>>>(changeListeners.size()); for (ChangeListener<T> changeListener : changeListeners) { optionalChangeListeners.add(new ChangeListener.OptionalChangeListenerAdapter<T>(changeListener)); } final List<Validator<Optional<T>>> optionalValidators = new ArrayList<Validator<Optional<T>>>(validators.size()); for (Validator<T> validator : validators) { optionalValidators.add(new Validator.OptionalValidatorAdapter<T>(validator)); } return new ConfigurationOption<Optional<T>>(dynamic, sensitive, key, label, description, java.util.Optional.ofNullable(defaultValue), configurationCategory, new OptionalValueConverter<T>(valueConverter), java.util.Optional.class, Arrays.asList(this.tags), required, optionalChangeListeners, optionalValidators, Arrays.asList(aliasKeys), validOptions); } public ConfigurationOptionBuilder<T> dynamic(boolean dynamic) { this.dynamic = dynamic; return this; } public ConfigurationOptionBuilder<T> key(String key) { this.key = key; return this; } /** * Sets alternate keys of the configuration option which act as an alias for the primary {@link #key(String)} * * @return <code>this</code>, for chaining. */ public ConfigurationOptionBuilder<T> aliasKeys(String... aliasKeys) { this.aliasKeys = aliasKeys; return this; } public ConfigurationOptionBuilder<T> label(String label) { this.label = label; return this; } public ConfigurationOptionBuilder<T> description(String description) { this.description = description; return this; } /** * @deprecated use {@link #buildWithDefault(Object)} */ @Deprecated public ConfigurationOptionBuilder<T> defaultValue(T defaultValue) { this.defaultValue = defaultValue; return this; } public ConfigurationOptionBuilder<T> configurationCategory(String configurationCategory) { this.configurationCategory = configurationCategory; return this; } public ConfigurationOptionBuilder<T> tags(String... tags) { this.tags = tags; return this; } /** * Marks this ConfigurationOption as sensitive. * * <p> If a value has sensitive content (e.g. password), it should be rendered as an input of type="password", * rather then as type="text". </p> * * @return <code>this</code>, for chaining. */ public ConfigurationOptionBuilder<T> sensitive() { this.sensitive = true; return this; } /** * Marks this option as required. * * <p> When a required option does not have a value the behavior depends on {@link * ConfigurationRegistry#failOnMissingRequiredValues}. Either an {@link IllegalStateException} is raised, which * can potentially prevent the application form starting or a warning gets logged. </p> * * @return <code>this</code>, for chaining. * @deprecated use {@link #buildRequired()} */ @Deprecated public ConfigurationOptionBuilder<T> required() { this.required = true; return this; } public ConfigurationOptionBuilder<T> addChangeListener(ChangeListener<T> changeListener) { this.changeListeners.add(changeListener); return this; } public ConfigurationOptionBuilder<T> addValidator(Validator<T> validator) { this.validators.add(validator); return this; } public ConfigurationOptionBuilder<T> validOptions(List<T> options) { for (T option : options) { addValidOption(option); } return this; } public ConfigurationOptionBuilder<T> addValidOptions(T... options) { for (T option : options) { addValidOption(option); } return this; } public ConfigurationOptionBuilder<T> addValidOption(T option) { if (option instanceof Collection) { throw new UnsupportedOperationException("Adding valid options to a collection option is not supported. " + "If you need this feature please raise an issue describing your use case."); } else { final String validOptionAsString = valueConverter.toString(option); addValidOptionAsString(validOptionAsString, getLabel(option, validOptionAsString)); } return this; } private String getLabel(Object option, String defaultLabel) { if (overridesToString(option)) { return option.toString(); } return defaultLabel; } private boolean overridesToString(Object o) { try { return o.getClass().getDeclaredMethod("toString").getDeclaringClass() != Object.class; } catch (NoSuchMethodException e) { return false; } } @SuppressWarnings("unchecked") private T getSingleValue(Object o) { return (T) Collections.singletonList(o); } private ConfigurationOptionBuilder<T> addValidOptionAsString(String validOptionAsString, String label) { if (validOptionsSealed) { throw new IllegalStateException("Options are sealed, you can't add any new ones"); } if (validOptions == null) { validOptions = new LinkedHashMap<String, String>(); } validOptions.put(validOptionAsString, label); return this; } /** * Makes sure that no more valid options can be added * * @return this, for chaining */ public ConfigurationOptionBuilder<T> sealValidOptions() { this.validOptionsSealed = true; if (validOptions != null) { validOptions = Collections.unmodifiableMap(validOptions); } return this; } } private static class ConfigValueInfo { private String newValueAsString; private String newConfigurationSourceName; private ConfigValueInfo() { } private ConfigValueInfo(String newValueAsString, String newConfigurationSourceName) { this.newValueAsString = newValueAsString; this.newConfigurationSourceName = newConfigurationSourceName; } private String getNewValueAsString() { return newValueAsString; } private String getNewConfigurationSourceName() { return newConfigurationSourceName; } } private static class ValidOptionValidator<T> implements Validator<T> { private final Set<String> validOptions; private final ValueConverter<T> valueConverter; ValidOptionValidator(Collection<String> validOptions, ValueConverter<T> valueConverter) { this.validOptions = new HashSet<String>(validOptions); this.valueConverter = valueConverter; } @Override public void assertValid(T value) { String valueAsString = valueConverter.toString(value); if (!validOptions.contains(valueAsString)) { throw new IllegalArgumentException("Invalid option '" + valueAsString + "' expecting one of " + validOptions); } } } }
Revert "472 set always the right name of configuration source" This reverts commit f134b48b
stagemonitor-configuration/src/main/java/org/stagemonitor/configuration/ConfigurationOption.java
Revert "472 set always the right name of configuration source"
Java
bsd-3-clause
60929f9f66fe04d523985a6cf8b514ba4d418fc2
0
lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon
/* * $Id: MockIdentityManager.java,v 1.4 2005-07-14 23:33:55 troberts Exp $ */ /* Copyright (c) 2000-2003 Board of Trustees of Leland Stanford Jr. University, all rights reserved. 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 STANFORD UNIVERSITY 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. Except as contained in this notice, the name of Stanford University shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Stanford University. */ package org.lockss.protocol; import java.util.*; import org.lockss.app.*; import org.lockss.util.*; import org.lockss.config.*; import org.lockss.plugin.*; /** * Mock override of IdentityManager. */ public class MockIdentityManager extends IdentityManager { private static Logger logger = Logger.getLogger("MockIdentityManager"); public HashMap idMap = new HashMap(); public HashMap piMap = new HashMap(); public HashMap repMap = new HashMap(); public Map agreeMap = new HashMap(); int maxRep = 5000; PeerIdentity localId = new MockPeerIdentity("fake peer id"); public MockIdentityManager() { super(); } public void initService(LockssDaemon daemon) throws LockssAppException { // throw new UnsupportedOperationException("not implemented"); } public void startService() { throw new UnsupportedOperationException("not implemented"); } public void stopService() { throw new UnsupportedOperationException("not implemented"); } public PeerIdentity findPeerIdentity(String key) { throw new UnsupportedOperationException("not implemented"); } public PeerIdentity ipAddrToPeerIdentity(IPAddr addr, int port) { String key = ""+addr+port; return new MockPeerIdentity(key); } public PeerIdentity ipAddrToPeerIdentity(IPAddr addr) { throw new UnsupportedOperationException("not implemented"); } public PeerIdentity stringToPeerIdentity(String idKey) throws IdentityManager.MalformedIdentityKeyException { return (PeerIdentity)piMap.get(idKey); } public void addPeerIdentity(String idKey, PeerIdentity pi) { piMap.put(idKey, pi); } public IPAddr identityToIPAddr(PeerIdentity pid) { throw new UnsupportedOperationException("not implemented"); } public PeerIdentity getLocalPeerIdentity(int pollVersion) { return new MockPeerIdentity("127.0.0.1"); } public IPAddr getLocalIPAddr() { throw new UnsupportedOperationException("not implemented"); } public boolean isLocalIdentity(PeerIdentity id) { log.debug3("Checking if "+id+" is the local identity "+localId); return id == localId; } public void setLocalIdentity(PeerIdentity id) { log.debug3("Setting local identity to "+id); this.localId = id; } public boolean isLocalIdentity(String idStr) { throw new UnsupportedOperationException("not implemented"); } public void rememberEvent(PeerIdentity id, int event, LcapMessage msg) { throw new UnsupportedOperationException("not implemented"); } public int getMaxReputation() { return maxRep; } public void setMaxReputation(int maxRep) { this.maxRep = maxRep; } public int getReputation(PeerIdentity id) { Integer rep = (Integer)repMap.get(id); if (rep == null) { return 0; } return rep.intValue(); } public void setReputation(PeerIdentity id, int rep) { repMap.put(id, new Integer(rep)); } // public void storeIdentities() throws ProtocolException { // throw new UnsupportedOperationException("not implemented"); // } public IdentityListBean getIdentityListBean() { throw new UnsupportedOperationException("not implemented"); } public void signalAgreed(PeerIdentity pid, ArchivalUnit au) { throw new UnsupportedOperationException("not implemented"); } public void signalDisagreed(PeerIdentity pid, ArchivalUnit au) { throw new UnsupportedOperationException("not implemented"); } public Map getCachesToRepairFrom(ArchivalUnit au) { throw new UnsupportedOperationException("not implemented"); } public void setConfig(Configuration config, Configuration oldConfig, Configuration.Differences changedKeys) { throw new UnsupportedOperationException("not implemented"); } // public void initService(LockssDaemon daemon) throws LockssAppException { // log.debug("MockIdentityManager: initService"); // super.initService(daemon); // } // protected String getLocalIpParam(Configuration config) { // String res = config.get(PARAM_LOCAL_IP); // if (res == null) { // res = "127.7.7.7"; // } // return res; // } // public void startService() { // log.debug("MockIdentityManager: startService"); // super.startService(); // idMap = new HashMap(); // } // public void stopService() { // log.debug("MockIdentityManager: stopService"); // super.stopService(); // idMap = null; // } // public void changeReputation(PeerIdentity id, int changeKind) { // throw new UnsupportedOperationException("not implemented"); // // idMap.put(id, new Integer(changeKind)); // } public int lastChange(PeerIdentity id) { Integer change = (Integer)idMap.get(id); if (change == null) { return -1; } return change.intValue(); } // public void signalAgreed(PeerIdentity id, ArchivalUnit au) { // throw new UnsupportedOperationException("not implemented"); // } // public void signalDisagreed(PeerIdentity id, ArchivalUnit au) { // throw new UnsupportedOperationException("not implemented"); // } public Map getAgreed(ArchivalUnit au) { return (Map)agreeMap.get(au); } /** * Change the the reputation of the peer * @param peer the PeerIdentity * @param reputation the new reputation */ // public void setReputation(PeerIdentity peer, int reputation) { // try { // LcapIdentity lid = findLcapIdentity(peer, peer.getIdString()); // lid.changeReputation(reputation - lid.getReputation()); // } catch (IdentityManager.MalformedIdentityKeyException e) { // throw new RuntimeException(e.toString()); // } // } public void setAgeedForAu(ArchivalUnit au, Map map) { agreeMap.put(au, map); } //protected // protected IdentityManagerStatus makeStatusAccessor(Map theIdentities) { // throw new UnsupportedOperationException("not implemented"); // } // protected LcapIdentity findLcapIdentity(PeerIdentity pid, String key) { // throw new UnsupportedOperationException("not implemented"); // } protected LcapIdentity findLcapIdentity(PeerIdentity pid, IPAddr addr, int port) { throw new UnsupportedOperationException("not implemented"); } protected int getReputationDelta(int changeKind) { throw new UnsupportedOperationException("not implemented"); } // protected String getLocalIpParam(Configuration config) { // throw new UnsupportedOperationException("not implemented"); // } }
test/src/org/lockss/protocol/MockIdentityManager.java
/* * $Id: MockIdentityManager.java,v 1.3 2005-07-13 17:48:39 troberts Exp $ */ /* Copyright (c) 2000-2003 Board of Trustees of Leland Stanford Jr. University, all rights reserved. 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 STANFORD UNIVERSITY 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. Except as contained in this notice, the name of Stanford University shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Stanford University. */ package org.lockss.protocol; import java.util.*; import org.lockss.app.*; import org.lockss.util.*; import org.lockss.config.*; import org.lockss.plugin.*; /** * Mock override of IdentityManager. */ public class MockIdentityManager extends IdentityManager { public HashMap idMap = new HashMap(); public HashMap piMap = new HashMap(); public HashMap repMap = new HashMap(); public Map agreeMap = new HashMap(); int maxRep = 5000; public MockIdentityManager() { super(); } public void initService(LockssDaemon daemon) throws LockssAppException { // throw new UnsupportedOperationException("not implemented"); } public void startService() { throw new UnsupportedOperationException("not implemented"); } public void stopService() { throw new UnsupportedOperationException("not implemented"); } public PeerIdentity findPeerIdentity(String key) { throw new UnsupportedOperationException("not implemented"); } public PeerIdentity ipAddrToPeerIdentity(IPAddr addr, int port) { String key = ""+addr+port; return new MockPeerIdentity(key); } public PeerIdentity ipAddrToPeerIdentity(IPAddr addr) { throw new UnsupportedOperationException("not implemented"); } public PeerIdentity stringToPeerIdentity(String idKey) throws IdentityManager.MalformedIdentityKeyException { return (PeerIdentity)piMap.get(idKey); } public void addPeerIdentity(String idKey, PeerIdentity pi) { piMap.put(idKey, pi); } public IPAddr identityToIPAddr(PeerIdentity pid) { throw new UnsupportedOperationException("not implemented"); } public PeerIdentity getLocalPeerIdentity(int pollVersion) { return new MockPeerIdentity("127.0.0.1"); } public IPAddr getLocalIPAddr() { throw new UnsupportedOperationException("not implemented"); } public boolean isLocalIdentity(PeerIdentity id) { return false; // throw new UnsupportedOperationException("not implemented"); } public boolean isLocalIdentity(String idStr) { throw new UnsupportedOperationException("not implemented"); } public void rememberEvent(PeerIdentity id, int event, LcapMessage msg) { throw new UnsupportedOperationException("not implemented"); } public int getMaxReputation() { return maxRep; } public void setMaxReputation(int maxRep) { this.maxRep = maxRep; } public int getReputation(PeerIdentity id) { Integer rep = (Integer)repMap.get(id); if (rep == null) { return 0; } return rep.intValue(); } public void setReputation(PeerIdentity id, int rep) { repMap.put(id, new Integer(rep)); } // public void storeIdentities() throws ProtocolException { // throw new UnsupportedOperationException("not implemented"); // } public IdentityListBean getIdentityListBean() { throw new UnsupportedOperationException("not implemented"); } public void signalAgreed(PeerIdentity pid, ArchivalUnit au) { throw new UnsupportedOperationException("not implemented"); } public void signalDisagreed(PeerIdentity pid, ArchivalUnit au) { throw new UnsupportedOperationException("not implemented"); } public Map getCachesToRepairFrom(ArchivalUnit au) { throw new UnsupportedOperationException("not implemented"); } public void setConfig(Configuration config, Configuration oldConfig, Configuration.Differences changedKeys) { throw new UnsupportedOperationException("not implemented"); } // public void initService(LockssDaemon daemon) throws LockssAppException { // log.debug("MockIdentityManager: initService"); // super.initService(daemon); // } // protected String getLocalIpParam(Configuration config) { // String res = config.get(PARAM_LOCAL_IP); // if (res == null) { // res = "127.7.7.7"; // } // return res; // } // public void startService() { // log.debug("MockIdentityManager: startService"); // super.startService(); // idMap = new HashMap(); // } // public void stopService() { // log.debug("MockIdentityManager: stopService"); // super.stopService(); // idMap = null; // } // public void changeReputation(PeerIdentity id, int changeKind) { // throw new UnsupportedOperationException("not implemented"); // // idMap.put(id, new Integer(changeKind)); // } public int lastChange(PeerIdentity id) { Integer change = (Integer)idMap.get(id); if (change == null) { return -1; } return change.intValue(); } // public void signalAgreed(PeerIdentity id, ArchivalUnit au) { // throw new UnsupportedOperationException("not implemented"); // } // public void signalDisagreed(PeerIdentity id, ArchivalUnit au) { // throw new UnsupportedOperationException("not implemented"); // } public Map getAgreed(ArchivalUnit au) { return (Map)agreeMap.get(au); } /** * Change the the reputation of the peer * @param peer the PeerIdentity * @param reputation the new reputation */ // public void setReputation(PeerIdentity peer, int reputation) { // try { // LcapIdentity lid = findLcapIdentity(peer, peer.getIdString()); // lid.changeReputation(reputation - lid.getReputation()); // } catch (IdentityManager.MalformedIdentityKeyException e) { // throw new RuntimeException(e.toString()); // } // } public void setAgeedForAu(ArchivalUnit au, Map map) { agreeMap.put(au, map); } //protected // protected IdentityManagerStatus makeStatusAccessor(Map theIdentities) { // throw new UnsupportedOperationException("not implemented"); // } // protected LcapIdentity findLcapIdentity(PeerIdentity pid, String key) { // throw new UnsupportedOperationException("not implemented"); // } protected LcapIdentity findLcapIdentity(PeerIdentity pid, IPAddr addr, int port) { throw new UnsupportedOperationException("not implemented"); } protected int getReputationDelta(int changeKind) { throw new UnsupportedOperationException("not implemented"); } // protected String getLocalIpParam(Configuration config) { // throw new UnsupportedOperationException("not implemented"); // } }
* added a logger * added code to set the local identity git-svn-id: 293778eaa97c8c94097d610b1bd5133a8f478f36@4392 4f837ed2-42f5-46e7-a7a5-fa17313484d4
test/src/org/lockss/protocol/MockIdentityManager.java
* added a logger * added code to set the local identity
Java
bsd-3-clause
cc84935f80c18ac097aaa916603c22a4d9b62c2e
0
MerelyAPseudonym/isabelle,MerelyAPseudonym/isabelle,MerelyAPseudonym/isabelle,MerelyAPseudonym/isabelle,MerelyAPseudonym/isabelle,MerelyAPseudonym/isabelle
/*************************************************************************** Title: GraphBrowser/GraphBrowser.java ID: $Id$ Author: Stefan Berghofer, TU Muenchen Copyright 1997 TU Muenchen This is the graph browser's main class. It contains the "main(...)" method, which is used for the stand-alone version, as well as "init(...)", "start(...)" and "stop(...)" methods which are used for the applet version. Note: GraphBrowser is designed for the 1.0.2 version of the JDK. ***************************************************************************/ package GraphBrowser; import java.awt.*; import java.applet.*; import java.io.*; import java.util.*; import java.net.*; import awtUtilities.*; public class GraphBrowser extends Applet { GraphView gv; TreeBrowser tb=null; String gfname; static boolean isApplet; static Frame f; public GraphBrowser(String name) { gfname=name; } public GraphBrowser() {} public void showWaitMessage() { if (isApplet) getAppletContext().showStatus("calculating layout, please wait ..."); else { f.setCursor(Frame.WAIT_CURSOR); } } public void showReadyMessage() { if (isApplet) getAppletContext().showStatus("ready !"); else { f.setCursor(Frame.DEFAULT_CURSOR); } } public void viewFile(String fname) { try { if (isApplet) getAppletContext().showDocument(new URL(getDocumentBase(), fname),"_blank"); else { String path=gfname.substring(0,gfname.lastIndexOf('/')+1); InputStream is; String line, text=""; DataInputStream di; is=new FileInputStream(path+fname); di=new DataInputStream(is); while ((line=di.readLine())!=null) text+=line+"\n"; if (fname.endsWith(".html")) { /**** convert HTML to text (just a quick hack) ****/ String buf=""; char[] text2,text3; int i,j=0; boolean special=false, html=false; char ctrl; text2 = text.toCharArray(); text3 = new char[text.length()]; for (i = 0; i < text.length(); i++) { char c = text2[i]; if (c == '&') { special = true; buf = ""; } else if (special) { if (c == ';') { special = false; if (buf.equals("lt")) text3[j++] = '<'; else if (buf.equals("gt")) text3[j++] = '>'; else if (buf.equals("amp")) text3[j++] = '&'; } else buf += c; } else if (c == '<') { html = true; ctrl = text2[i+1]; if ((ctrl == 'P') || (ctrl == 'B')) text3[j++] = '\n'; } else if (c == '>') html = false; else if (!html) text3[j++] = c; } text = String.valueOf(text3); } Frame f=new TextFrame(fname.substring(fname.lastIndexOf('/')+1),text); f.resize(500,600); f.show(); } } catch (Exception exn) { System.out.println("Can't read file "+fname); } } public void PS(String fname,boolean printable) throws IOException { gv.PS(fname,printable); } public boolean isEmpty() { return tb==null; } public void initBrowser(InputStream is) { try { TreeNode tn=new TreeNode("Directories","",-1,true); gv=new GraphView(new Graph(is,tn),this); tb=new TreeBrowser(tn,gv); gv.setTreeBrowser(tb); Vector v=new Vector(10,10); tn.collapsedDirectories(v); gv.collapseDir(v); Component gv2=new Border(gv,5); Component tb2=new Border(tb,5); GridBagLayout gridbag = new GridBagLayout(); GridBagConstraints cnstr = new GridBagConstraints(); setLayout(gridbag); cnstr.fill = GridBagConstraints.BOTH; cnstr.insets = new Insets(5,5,5,5); cnstr.weightx = 1; cnstr.weighty = 1; cnstr.gridwidth = 1; gridbag.setConstraints(tb2,cnstr); add(tb2); cnstr.weightx = 2.5; cnstr.gridwidth = GridBagConstraints.REMAINDER; gridbag.setConstraints(gv2,cnstr); add(gv2); } catch (IOException exn) { System.out.println("\nI/O error while reading graph file."); } catch (ParseError exn) { System.out.println("\nParse error in graph file:"); System.out.println(exn.getMessage()); System.out.println("\nSyntax:\n<vertexname> <vertexID> <dirname> [ + ] <path> [ < | > ] [ <vertexID> [ ... [ <vertexID> ] ... ] ] ;"); } } public void init() { isApplet=true; gfname=getParameter("graphfile"); try { InputStream is=(new URL(getDocumentBase(), gfname)).openConnection().getInputStream(); initBrowser(is); is.close(); } catch (MalformedURLException exn) { System.out.println("Invalid URL: "+gfname); } catch (IOException exn) { System.out.println("I/O error while reading "+gfname+"."); } } public static void main(String[] args) { isApplet=false; try { GraphBrowser gb=new GraphBrowser(args.length > 0 ? args[0] : ""); if (args.length>0) { InputStream is=new FileInputStream(args[0]); gb.initBrowser(is); is.close(); } f=new GraphBrowserFrame(gb); f.resize(700,500); f.show(); } catch (IOException exn) { System.out.println("Can't open graph file "+args[0]); } } }
lib/browser/GraphBrowser/GraphBrowser.java
/*************************************************************************** Title: GraphBrowser/GraphBrowser.java ID: $Id$ Author: Stefan Berghofer, TU Muenchen Copyright 1997 TU Muenchen This is the graph browser's main class. It contains the "main(...)" method, which is used for the stand-alone version, as well as "init(...)", "start(...)" and "stop(...)" methods which are used for the applet version. Note: GraphBrowser is designed for the 1.0.2 version of the JDK. ***************************************************************************/ package GraphBrowser; import java.awt.*; import java.applet.*; import java.io.*; import java.util.*; import java.net.*; import awtUtilities.*; public class GraphBrowser extends Applet { GraphView gv; TreeBrowser tb=null; String gfname; static boolean isApplet; static Frame f; public GraphBrowser(String name) { gfname=name; } public GraphBrowser() {} public void showWaitMessage() { if (isApplet) getAppletContext().showStatus("calculating layout, please wait ..."); else { f.setCursor(Frame.WAIT_CURSOR); } } public void showReadyMessage() { if (isApplet) getAppletContext().showStatus("ready !"); else { f.setCursor(Frame.DEFAULT_CURSOR); } } public void viewFile(String fname) { try { if (isApplet) getAppletContext().showDocument(new URL(getDocumentBase(), fname),"_blank"); else { String path=gfname.substring(0,gfname.lastIndexOf('/')+1); InputStream is; String line, text=""; DataInputStream di; is=new FileInputStream(path+fname); di=new DataInputStream(is); while ((line=di.readLine())!=null) text+=line+"\n"; if (fname.endsWith(".html")) { /**** convert HTML to text (just a quick hack) ****/ String buf=""; char[] text2,text3; int i,j=0; boolean special=false, html=false; char ctrl; text2 = text.toCharArray(); text3 = new char[text.length()]; for (i = 0; i < text.length(); i++) { char c = text2[i]; if (c == '&') { special = true; buf = ""; } else if (special) { if (c == ';') { special = false; if (buf.equals("lt")) text3[j++] = '<'; else if (buf.equals("gt")) text3[j++] = '>'; else if (buf.equals("amp")) text3[j++] = '&'; } else buf += c; } else if (c == '<') { html = true; ctrl = text2[i+1]; if ((ctrl == 'P') || (ctrl == 'B')) text3[j++] = '\n'; } else if (c == '>') html = false; else if (!html) text3[j++] = c; } text = String.valueOf(text3); } Frame f=new TextFrame(fname.substring(fname.lastIndexOf('/')+1),text); f.resize(500,600); f.show(); } } catch (Exception exn) { System.out.println("Can't read file "+fname); } } public void PS(String fname,boolean printable) throws IOException { gv.PS(fname,printable); } public boolean isEmpty() { return tb==null; } public void initBrowser(InputStream is) { try { TreeNode tn=new TreeNode("Directories","",-1,true); gv=new GraphView(new Graph(is,tn),this); tb=new TreeBrowser(tn,gv); gv.setTreeBrowser(tb); Vector v=new Vector(10,10); tn.collapsedDirectories(v); gv.collapseDir(v); Component gv2=new Border(gv,5); Component tb2=new Border(tb,5); GridBagLayout gridbag = new GridBagLayout(); GridBagConstraints cnstr = new GridBagConstraints(); setLayout(gridbag); cnstr.fill = GridBagConstraints.BOTH; cnstr.insets = new Insets(5,5,5,5); cnstr.weightx = 1; cnstr.weighty = 1; cnstr.gridwidth = 1; gridbag.setConstraints(tb2,cnstr); add(tb2); cnstr.weightx = 2.5; cnstr.gridwidth = GridBagConstraints.REMAINDER; gridbag.setConstraints(gv2,cnstr); add(gv2); } catch (IOException exn) { System.out.println("\nI/O error while reading graph file."); } catch (ParseError exn) { System.out.println("\nParse error in graph file:"); System.out.println(exn.getMessage()); System.out.println("\nSyntax:\n<vertexname> <dirname> [ + ] <path> [ < | > ] [ <vertexname> [ ... [ <vertexname> ] ... ] ] ;"); } } public void init() { isApplet=true; gfname=getParameter("graphfile"); try { InputStream is=(new URL(getDocumentBase(), gfname)).openConnection().getInputStream(); initBrowser(is); is.close(); } catch (MalformedURLException exn) { System.out.println("Invalid URL: "+gfname); } catch (IOException exn) { System.out.println("I/O error while reading "+gfname+"."); } } public static void main(String[] args) { isApplet=false; try { GraphBrowser gb=new GraphBrowser(args.length > 0 ? args[0] : ""); if (args.length>0) { InputStream is=new FileInputStream(args[0]); gb.initBrowser(is); is.close(); } f=new GraphBrowserFrame(gb); f.resize(700,500); f.show(); } catch (IOException exn) { System.out.println("Can't open graph file "+args[0]); } } }
Modified parse error message.
lib/browser/GraphBrowser/GraphBrowser.java
Modified parse error message.
Java
mit
947abcf6db22bb2bbdd39b12f520476884d37889
0
przodownikR1/nbpExchangeRatesMicroService,przodownikR1/nbpExchangeRatesMicroService,przodownikR1/nbpExchangeRatesMicroService
package pl.java.scalatech.spring_camel.route; import org.apache.camel.builder.RouteBuilder; import org.springframework.stereotype.Component; import pl.java.scalatech.spring_camel.eip.RecipientListBean; @Component public class HttpRoute extends RouteBuilder { @Override public void configure() throws Exception { RecipientListBean rl = new RecipientListBean("file://outbox?fileName=${date:now:yyyyMMddHHmmss}.xml", "stream:out"); from("timer://nbp?fixedRate=true&delay=0&period=1800000") .to("http://www.nbp.pl/kursy/xml/LastA.xml") .convertBodyTo(String.class).recipientList(method(rl, "route")); } }
src/main/java/pl/java/scalatech/spring_camel/route/HttpRoute.java
package pl.java.scalatech.spring_camel.route; import org.apache.camel.builder.RouteBuilder; import org.springframework.stereotype.Component; import pl.java.scalatech.spring_camel.eip.RecipientListBean; @Component public class HttpRoute extends RouteBuilder { @Override public void configure() throws Exception { RecipientListBean rl = new RecipientListBean("file://outbox?fileName=${date:now:yyyyMMddHHmmss}.xml", "stream:out"); from("timer://nbp?fixedRate=true&delay=0&period=5000") .to("http://www.nbp.pl/kursy/xml/LastA.xml") .convertBodyTo(String.class).recipientList(method(rl, "route")); } }
http fetch content from website added
src/main/java/pl/java/scalatech/spring_camel/route/HttpRoute.java
http fetch content from website added
Java
mit
d907c48b42c6ac5d43391735f479d736aa573064
0
natemara/databases-project,natemara/databases-project
import javax.swing.*; import javax.swing.table.DefaultTableModel; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; /** * Created by loomisdf on 4/10/2016. */ public class DatabaseFrame{ private JFrame frame; private JLabel descriptionLabel, userGreeting; private JPanel panel; private JPanel loginScreen; private JButton goButton; private JButton purchaseButton; private JTable gameTable; private DefaultTableModel tableModel; private JComboBox dropdown; private JTabbedPane userScreen; private JButton friends; private JButton ownedGames; private JTable userTable; private DefaultTableModel tableModel2; private JPanel gameListPanel; private JPanel gamePagePanel; private JLabel gameNameLabel; private JScrollPane gameTableScrollPane; private User currentUser; public DatabaseFrame() { frame = new JFrame("Database Frame"); panel = new JPanel(); descriptionLabel = new JLabel("Welcome to the DB"); // Various creation operations createDropdown(); createButtons(); createTable(); createUserScreen(); createLoginScreen(); // Setup JFrame frame.setSize(500, 550); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setBackground(Color.WHITE); // Add things to panel panel.add(userScreen); panel.add(loginScreen); // Add panel to frame frame.add(panel); // Set the frame visible frame.setVisible(true); } private void createLoginScreen() { loginScreen = new JPanel(); // Create Labels JLabel userLabel = new JLabel("Username:"); JLabel passLabel = new JLabel("Password:"); final JLabel userNotFoundWarning = new JLabel("User not found!"); userNotFoundWarning.setForeground(Color.red); userNotFoundWarning.setVisible(false); final JLabel invalidPasswordWarning = new JLabel("Invalid password!"); invalidPasswordWarning.setForeground(Color.red); invalidPasswordWarning.setVisible(false); // Create Inputs final JTextField userNameInput = new JTextField(15); final JPasswordField passInput = new JPasswordField(15); // Button Functionality JButton loginButton = new JButton("Login"); loginButton.addActionListener((ActionEvent e) -> { currentUser = User.getUserByProfileName(userNameInput.getText()); if(currentUser != null) { if (currentUser.isPasswordValid(String.valueOf(passInput.getPassword()))) { loginScreen.setVisible(false); userGreeting.setText("Hello " + currentUser.profileName); userScreen.setVisible(true); } else { invalidPasswordWarning.setVisible(true); } } else { userNotFoundWarning.setVisible(true); } }); loginScreen.add(userLabel); loginScreen.add(userNameInput); loginScreen.add(passLabel); loginScreen.add(passInput); loginScreen.add(loginButton); loginScreen.add(userNotFoundWarning); loginScreen.add(invalidPasswordWarning); loginScreen.setLayout(new BoxLayout(loginScreen, BoxLayout.PAGE_AXIS)); } private void createUserScreen() { userScreen = new JTabbedPane(); // Store Panel JPanel card1 = new JPanel(); gameListPanel = new JPanel(); gameListPanel.add(descriptionLabel); gameListPanel.add(dropdown); gameListPanel.add(goButton); gameListPanel.add(purchaseButton); gameListPanel.setLayout(new FlowLayout()); //Create the gamePanel createGamePagePanel(); gamePagePanel.setVisible(false); card1.add(gameListPanel); card1.add(gamePagePanel); gameTableScrollPane = new JScrollPane(gameTable); card1.add(gameTableScrollPane); card1.setLayout(new BoxLayout(card1, BoxLayout.Y_AXIS)); // User Page JPanel card2 = new JPanel(); userGreeting = new JLabel("Hello Unknown User"); card2.add(userGreeting); card2.add(friends); card2.add(ownedGames); card2.add(new JScrollPane(userTable)); card2.setLayout(new BoxLayout(card2, BoxLayout.Y_AXIS)); userScreen.addTab("Store", card1); userScreen.addTab("User Page", card2); userScreen.setVisible(false); } private void createDropdown() { String[] options = {"Show All Games", "Show All Categories"}; dropdown = new JComboBox(options); } private void createTable() { gameTable = new JTable(); userTable = new JTable(); tableModel = new DefaultTableModel(0, 0); tableModel2 = new DefaultTableModel(0, 0); // Double click on a game title gameTable.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { JTable table =(JTable) me.getSource(); Point p = me.getPoint(); int row = table.rowAtPoint(p); String gameTitle = (String) table.getValueAt(row, 0); if (me.getClickCount() == 2) { // your valueChanged overridden method gameListPanel.setVisible(false); updateGamePagePanel(gameTitle); gamePagePanel.setVisible(true); gameTableScrollPane.setVisible(false); } } }); } public void replaceTable(JTable cTable, DefaultTableModel model, Object rowData[][], Object columns[]) { if(rowData == null || columns == null) return; model.setColumnIdentifiers(columns); cTable.setModel(model); // Remove Rows if (model.getRowCount() > 0) { for (int i = model.getRowCount() - 1; i > -1; i--) { model.removeRow(i); } } // Add new rows for(int r = 0; r < rowData.length; r++) { model.addRow(rowData[r]); } } private void createGamePagePanel() { gamePagePanel = new JPanel(); gameNameLabel = new JLabel("This shouldn't be showing yet"); gamePagePanel.add(gameNameLabel); } private void updateGamePagePanel(String gameName) { gamePagePanel.setVisible(true); gameNameLabel.setText(gameName); } private void createButtons() { goButton = new JButton("Go!"); goButton.addActionListener((ActionEvent e) -> { String operation = (String) dropdown.getSelectedItem(); switch(operation) { case("Show All Games"): { TableInfo t = new TableInfo(Game.getAllGames()); replaceTable(gameTable,tableModel,t.rowData, t.columns); purchaseButton.setVisible(true); break; } case("Show All Categories") : { TableInfo t = new TableInfo(Category.getAllCategories()); replaceTable(gameTable,tableModel, t.rowData, t.columns); purchaseButton.setVisible(false); break; } } }); purchaseButton = new JButton("Purchase"); purchaseButton.setVisible(false); purchaseButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int row = gameTable.getSelectedRow(); int GameId = (Integer) gameTable.getValueAt(row,1); ErrorCode errorCode = currentUser.purchaseGame(GameId); if(errorCode.result == ErrorResult.FAIL) { JOptionPane.showMessageDialog(frame, errorCode.message); } else if(errorCode.result == ErrorResult.SUCCESS) { JOptionPane.showMessageDialog(frame, errorCode.message); } if (row == -1) { return; } } }); friends = new JButton("Friends"); friends.addActionListener((ActionEvent e) -> { TableInfo t = new TableInfo(currentUser.friends()); if(t.columns != null) { replaceTable(userTable, tableModel2, t.rowData, t.columns); } else { JOptionPane.showMessageDialog(frame, "You have no friends :("); } }); ownedGames = new JButton("My Games"); ownedGames.addActionListener((ActionEvent e) -> { TableInfo t = new TableInfo(currentUser.games()); if (t.columns != null) replaceTable(userTable, tableModel2, t.rowData, t.columns); else JOptionPane.showMessageDialog(frame, "You have no games :("); }); } }
src/main/java/DatabaseFrame.java
import javax.swing.*; import javax.swing.table.DefaultTableModel; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; /** * Created by loomisdf on 4/10/2016. */ public class DatabaseFrame{ private JFrame frame; private JLabel descriptionLabel, userGreeting; private JPanel panel; private JPanel loginScreen; private JButton goButton; private JButton purchaseButton; private JTable gameTable; private DefaultTableModel tableModel; private JComboBox dropdown; private JTabbedPane userScreen; private JButton friends; private JButton ownedGames; private JTable userTable; private DefaultTableModel tableModel2; private JPanel gameListPanel; private JPanel gamePagePanel; private JLabel gameNameLabel; private JScrollPane gameTableScrollPane; private User currentUser; public DatabaseFrame() { frame = new JFrame("Database Frame"); panel = new JPanel(); descriptionLabel = new JLabel("Welcome to the DB"); // Various creation operations createDropdown(); createButtons(); createTable(); createUserScreen(); createLoginScreen(); // Setup JFrame frame.setSize(500, 550); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setBackground(Color.WHITE); // Add things to panel panel.add(userScreen); panel.add(loginScreen); // Add panel to frame frame.add(panel); // Set the frame visible frame.setVisible(true); } private void createLoginScreen() { loginScreen = new JPanel(); // Create Labels JLabel userLabel = new JLabel("Username:"); JLabel passLabel = new JLabel("Password:"); final JLabel userNotFoundWarning = new JLabel("User not found!"); userNotFoundWarning.setForeground(Color.red); userNotFoundWarning.setVisible(false); final JLabel invalidPasswordWarning = new JLabel("Invalid password!"); invalidPasswordWarning.setForeground(Color.red); invalidPasswordWarning.setVisible(false); // Create Inputs final JTextField userNameInput = new JTextField(15); final JPasswordField passInput = new JPasswordField(15); // Button Functionality JButton loginButton = new JButton("Login"); loginButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { currentUser = User.getUserByProfileName(userNameInput.getText()); if(currentUser != null) { if (currentUser.isPasswordValid(String.valueOf(passInput.getPassword()))) { loginScreen.setVisible(false); userGreeting.setText("Hello " + currentUser.profileName); userScreen.setVisible(true); } else { invalidPasswordWarning.setVisible(true); } } else { userNotFoundWarning.setVisible(true); } } }); loginScreen.add(userLabel); loginScreen.add(userNameInput); loginScreen.add(passLabel); loginScreen.add(passInput); loginScreen.add(loginButton); loginScreen.add(userNotFoundWarning); loginScreen.add(invalidPasswordWarning); loginScreen.setLayout(new BoxLayout(loginScreen, BoxLayout.PAGE_AXIS)); } private void createUserScreen() { userScreen = new JTabbedPane(); // Store Panel JPanel card1 = new JPanel(); gameListPanel = new JPanel(); gameListPanel.add(descriptionLabel); gameListPanel.add(dropdown); gameListPanel.add(goButton); gameListPanel.add(purchaseButton); gameListPanel.setLayout(new FlowLayout()); //Create the gamePanel createGamePagePanel(); gamePagePanel.setVisible(false); card1.add(gameListPanel); card1.add(gamePagePanel); gameTableScrollPane = new JScrollPane(gameTable); card1.add(gameTableScrollPane); card1.setLayout(new BoxLayout(card1, BoxLayout.Y_AXIS)); // User Page JPanel card2 = new JPanel(); userGreeting = new JLabel("Hello Unknown User"); card2.add(userGreeting); card2.add(friends); card2.add(ownedGames); card2.add(new JScrollPane(userTable)); card2.setLayout(new BoxLayout(card2, BoxLayout.Y_AXIS)); userScreen.addTab("Store", card1); userScreen.addTab("User Page", card2); userScreen.setVisible(false); } private void createDropdown() { String[] options = {"Show All Games", "Show All Categories"}; dropdown = new JComboBox(options); } private void createTable() { gameTable = new JTable(); userTable = new JTable(); tableModel = new DefaultTableModel(0, 0); tableModel2 = new DefaultTableModel(0, 0); // Double click on a game title gameTable.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { JTable table =(JTable) me.getSource(); Point p = me.getPoint(); int row = table.rowAtPoint(p); String gameTitle = (String) table.getValueAt(row, 0); if (me.getClickCount() == 2) { // your valueChanged overridden method gameListPanel.setVisible(false); updateGamePagePanel(gameTitle); gamePagePanel.setVisible(true); gameTableScrollPane.setVisible(false); } } }); } public void replaceTable(JTable cTable, DefaultTableModel model, Object rowData[][], Object columns[]) { if(rowData == null || columns == null) return; model.setColumnIdentifiers(columns); cTable.setModel(model); // Remove Rows if (model.getRowCount() > 0) { for (int i = model.getRowCount() - 1; i > -1; i--) { model.removeRow(i); } } // Add new rows for(int r = 0; r < rowData.length; r++) { model.addRow(rowData[r]); } } private void createGamePagePanel() { gamePagePanel = new JPanel(); gameNameLabel = new JLabel("This shouldn't be showing yet"); gamePagePanel.add(gameNameLabel); } private void updateGamePagePanel(String gameName) { gamePagePanel.setVisible(true); gameNameLabel.setText(gameName); } private void createButtons() { goButton = new JButton("Go!"); goButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String operation = (String) dropdown.getSelectedItem(); switch(operation) { case("Show All Games"): { TableInfo t = new TableInfo(Game.getAllGames()); replaceTable(gameTable,tableModel,t.rowData, t.columns); purchaseButton.setVisible(true); break; } case("Show All Categories") : { TableInfo t = new TableInfo(Category.getAllCategories()); replaceTable(gameTable,tableModel, t.rowData, t.columns); purchaseButton.setVisible(false); break; } } } }); purchaseButton = new JButton("Purchase"); purchaseButton.setVisible(false); purchaseButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int row = gameTable.getSelectedRow(); int GameId = (Integer) gameTable.getValueAt(row,1); ErrorCode errorCode = currentUser.purchaseGame(GameId); if(errorCode.result == ErrorResult.FAIL) { JOptionPane.showMessageDialog(frame, errorCode.message); } else if(errorCode.result == ErrorResult.SUCCESS) { JOptionPane.showMessageDialog(frame, errorCode.message); } if (row == -1) { return; } } }); friends = new JButton("Friends"); friends.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { TableInfo t = new TableInfo(currentUser.friends()); if(t.columns != null) { replaceTable(userTable, tableModel2, t.rowData, t.columns); } else { JOptionPane.showMessageDialog(frame, "You have no friends :("); } } }); ownedGames = new JButton("My Games"); ownedGames.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { TableInfo t = new TableInfo(currentUser.games()); if (t.columns != null) replaceTable(userTable, tableModel2, t.rowData, t.columns); else JOptionPane.showMessageDialog(frame, "You have no games :("); } }); } }
Stop using deprecated ActionEvent API
src/main/java/DatabaseFrame.java
Stop using deprecated ActionEvent API
Java
mit
777d4312ac9e20f76bb6e29c101a1c7a062a2f1c
0
tzulberti/archery-training
package ar.com.tzulberti.archerytraining.activities.common; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.MotionEvent; import android.view.View; import android.view.ViewTreeObserver; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import java.util.Collections; import java.util.Comparator; import ar.com.tzulberti.archerytraining.R; import ar.com.tzulberti.archerytraining.helper.TournamentHelper; import ar.com.tzulberti.archerytraining.model.base.AbstractArrow; import ar.com.tzulberti.archerytraining.model.base.ISerie; /** * Created by tzulberti on 6/3/17. */ public abstract class AbstractSerieArrowsActivity extends BaseArcheryTrainingActivity implements View.OnTouchListener, View.OnLongClickListener { public static final String SERIE_ARGUMENT_KEY = "serie"; public static final String CONTAINER_ARGUMENT_KEY = "container"; public static final float IMAGE_WIDTH = 512; public static final float ARROW_IMPACT_RADIUS = 5; private static final int Y_PADDING = -80; private ImageView targetImageView; private TextView[] currentScoreText; private TextView totalSerieScoreText; private Button previousSerieButton; private Button nextSerieButton; private Button arrowUndoButton; private float targetCenterX = -1; private float targetCenterY = -1; private float imageScale = -1; private float pointWidth = -1; private Bitmap imageBitmap; private Paint currentImpactPaint; private Paint finalImpactPaint; private boolean canGoBack; protected ISerie serie; /** * @return the id of the layout that is going to be shown */ protected abstract int getLayoutResource(); /** * Shows additional information on the view (for example, the tournament score, or the playoff * score) */ protected abstract void setAdditionalInformation(); /** * Saves the serie information using the different datos */ protected abstract void saveSerie(); /** * Deletes the current serie that the user is saving * <p> * This is used when the user goes back before finishing the current serie */ protected abstract void deleteSerie(); /** * Add an arrow to the current serie * <p> * This should also update the serie total score, and all those kind of values * * @param x * @param y * @param score * @param isX */ protected abstract void addArrowData(float x, float y, int score, boolean isX); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(this.getLayoutResource()); this.serie = (ISerie)this.getIntent().getSerializableExtra(SERIE_ARGUMENT_KEY); this.createDAOs(); this.targetImageView = (ImageView) this.findViewById(R.id.photo_view); this.targetImageView.setOnTouchListener(this); this.targetImageView.setOnLongClickListener(this); this.currentImpactPaint = new Paint(); this.currentImpactPaint.setAntiAlias(true); this.currentImpactPaint.setColor(Color.MAGENTA); this.finalImpactPaint = new Paint(); this.finalImpactPaint.setAntiAlias(true); this.finalImpactPaint.setColor(Color.LTGRAY); this.currentScoreText = new TextView[6]; this.currentScoreText[0] = (TextView) this.findViewById(R.id.current_score1); this.currentScoreText[1] = (TextView) this.findViewById(R.id.current_score2); this.currentScoreText[2] = (TextView) this.findViewById(R.id.current_score3); this.currentScoreText[3] = (TextView) this.findViewById(R.id.current_score4); this.currentScoreText[4] = (TextView) this.findViewById(R.id.current_score5); this.currentScoreText[5] = (TextView) this.findViewById(R.id.current_score6); this.nextSerieButton = (Button) this.findViewById(R.id.btn_serie_next); this.previousSerieButton = (Button) this.findViewById(R.id.btn_serie_previous); this.arrowUndoButton = (Button) this.findViewById(R.id.btn_arrow_undo); this.nextSerieButton.setEnabled(false); this.previousSerieButton.setEnabled(false); ViewTreeObserver vto = this.targetImageView.getViewTreeObserver(); vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { targetImageView.getViewTreeObserver().removeOnPreDrawListener(this); initializeValues(); return true; } }); ((TextView) this.findViewById(R.id.serie_index)).setText(getString(R.string.tournament_serie_current_serie, this.serie.getIndex())); this.setAdditionalInformation(); this.totalSerieScoreText = (TextView) this.findViewById(R.id.total_serie_score); } protected void initializeValues() { this.imageScale = Math.min(this.targetImageView.getWidth(), this.targetImageView.getHeight()) / IMAGE_WIDTH; this.targetCenterX = this.targetImageView.getWidth() / (2 * this.imageScale); this.targetCenterY = this.targetImageView.getHeight() / (2 * this.imageScale); this.pointWidth = Math.min(this.targetCenterX, this.targetCenterY) / 10; this.showSeriesArrow(); // if viewing an already existing serie, then disable the undo button since // the serie was already saved, or it is disabled because the serie has no // arrow information this.arrowUndoButton.setEnabled(false); if (this.canActivateButtons()) { this.nextSerieButton.setEnabled(true); this.previousSerieButton.setEnabled(this.serie.getIndex() > 1); } if (this.hasFinished()) { this.nextSerieButton.setText(getText(R.string.tournament_serie_end)); } } /** * Take care of creating the correct bitmap and showing those on the target */ protected void showSeriesArrow() { BitmapFactory.Options myOptions = new BitmapFactory.Options(); myOptions.inScaled = false; myOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;// important Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.complete_archery_target, myOptions); Paint paint = new Paint(); paint.setAntiAlias(true); paint.setColor(Color.BLUE); this.imageBitmap = Bitmap.createBitmap(bitmap); if (this.serie.getArrows().size() == 0) { // if there is no serie, then show the empty target. This is used // when undoing the first added arrow this.targetImageView.setAdjustViewBounds(true); this.targetImageView.setImageBitmap(this.imageBitmap); } else { int arrowIndex = 0; for (AbstractArrow serieArrow : this.serie.getArrows()) { this.addTargetImpact(serieArrow.xPosition, serieArrow.yPosition, true, true, arrowIndex); arrowIndex += 1; } } } @Override public boolean onTouch(View v, MotionEvent event) { int numberOfArrows = this.serie.getArrows().size(); if (this.canActivateButtons()) { // already got the max number of arrows so there is nothing specific to do return false; } int eventAction = event.getAction(); boolean isFinal = false; if (eventAction == MotionEvent.ACTION_DOWN || eventAction == MotionEvent.ACTION_MOVE || eventAction == MotionEvent.ACTION_UP) { isFinal = (eventAction == MotionEvent.ACTION_UP); this.addTargetImpact(event.getX() / this.imageScale, event.getY() / this.imageScale, isFinal, false, numberOfArrows); } if (isFinal && this.canActivateButtons()) { // enable the buttons to save the current serie if (this.serie.getIndex() > 1) { this.previousSerieButton.setEnabled(true); } this.nextSerieButton.setEnabled(true); // update the series information after updating the arrows by it's score // so it can be showed on that order Collections.sort(this.serie.getArrows(), new Comparator<AbstractArrow>() { @Override public int compare(AbstractArrow o1, AbstractArrow o2) { int res = 0; if (o1.isX && !o2.isX) { res = 1; } else if (!o1.isX && o2.isX) { res = -1; } else if (o1.score > o2.score) { res = 1; } else if (o1.score < o2.score) { res = -1; } res = -1 * res; return res; } }); this.saveSerie(); } return false; } private void addTargetImpact(float x, float y, boolean isFinal, boolean showingExisting, int arrowIndex) { Bitmap mutableBitmap = this.imageBitmap.copy(Bitmap.Config.ARGB_8888, true); Paint paint = this.finalImpactPaint; if (isFinal) { this.imageBitmap = mutableBitmap; } else { paint = this.currentImpactPaint; } Canvas canvas = new Canvas(mutableBitmap); if (!showingExisting) { y = y + Y_PADDING; } canvas.drawCircle(x, y, ARROW_IMPACT_RADIUS, paint); double distance = Math.sqrt(Math.pow(x - this.targetCenterX, 2) + Math.pow(y - this.targetCenterY, 2)); int score = (int) (10 - Math.floor(distance / this.pointWidth)); if (score < 0) { score = 0; } boolean isX = (score == 10 && (distance / this.pointWidth) < 0.5); this.targetImageView.setAdjustViewBounds(true); this.targetImageView.setImageBitmap(mutableBitmap); TextView scoreText = this.currentScoreText[arrowIndex]; scoreText.getBackground().setColorFilter(new PorterDuffColorFilter(TournamentHelper.getBackground(score), PorterDuff.Mode.SRC_IN)); scoreText.setText(TournamentHelper.getUserScore(score, isX)); scoreText.setTextColor(TournamentHelper.getFontColor(score)); if (isFinal && !showingExisting) { this.addArrowData(x, y, score, isX); this.serie.updateTotalScore(score); } if (isFinal) { this.totalSerieScoreText.setText(String.format("%s / %s", this.serie.getTotalScore(), this.serie.getContainer().getSerieMaxPossibleScore())); this.arrowUndoButton.setEnabled(true); } } public void goToPreviousSerie(View v) { // -2 is required because the first index is 1. ISerie transitionSerie = this.serie.getContainer().getSeries().get(this.serie.getIndex() - 2); Intent intent = new Intent(this, AbstractSerieArrowsActivity.class); intent.putExtra(AbstractSerieArrowsActivity.SERIE_ARGUMENT_KEY, transitionSerie); startActivity(intent); } public void undoLastArrow(View v) { TextView scoreText = this.currentScoreText[this.serie.getArrows().size() - 1]; scoreText.setText(""); scoreText.setBackgroundResource(R.drawable.rounded); // remove the last added arrow AbstractArrow arrowToRemove = this.serie.getArrows().get(this.serie.getArrows().size() - 1); this.serie.getArrows().remove(this.serie.getArrows().size() - 1); this.serie.updateTotalScore(0 - arrowToRemove.score); // disable the buttons if they were enabled this.previousSerieButton.setEnabled(false); this.nextSerieButton.setEnabled(false); // update the total score of the serie this.totalSerieScoreText.setText(String.format("%s / %s", this.serie.getTotalScore(), this.serie.getContainer().getSerieMaxPossibleScore())); // removed only arrow for the current serie so he can not undo anymore if (this.serie.getArrows().size() == 0) { this.arrowUndoButton.setEnabled(false); } // redraw all the arrows on the target to remove the last added arrow this.showSeriesArrow(); } public void goToNextOrEnd(View v) { ISerie transitionSerie = null; if (this.hasFinished()) { Intent intent = new Intent(this, this.getContainerDetailsFragment()); intent.putExtra(CONTAINER_ARGUMENT_KEY, this.serie.getContainer()); startActivity(intent); return; } else if (this.serie.getContainer().getSeries().size() > this.serie.getIndex()) { // same here... there isn't any need to add +1 because the serie already starts at 1 transitionSerie = this.serie.getContainer().getSeries().get(this.serie.getIndex()); } else { // creating a new serie for the tournament transitionSerie = this.createNewSerie(); } Intent intent = new Intent(this, this.getClass()); intent.putExtra(AbstractSerieArrowsActivity.SERIE_ARGUMENT_KEY, transitionSerie); startActivity(intent); } /** * Used to shown the container details when the user alread finished loading * all the possible series */ protected abstract Class<? extends AppCompatActivity> getContainerDetailsFragment(); /** * Used to show the previous or next serie. * * @return the fragment to be shown */ protected abstract AbstractSerieArrowsActivity getSerieDetailsFragment(); /** * Creates the new serie on the database * * @return */ protected abstract ISerie createNewSerie(); /** * Indicates if it can activate the next, and previous buttons * @return */ protected abstract boolean canActivateButtons(); /** * Indicates if no more series can be loaded * @return */ protected abstract boolean hasFinished(); @Override public boolean onLongClick(View v) { return false; } @Override public void onBackPressed() { if (this.canGoBack()) { super.onBackPressed(); } } public boolean canGoBack() { if (this.canActivateButtons()) { // if the serie is created with 6 arrows, then it doesnt has any issue // if the user go back return true; } if (this.canGoBack) { // if the user already confirmed that he can go back, then it should do it return true; } final AbstractSerieArrowsActivity self = this; new AlertDialog.Builder(this) .setTitle(R.string.common_confirmation_dialog_title) .setMessage(R.string.tournament_view_serie_creating_back) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { self.canGoBack = true; self.deleteSerie(); self.onBackPressed(); }}) .setNegativeButton(android.R.string.no, null) .show(); // ask the user if he is sure to go back or not return false; } }
app/src/main/java/ar/com/tzulberti/archerytraining/activities/common/AbstractSerieArrowsActivity.java
package ar.com.tzulberti.archerytraining.activities.common; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.MotionEvent; import android.view.View; import android.view.ViewTreeObserver; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import java.util.Collections; import java.util.Comparator; import ar.com.tzulberti.archerytraining.R; import ar.com.tzulberti.archerytraining.helper.TournamentHelper; import ar.com.tzulberti.archerytraining.model.base.AbstractArrow; import ar.com.tzulberti.archerytraining.model.base.ISerie; /** * Created by tzulberti on 6/3/17. */ public abstract class AbstractSerieArrowsActivity extends BaseArcheryTrainingActivity implements View.OnTouchListener, View.OnLongClickListener { public static final String SERIE_ARGUMENT_KEY = "serie"; public static final String CONTAINER_ARGUMENT_KEY = "container"; public static final float IMAGE_WIDTH = 512; public static final float ARROW_IMPACT_RADIUS = 5; private static final int Y_PADDING = -80; private ImageView targetImageView; private TextView[] currentScoreText; private TextView totalSerieScoreText; private Button previousSerieButton; private Button nextSerieButton; private Button arrowUndoButton; private float targetCenterX = -1; private float targetCenterY = -1; private float imageScale = -1; private float pointWidth = -1; private Bitmap imageBitmap; private Paint currentImpactPaint; private Paint finalImpactPaint; private boolean canGoBack; protected ISerie serie; /** * @return the id of the layout that is going to be shown */ protected abstract int getLayoutResource(); /** * Shows additional information on the view (for example, the tournament score, or the playoff * score) */ protected abstract void setAdditionalInformation(); /** * Saves the serie information using the different datos */ protected abstract void saveSerie(); /** * Deletes the current serie that the user is saving * <p> * This is used when the user goes back before finishing the current serie */ protected abstract void deleteSerie(); /** * Add an arrow to the current serie * <p> * This should also update the serie total score, and all those kind of values * * @param x * @param y * @param score * @param isX */ protected abstract void addArrowData(float x, float y, int score, boolean isX); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(this.getLayoutResource()); this.serie = (ISerie)this.getIntent().getSerializableExtra(SERIE_ARGUMENT_KEY); this.createDAOs(); this.targetImageView = (ImageView) this.findViewById(R.id.photo_view); this.targetImageView.setOnTouchListener(this); this.targetImageView.setOnLongClickListener(this); this.currentImpactPaint = new Paint(); this.currentImpactPaint.setAntiAlias(true); this.currentImpactPaint.setColor(Color.MAGENTA); this.finalImpactPaint = new Paint(); this.finalImpactPaint.setAntiAlias(true); this.finalImpactPaint.setColor(Color.LTGRAY); this.currentScoreText = new TextView[6]; this.currentScoreText[0] = (TextView) this.findViewById(R.id.current_score1); this.currentScoreText[1] = (TextView) this.findViewById(R.id.current_score2); this.currentScoreText[2] = (TextView) this.findViewById(R.id.current_score3); this.currentScoreText[3] = (TextView) this.findViewById(R.id.current_score4); this.currentScoreText[4] = (TextView) this.findViewById(R.id.current_score5); this.currentScoreText[5] = (TextView) this.findViewById(R.id.current_score6); this.nextSerieButton = (Button) this.findViewById(R.id.btn_serie_next); this.previousSerieButton = (Button) this.findViewById(R.id.btn_serie_previous); this.arrowUndoButton = (Button) this.findViewById(R.id.btn_arrow_undo); this.nextSerieButton.setEnabled(false); this.previousSerieButton.setEnabled(false); ViewTreeObserver vto = this.targetImageView.getViewTreeObserver(); vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { targetImageView.getViewTreeObserver().removeOnPreDrawListener(this); initializeValues(); return true; } }); ((TextView) this.findViewById(R.id.serie_index)).setText(getString(R.string.tournament_serie_current_serie, this.serie.getIndex())); this.setAdditionalInformation(); this.totalSerieScoreText = (TextView) this.findViewById(R.id.total_serie_score); } protected void initializeValues() { this.imageScale = Math.min(this.targetImageView.getWidth(), this.targetImageView.getHeight()) / IMAGE_WIDTH; this.targetCenterX = this.targetImageView.getWidth() / (2 * this.imageScale); this.targetCenterY = this.targetImageView.getHeight() / (2 * this.imageScale); this.pointWidth = Math.min(this.targetCenterX, this.targetCenterY) / 10; this.showSeriesArrow(); // if viewing an already existing serie, then disable the undo button since // the serie was already saved, or it is disabled because the serie has no // arrow information this.arrowUndoButton.setEnabled(false); if (this.canActivateButtons()) { this.nextSerieButton.setEnabled(true); this.previousSerieButton.setEnabled(this.serie.getIndex() > 1); } if (this.hasFinished()) { this.nextSerieButton.setText(getText(R.string.tournament_serie_end)); } } /** * Take care of creating the correct bitmap and showing those on the target */ protected void showSeriesArrow() { BitmapFactory.Options myOptions = new BitmapFactory.Options(); myOptions.inScaled = false; myOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;// important Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.complete_archery_target, myOptions); Paint paint = new Paint(); paint.setAntiAlias(true); paint.setColor(Color.BLUE); this.imageBitmap = Bitmap.createBitmap(bitmap); if (this.serie.getArrows().size() == 0) { // if there is no serie, then show the empty target. This is used // when undoing the first added arrow this.targetImageView.setAdjustViewBounds(true); this.targetImageView.setImageBitmap(this.imageBitmap); } else { int arrowIndex = 0; for (AbstractArrow serieArrow : this.serie.getArrows()) { this.addTargetImpact(serieArrow.xPosition, serieArrow.yPosition, true, true, arrowIndex); arrowIndex += 1; } } } @Override public boolean onTouch(View v, MotionEvent event) { int numberOfArrows = this.serie.getArrows().size(); if (this.canActivateButtons()) { // already got the max number of arrows so there is nothing specific to do return false; } int eventAction = event.getAction(); boolean isFinal = false; if (eventAction == MotionEvent.ACTION_DOWN || eventAction == MotionEvent.ACTION_MOVE || eventAction == MotionEvent.ACTION_UP) { isFinal = (eventAction == MotionEvent.ACTION_UP); this.addTargetImpact(event.getX() / this.imageScale, event.getY() / this.imageScale, isFinal, false, numberOfArrows); } if (isFinal && this.canActivateButtons()) { // enable the buttons to save the current serie if (this.serie.getIndex() > 1) { this.previousSerieButton.setEnabled(true); } this.nextSerieButton.setEnabled(true); // update the series information after updating the arrows by it's score // so it can be showed on that order Collections.sort(this.serie.getArrows(), new Comparator<AbstractArrow>() { @Override public int compare(AbstractArrow o1, AbstractArrow o2) { int res = 0; if (o1.isX && !o2.isX) { res = 1; } else if (!o1.isX && o2.isX) { res = -1; } else if (o1.score > o2.score) { res = 1; } else if (o1.score < o2.score) { res = -1; } res = -1 * res; return res; } }); this.saveSerie(); } return false; } private void addTargetImpact(float x, float y, boolean isFinal, boolean showingExisting, int arrowIndex) { Bitmap mutableBitmap = this.imageBitmap.copy(Bitmap.Config.ARGB_8888, true); Paint paint = this.finalImpactPaint; if (isFinal) { this.imageBitmap = mutableBitmap; } else { paint = this.currentImpactPaint; } Canvas canvas = new Canvas(mutableBitmap); if (!showingExisting) { y = y + Y_PADDING; } canvas.drawCircle(x, y, ARROW_IMPACT_RADIUS, paint); double distance = Math.sqrt(Math.pow(x - this.targetCenterX, 2) + Math.pow(y - this.targetCenterY, 2)); int score = (int) (10 - Math.floor(distance / this.pointWidth)); if (score < 0) { score = 0; } boolean isX = (score == 10 && (distance / this.pointWidth) < 0.5); this.targetImageView.setAdjustViewBounds(true); this.targetImageView.setImageBitmap(mutableBitmap); TextView scoreText = this.currentScoreText[arrowIndex]; scoreText.getBackground().setColorFilter(new PorterDuffColorFilter(TournamentHelper.getBackground(score), PorterDuff.Mode.SRC_IN)); scoreText.setText(TournamentHelper.getUserScore(score, isX)); scoreText.setTextColor(TournamentHelper.getFontColor(score)); if (isFinal && !showingExisting) { this.addArrowData(x, y, score, isX); this.serie.updateTotalScore(score); } if (isFinal) { this.totalSerieScoreText.setText(String.format("%s / %s", this.serie.getTotalScore(), this.serie.getContainer().getSerieMaxPossibleScore())); this.arrowUndoButton.setEnabled(true); } } public void goToPreviousSerie(View v) { // -2 is required because the first index is 1. ISerie transitionSerie = this.serie.getContainer().getSeries().get(this.serie.getIndex() - 2); Intent intent = new Intent(this, AbstractSerieArrowsActivity.class); intent.putExtra(AbstractSerieArrowsActivity.SERIE_ARGUMENT_KEY, transitionSerie); startActivity(intent); } public void undoLastArrow(View v) { TextView scoreText = this.currentScoreText[this.serie.getArrows().size() - 1]; scoreText.setText(""); scoreText.getBackground().setColorFilter(new PorterDuffColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN)); // remove the last added arrow AbstractArrow arrowToRemove = this.serie.getArrows().get(this.serie.getArrows().size() - 1); this.serie.getArrows().remove(this.serie.getArrows().size() - 1); this.serie.updateTotalScore(0 - arrowToRemove.score); // disable the buttons if they were enabled this.previousSerieButton.setEnabled(false); this.nextSerieButton.setEnabled(false); // update the total score of the serie this.totalSerieScoreText.setText(String.format("%s / %s", this.serie.getTotalScore(), this.serie.getContainer().getSerieMaxPossibleScore())); // removed only arrow for the current serie so he can not undo anymore if (this.serie.getArrows().size() == 0) { this.arrowUndoButton.setEnabled(false); } // redraw all the arrows on the target to remove the last added arrow this.showSeriesArrow(); } public void goToNextOrEnd(View v) { ISerie transitionSerie = null; if (this.hasFinished()) { Intent intent = new Intent(this, this.getContainerDetailsFragment()); intent.putExtra(CONTAINER_ARGUMENT_KEY, this.serie.getContainer()); startActivity(intent); return; } else if (this.serie.getContainer().getSeries().size() > this.serie.getIndex()) { // same here... there isn't any need to add +1 because the serie already starts at 1 transitionSerie = this.serie.getContainer().getSeries().get(this.serie.getIndex()); } else { // creating a new serie for the tournament transitionSerie = this.createNewSerie(); } Intent intent = new Intent(this, this.getClass()); intent.putExtra(AbstractSerieArrowsActivity.SERIE_ARGUMENT_KEY, transitionSerie); startActivity(intent); } /** * Used to shown the container details when the user alread finished loading * all the possible series */ protected abstract Class<? extends AppCompatActivity> getContainerDetailsFragment(); /** * Used to show the previous or next serie. * * @return the fragment to be shown */ protected abstract AbstractSerieArrowsActivity getSerieDetailsFragment(); /** * Creates the new serie on the database * * @return */ protected abstract ISerie createNewSerie(); /** * Indicates if it can activate the next, and previous buttons * @return */ protected abstract boolean canActivateButtons(); /** * Indicates if no more series can be loaded * @return */ protected abstract boolean hasFinished(); @Override public boolean onLongClick(View v) { return false; } @Override public void onBackPressed() { if (this.canGoBack()) { super.onBackPressed(); } } public boolean canGoBack() { if (this.canActivateButtons()) { // if the serie is created with 6 arrows, then it doesnt has any issue // if the user go back return true; } if (this.canGoBack) { // if the user already confirmed that he can go back, then it should do it return true; } final AbstractSerieArrowsActivity self = this; new AlertDialog.Builder(this) .setTitle(R.string.common_confirmation_dialog_title) .setMessage(R.string.tournament_view_serie_creating_back) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { self.canGoBack = true; self.deleteSerie(); self.onBackPressed(); }}) .setNegativeButton(android.R.string.no, null) .show(); // ask the user if he is sure to go back or not return false; } }
ISSUE-163: Redraw text on undo last arrow
app/src/main/java/ar/com/tzulberti/archerytraining/activities/common/AbstractSerieArrowsActivity.java
ISSUE-163: Redraw text on undo last arrow