gt stringclasses 1
value | context stringlengths 2.05k 161k |
|---|---|
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang;
import com.intellij.codeHighlighting.TextEditorHighlightingPassRegistrar;
import com.intellij.codeInsight.daemon.ImplicitUsageProvider;
import com.intellij.codeInsight.highlighting.ReadWriteAccessDetector;
import com.intellij.codeInspection.unused.ImplicitPropertyUsageProvider;
import com.intellij.core.CoreApplicationEnvironment;
import com.intellij.core.CoreProjectEnvironment;
import com.intellij.ide.FileIconProvider;
import com.intellij.javaee.CoreExternalResourceManager;
import com.intellij.javaee.ExternalResourceManagerEx;
import com.intellij.lang.LanguageAnnotators;
import com.intellij.lang.LanguageParserDefinitions;
import com.intellij.lang.LanguageStructureViewBuilder;
import com.intellij.lang.findUsages.LanguageFindUsages;
import com.intellij.lang.folding.LanguageFolding;
import com.intellij.mock.MockProject;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.fileTypes.FileTypeRegistry;
import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.PomDeclarationSearcher;
import com.intellij.problems.WolfTheProblemSolver;
import com.intellij.psi.ClassTypePointerFactory;
import com.intellij.psi.PsiElementFinder;
import com.intellij.psi.ResolveScopeProvider;
import com.intellij.psi.codeStyle.ReferenceAdjuster;
import com.intellij.psi.impl.ExpressionConverter;
import com.intellij.psi.impl.LanguageConstantExpressionEvaluator;
import com.intellij.psi.impl.compiled.ClsCustomNavigationPolicy;
import com.intellij.psi.search.PsiShortNamesCache;
import com.intellij.psi.search.UseScopeEnlarger;
import com.intellij.psi.search.searches.*;
import com.intellij.psi.stubs.StubIndexExtension;
import com.intellij.util.QueryExecutor;
import com.intellij.util.indexing.FileBasedIndexExtension;
import org.jetbrains.plugins.groovy.*;
import org.jetbrains.plugins.groovy.annotator.GrAnnotatorImpl;
import org.jetbrains.plugins.groovy.annotator.GrKeywordAndDeclarationHighlightFactory;
import org.jetbrains.plugins.groovy.annotator.GrReferenceHighlighterFactory;
import org.jetbrains.plugins.groovy.annotator.GroovyFrameworkConfigNotification;
import org.jetbrains.plugins.groovy.annotator.checkers.*;
import org.jetbrains.plugins.groovy.builder.XmlMarkupBuilderNonCodeMemberContributor;
import org.jetbrains.plugins.groovy.codeInsight.GroovyClsCustomNavigationPolicy;
import org.jetbrains.plugins.groovy.codeInspection.GroovyQuickFixFactory;
import org.jetbrains.plugins.groovy.codeInspection.declaration.GrMethodMayBeStaticInspectionFilter;
import org.jetbrains.plugins.groovy.codeInspection.local.GroovyUnusedImportsPassFactory;
import org.jetbrains.plugins.groovy.codeStyle.GrReferenceAdjuster;
import org.jetbrains.plugins.groovy.configSlurper.ConfigSlurperMapContentProvider;
import org.jetbrains.plugins.groovy.configSlurper.GroovyMapValueTypeEnhancer;
import org.jetbrains.plugins.groovy.dgm.DGMImplicitPropertyUsageProvider;
import org.jetbrains.plugins.groovy.dgm.DGMMemberContributor;
import org.jetbrains.plugins.groovy.dgm.GroovyExtensionProvider;
import org.jetbrains.plugins.groovy.dsl.DslActivationStatus;
import org.jetbrains.plugins.groovy.dsl.GroovyDslAnnotator;
import org.jetbrains.plugins.groovy.dsl.GroovyDslFileIndex;
import org.jetbrains.plugins.groovy.dsl.dsltop.GdslMembersProvider;
import org.jetbrains.plugins.groovy.dsl.dsltop.GroovyDslDefaultMembers;
import org.jetbrains.plugins.groovy.dsl.psi.*;
import org.jetbrains.plugins.groovy.extensions.*;
import org.jetbrains.plugins.groovy.findUsages.*;
import org.jetbrains.plugins.groovy.geb.*;
import org.jetbrains.plugins.groovy.gpp.GppClosureParameterTypeProvider;
import org.jetbrains.plugins.groovy.gpp.GppExpectedTypesContributor;
import org.jetbrains.plugins.groovy.gpp.GppTypeConverter;
import org.jetbrains.plugins.groovy.lang.folding.GroovyFoldingBuilder;
import org.jetbrains.plugins.groovy.lang.parser.GroovyElementTypes;
import org.jetbrains.plugins.groovy.lang.parser.GroovyParserDefinition;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory;
import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.GroovyExpectedTypesContributor;
import org.jetbrains.plugins.groovy.lang.psi.impl.*;
import org.jetbrains.plugins.groovy.lang.psi.impl.javaView.GroovyClassFinder;
import org.jetbrains.plugins.groovy.lang.psi.impl.search.GrPrivateFieldScopeEnlarger;
import org.jetbrains.plugins.groovy.lang.psi.impl.smartPointers.GrClassReferenceTypePointerFactory;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.path.*;
import org.jetbrains.plugins.groovy.lang.psi.stubs.index.*;
import org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.*;
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyConstantExpressionEvaluator;
import org.jetbrains.plugins.groovy.lang.resolve.*;
import org.jetbrains.plugins.groovy.lang.resolve.ast.*;
import org.jetbrains.plugins.groovy.lang.resolve.ast.bindable.BindableTransformContributor;
import org.jetbrains.plugins.groovy.lang.resolve.ast.builder.strategy.DefaultBuilderStrategySupport;
import org.jetbrains.plugins.groovy.lang.resolve.ast.builder.strategy.ExternalBuilderStrategySupport;
import org.jetbrains.plugins.groovy.lang.resolve.ast.builder.strategy.InitializerBuilderStrategySupport;
import org.jetbrains.plugins.groovy.lang.resolve.ast.builder.strategy.SimpleBuilderStrategySupport;
import org.jetbrains.plugins.groovy.lang.resolve.noncode.GrCollectionTypeMembersProvider;
import org.jetbrains.plugins.groovy.lang.resolve.noncode.MixinMemberContributor;
import org.jetbrains.plugins.groovy.lang.stubs.GroovyShortNamesCache;
import org.jetbrains.plugins.groovy.spock.SpockMemberContributor;
import org.jetbrains.plugins.groovy.spock.SpockPomDeclarationSearcher;
import org.jetbrains.plugins.groovy.structure.GroovyStructureViewFactory;
import org.jetbrains.plugins.groovy.swingBuilder.SwingBuilderNamedArgumentProvider;
import org.jetbrains.plugins.groovy.swingBuilder.SwingBuilderNonCodeMemberContributor;
import org.jetbrains.plugins.groovy.transformations.AstTransformationSupport;
import org.jetbrains.plugins.groovy.transformations.impl.CategoryTransformationSupport;
import org.jetbrains.plugins.groovy.transformations.impl.DefaultTransformationSupport;
import org.jetbrains.plugins.groovy.transformations.impl.DelegateTransformationSupport;
import org.jetbrains.plugins.groovy.transformations.impl.TraitTransformationSupport;
/**
* Upsource
*/
@SuppressWarnings("UnusedDeclaration")
public class GroovyCoreEnvironment {
public static class ApplicationEnvironment {
public ApplicationEnvironment(CoreApplicationEnvironment appEnvironment) {
appEnvironment.registerFileType(GroovyFileType.GROOVY_FILE_TYPE, GroovyFileType.DEFAULT_EXTENSION);
appEnvironment.addExplicitExtension(SyntaxHighlighterFactory.LANGUAGE_FACTORY, GroovyLanguage.INSTANCE,
new GroovySyntaxHighlighterFactory());
appEnvironment.addExplicitExtension(LanguageParserDefinitions.INSTANCE, GroovyLanguage.INSTANCE, new GroovyParserDefinition());
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), GrMethodComparator.EP_NAME, GrMethodComparator.class);
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), NonCodeMembersContributor.EP_NAME, NonCodeMembersContributor.class);
appEnvironment.addExtension(NonCodeMembersContributor.EP_NAME, new GebBrowserMemberContributor());
appEnvironment.addExtension(NonCodeMembersContributor.EP_NAME, new GebJUnitTestMemberContributor());
appEnvironment.addExtension(NonCodeMembersContributor.EP_NAME, new GebModuleMemberContributor());
appEnvironment.addExtension(NonCodeMembersContributor.EP_NAME, new GebPageMemberContributor());
appEnvironment.addExtension(NonCodeMembersContributor.EP_NAME, new GebSpockTestMemberContributor());
appEnvironment.addExtension(NonCodeMembersContributor.EP_NAME, new GebTestNGTestMemberContributor());
appEnvironment.addExtension(NonCodeMembersContributor.EP_NAME, new GrCollectionTypeMembersProvider());
appEnvironment.addExtension(NonCodeMembersContributor.EP_NAME, new MixinMemberContributor());
appEnvironment.addExtension(NonCodeMembersContributor.EP_NAME, new SpockMemberContributor());
appEnvironment.addExtension(NonCodeMembersContributor.EP_NAME, new XmlMarkupBuilderNonCodeMemberContributor());
appEnvironment.addExtension(NonCodeMembersContributor.EP_NAME, new DGMMemberContributor());
appEnvironment.addExtension(NonCodeMembersContributor.EP_NAME, new SwingBuilderNonCodeMemberContributor());
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), DefaultImportContributor.EP_NAME,
DefaultImportContributor.class);
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), AstTransformationSupport.EP_NAME, AstTransformationSupport.class);
appEnvironment.addExtension(AstTransformationSupport.EP_NAME, new AutoExternalizeContributor());
appEnvironment.addExtension(AstTransformationSupport.EP_NAME, new AutoCloneContributor());
appEnvironment.addExtension(AstTransformationSupport.EP_NAME, new ConstructorAnnotationsProcessor());
appEnvironment.addExtension(AstTransformationSupport.EP_NAME, new InheritConstructorContributor());
appEnvironment.addExtension(AstTransformationSupport.EP_NAME, new DefaultBuilderStrategySupport());
appEnvironment.addExtension(AstTransformationSupport.EP_NAME, new SimpleBuilderStrategySupport());
appEnvironment.addExtension(AstTransformationSupport.EP_NAME, new ExternalBuilderStrategySupport());
appEnvironment.addExtension(AstTransformationSupport.EP_NAME, new InitializerBuilderStrategySupport());
appEnvironment.addExtension(AstTransformationSupport.EP_NAME, new BindableTransformContributor());
appEnvironment.addExtension(AstTransformationSupport.EP_NAME, new LoggingContributor());
appEnvironment.addExtension(AstTransformationSupport.EP_NAME, new CategoryTransformationSupport());
appEnvironment.addExtension(AstTransformationSupport.EP_NAME, new DelegateTransformationSupport());
appEnvironment.addExtension(AstTransformationSupport.EP_NAME, new DefaultTransformationSupport());
appEnvironment.addExtension(AstTransformationSupport.EP_NAME, new TraitTransformationSupport());
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), ClosureMissingMethodContributor.EP_NAME,
ClosureMissingMethodContributor.class);
appEnvironment.addExtension(ClosureMissingMethodContributor.EP_NAME, new PluginXmlClosureMemberContributor());
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), GrVariableEnhancer.EP_NAME, GrVariableEnhancer.class);
appEnvironment.addExtension(GrVariableEnhancer.EP_NAME, new ClosureAsAnonymousParameterEnhancer());
appEnvironment.addExtension(GrVariableEnhancer.EP_NAME, new ClosureParameterEnhancer());
appEnvironment.addExtension(GrVariableEnhancer.EP_NAME, new ClosureParamsEnhancer());
appEnvironment.addExtension(GrVariableEnhancer.EP_NAME, new GppClosureParameterTypeProvider());
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), GrReferenceTypeEnhancer.EP_NAME,
GrReferenceTypeEnhancer.class);
appEnvironment.addExtension(GrReferenceTypeEnhancer.EP_NAME, new GroovyMapValueTypeEnhancer());
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), GrTypeConverter.EP_NAME, GrTypeConverter.class);
appEnvironment.addExtension(GrTypeConverter.EP_NAME, new GrBooleanTypeConverter());
appEnvironment.addExtension(GrTypeConverter.EP_NAME, new GrGenericTypeConverter());
appEnvironment.addExtension(GrTypeConverter.EP_NAME, new GrClassConverter());
appEnvironment.addExtension(GrTypeConverter.EP_NAME, new GrNullVoidConverter());
appEnvironment.addExtension(GrTypeConverter.EP_NAME, new GrCharConverter());
appEnvironment.addExtension(GrTypeConverter.EP_NAME, new GrNumberConverter());
appEnvironment.addExtension(GrTypeConverter.EP_NAME, new GrStringConverter());
appEnvironment.addExtension(GrTypeConverter.EP_NAME, new GrEnumConverter());
appEnvironment.addExtension(GrTypeConverter.EP_NAME, new GrContainerTypeConverter());
appEnvironment.addExtension(GrTypeConverter.EP_NAME, new ClosureToSamConverter());
appEnvironment.addExtension(GrTypeConverter.EP_NAME, new GrContainerConverter());
appEnvironment.addExtension(GrTypeConverter.EP_NAME, new GppTypeConverter());
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), GroovyExpectedTypesContributor.EP_NAME,
GroovyExpectedTypesContributor.class);
appEnvironment.addExtension(GroovyExpectedTypesContributor.EP_NAME, new GppExpectedTypesContributor());
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), GroovyScriptTypeDetector.EP_NAME,
GroovyScriptTypeDetector.class);
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), GroovyNamedArgumentProvider.EP_NAME, GroovyNamedArgumentProvider.class);
appEnvironment.addExtension(GroovyNamedArgumentProvider.EP_NAME, new GroovyConstructorNamedArgumentProvider());
appEnvironment.addExtension(GroovyNamedArgumentProvider.EP_NAME, new GroovyMethodReturnNamedArgumentProvider());
appEnvironment.addExtension(GroovyNamedArgumentProvider.EP_NAME, new GroovySourceCodeNamedArgumentProvider());
appEnvironment.addExtension(GroovyNamedArgumentProvider.EP_NAME, new SwingBuilderNamedArgumentProvider());
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), GroovyMapContentProvider.EP_NAME,
GroovyMapContentProvider.class);
appEnvironment.addExtension(GroovyMapContentProvider.EP_NAME, new ConfigSlurperMapContentProvider());
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), GroovyUnresolvedHighlightFilter.EP_NAME,
GroovyUnresolvedHighlightFilter.class);
appEnvironment.addExtension(GroovyUnresolvedHighlightFilter.EP_NAME, new GroovyUnresolvedReferenceFilterByFile());
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), GroovyUnresolvedHighlightFileFilter.EP_NAME,
GroovyUnresolvedHighlightFileFilter.class);
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), GrCallExpressionTypeCalculator.EP_NAME, GrCallExpressionTypeCalculator.class);
appEnvironment.addExtension(GrCallExpressionTypeCalculator.EP_NAME, new DefaultCallExpressionTypeCalculator());
appEnvironment.addExtension(GrCallExpressionTypeCalculator.EP_NAME, new GrDescriptorReturnTypeCalculator());
appEnvironment.addExtension(GrCallExpressionTypeCalculator.EP_NAME, new GrDGMTypeCalculator());
appEnvironment.addExtension(GrCallExpressionTypeCalculator.EP_NAME, new GrWithTraitTypeCalculator());
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), GrExpressionTypeCalculator.EP_NAME, GrExpressionTypeCalculator.class);
appEnvironment.addExtension(GrExpressionTypeCalculator.EP_NAME, new GrClosureDelegateTypeCalculator());
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), GroovyClassDescriptor.EP_NAME,
GroovyClassDescriptor.class);
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), GroovyMethodDescriptorExtension.EP_NAME,
GroovyMethodDescriptorExtension.class);
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), PsiEnhancerCategory.EP_NAME, PsiEnhancerCategory.class);
appEnvironment.addExtension(PsiEnhancerCategory.EP_NAME, new GrExpressionCategory());
appEnvironment.addExtension(PsiEnhancerCategory.EP_NAME, new PsiClassCategory());
appEnvironment.addExtension(PsiEnhancerCategory.EP_NAME, new PsiElementCategory());
appEnvironment.addExtension(PsiEnhancerCategory.EP_NAME, new PsiExpressionCategory());
appEnvironment.addExtension(PsiEnhancerCategory.EP_NAME, new PsiMethodCategory());
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), GdslMembersProvider.EP_NAME, GdslMembersProvider.class);
appEnvironment.addExtension(GdslMembersProvider.EP_NAME, new GdkMethodDslProvider());
appEnvironment.addExtension(GdslMembersProvider.EP_NAME, new GroovyDslDefaultMembers());
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), GroovyFrameworkConfigNotification.EP_NAME,
GroovyFrameworkConfigNotification.class);
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), GrMethodMayBeStaticInspectionFilter.EP_NAME, GrMethodMayBeStaticInspectionFilter.class);
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), CustomAnnotationChecker.EP_NAME, CustomAnnotationChecker.class);
appEnvironment.addExtension(CustomAnnotationChecker.EP_NAME, new AnnotationCollectorChecker());
appEnvironment.addExtension(CustomAnnotationChecker.EP_NAME, new BaseScriptAnnotationChecker());
appEnvironment.addExtension(CustomAnnotationChecker.EP_NAME, new DelegatesToAnnotationChecker());
appEnvironment.addExtension(CustomAnnotationChecker.EP_NAME, new FieldAnnotationChecker());
appEnvironment.addExtension(CustomAnnotationChecker.EP_NAME, new GrabAnnotationChecker());
appEnvironment.addExtension(CustomAnnotationChecker.EP_NAME, new GrAliasAnnotationChecker());
appEnvironment.addExtension(CustomAnnotationChecker.EP_NAME, new NewifyAnnotationChecker());
appEnvironment.addExtension(CustomAnnotationChecker.EP_NAME, new TypeCheckedAnnotationChecker());
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), ImplicitPropertyUsageProvider.EP_NAME,
ImplicitPropertyUsageProvider.class);
appEnvironment.addExtension(ImplicitPropertyUsageProvider.EP_NAME, new DGMImplicitPropertyUsageProvider());
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), ImplicitUsageProvider.EP_NAME,
ImplicitUsageProvider.class);
appEnvironment.addExtension(ImplicitUsageProvider.EP_NAME, new GrImplicitUsageProvider());
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), FileTypeRegistry.FileTypeDetector.EP_NAME,
FileTypeRegistry.FileTypeDetector.class);
appEnvironment.addExtension(FileTypeRegistry.FileTypeDetector.EP_NAME, new GroovyHashBangFileTypeDetector());
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), ClsCustomNavigationPolicy.EP_NAME,
ClsCustomNavigationPolicy.class);
appEnvironment.addExtension(ClsCustomNavigationPolicy.EP_NAME, new GroovyClsCustomNavigationPolicy());
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), PomDeclarationSearcher.EP_NAME,
PomDeclarationSearcher.class);
appEnvironment.addExtension(PomDeclarationSearcher.EP_NAME, new GebContentDeclarationSearcher());
appEnvironment.addExtension(PomDeclarationSearcher.EP_NAME, new SpockPomDeclarationSearcher());
appEnvironment.addExplicitExtension(LanguageConstantExpressionEvaluator.INSTANCE, GroovyLanguage.INSTANCE,
new GroovyConstantExpressionEvaluator());
appEnvironment.addExplicitExtension(ExpressionConverter.EP, GroovyLanguage.INSTANCE, new GroovyExpressionConverter());
appEnvironment.addExplicitExtension(LanguageAnnotators.INSTANCE, GroovyLanguage.INSTANCE, new GrAnnotatorImpl());
appEnvironment.addExplicitExtension(LanguageAnnotators.INSTANCE, GroovyLanguage.INSTANCE, new GroovyDslAnnotator());
appEnvironment.addExplicitExtension(LanguageStructureViewBuilder.INSTANCE, GroovyLanguage.INSTANCE, new GroovyStructureViewFactory());
appEnvironment.addExplicitExtension(LanguageFolding.INSTANCE, GroovyLanguage.INSTANCE, new GroovyFoldingBuilder());
appEnvironment.addExplicitExtension(LanguageFindUsages.INSTANCE, GroovyLanguage.INSTANCE, new GroovyFindUsagesProvider());
appEnvironment.addExplicitExtension(ReferenceAdjuster.Extension.INSTANCE, GroovyLanguage.INSTANCE, new GrReferenceAdjuster());
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), UseScopeEnlarger.EP_NAME, UseScopeEnlarger.class);
appEnvironment.addExtension(UseScopeEnlarger.EP_NAME, new GrPrivateFieldScopeEnlarger());
DirectClassInheritorsSearch.INSTANCE.registerExecutor(new GroovyDirectInheritorsSearcher());
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), MethodReferencesSearch.EP_NAME, QueryExecutor.class);
appEnvironment.addExtension(MethodReferencesSearch.EP_NAME, new AccessorMethodReferencesSearcher());
appEnvironment.addExtension(MethodReferencesSearch.EP_NAME, new MethodLateBoundReferencesSearcher());
appEnvironment.addExtension(MethodReferencesSearch.EP_NAME, new GroovyConstructorUsagesSearcher());
appEnvironment.addExtension(MethodReferencesSearch.EP_NAME, new GroovyReflectedMethodReferenceSearcher());
appEnvironment.addExtension(MethodReferencesSearch.EP_NAME, new GrLiteralMethodSearcher());
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), AnnotatedElementsSearch.EP_NAME, QueryExecutor.class);
appEnvironment.addExtension(AnnotatedElementsSearch.EP_NAME, new AnnotatedMembersSearcher());
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), SuperMethodsSearch.EP_NAME, QueryExecutor.class);
appEnvironment.addExtension(SuperMethodsSearch.EP_NAME, new GDKSuperMethodSearcher());
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), DefinitionsScopedSearch.EP_NAME, QueryExecutor.class);
appEnvironment.addExtension(DefinitionsScopedSearch.EP_NAME, new GroovyImplementationSearch());
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), StubIndexExtension.EP_NAME, StubIndexExtension.class);
appEnvironment.addExtension(StubIndexExtension.EP_NAME, new GrAnnotationMethodNameIndex());
appEnvironment.addExtension(StubIndexExtension.EP_NAME, new GrAnnotatedMemberIndex());
appEnvironment.addExtension(StubIndexExtension.EP_NAME, new GrAnonymousClassIndex());
appEnvironment.addExtension(StubIndexExtension.EP_NAME, new GrDirectInheritorsIndex());
appEnvironment.addExtension(StubIndexExtension.EP_NAME, new GrFieldNameIndex());
appEnvironment.addExtension(StubIndexExtension.EP_NAME, new GrFullClassNameIndex());
appEnvironment.addExtension(StubIndexExtension.EP_NAME, new GrFullScriptNameIndex());
appEnvironment.addExtension(StubIndexExtension.EP_NAME, new GrMethodNameIndex());
appEnvironment.addExtension(StubIndexExtension.EP_NAME, new GrScriptClassNameIndex());
appEnvironment.addExtension(StubIndexExtension.EP_NAME, new GrScriptClassNameIndex());
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), FileBasedIndexExtension.EXTENSION_POINT_NAME,
FileBasedIndexExtension.class);
appEnvironment.addExtension(FileBasedIndexExtension.EXTENSION_POINT_NAME, new GroovyDslFileIndex());
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), ReferencesSearch.EP_NAME, QueryExecutor.class);
appEnvironment.addExtension(ReferencesSearch.EP_NAME, new ConstructorReferencesSearcher());
appEnvironment.addExtension(ReferencesSearch.EP_NAME, new GrAliasedImportedElementSearcher());
appEnvironment.addExtension(ReferencesSearch.EP_NAME, new AccessorReferencesSearcher());
appEnvironment.addExtension(ReferencesSearch.EP_NAME, new GroovyTraitFieldSearcher());
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), FileIconProvider.EP_NAME, FileIconProvider.class);
appEnvironment.addExtension(FileIconProvider.EP_NAME, new GroovyFileIconProvider());
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), ResolveScopeProvider.EP_NAME, ResolveScopeProvider.class);
appEnvironment.addExtension(ResolveScopeProvider.EP_NAME, new GroovyResolveScopeProvider());
Class<Condition<VirtualFile>> conditionClass = (Class)Condition.class;
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), WolfTheProblemSolver.FILTER_EP_NAME, conditionClass);
appEnvironment.addExtension(WolfTheProblemSolver.FILTER_EP_NAME, new GroovyProblemFileHighlightFilter());
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), ClassTypePointerFactory.EP_NAME, ClassTypePointerFactory.class);
appEnvironment.addExtension(ClassTypePointerFactory.EP_NAME, new GrClassReferenceTypePointerFactory());
appEnvironment.registerApplicationService(GroovyQuickFixFactory.class, new EmptyGroovyQuickFixFactory());
appEnvironment.registerApplicationComponent(DslActivationStatus.class, new DslActivationStatus());
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), ReadWriteAccessDetector.EP_NAME, ReadWriteAccessDetector.class);
appEnvironment.addExtension(ReadWriteAccessDetector.EP_NAME, new GroovyReadWriteAccessDetector());
if (GroovyElementTypes.ADDITIVE_EXPRESSION == null) throw new IllegalStateException(); // initialize tokens
}
protected ExternalResourceManagerEx createExternalResourceManager() {
return new CoreExternalResourceManager();
}
}
public static class ProjectEnvironment {
public ProjectEnvironment(CoreProjectEnvironment projectEnvironment) {
MockProject project = projectEnvironment.getProject();
project.registerService(GroovyPsiElementFactory.class, GroovyPsiElementFactoryImpl.class);
project.registerService(GroovyPsiManager.class, GroovyPsiManager.class);
project.registerService(GroovyCodeStyleManager.class, CoreGroovyCodeStyleManager.class);
project.registerService(GroovyCodeStyleSettingsFacade.class, CoreGroovyCodeStyleSettingsFacade.class);
project.registerService(GroovyExtensionProvider.class, GroovyExtensionProvider.class);
projectEnvironment.addProjectExtension(PsiShortNamesCache.EP_NAME, new GroovyShortNamesCache(project));
projectEnvironment.addProjectExtension(PsiElementFinder.EP_NAME, new GroovyClassFinder(project));
TextEditorHighlightingPassRegistrar registrar = TextEditorHighlightingPassRegistrar.getInstance(project);
projectEnvironment.registerProjectComponent(GroovyUnusedImportsPassFactory.class, new GroovyUnusedImportsPassFactory(project, registrar));
projectEnvironment.registerProjectComponent(GrKeywordAndDeclarationHighlightFactory.class, new GrKeywordAndDeclarationHighlightFactory(project, registrar));
projectEnvironment.registerProjectComponent(GrReferenceHighlighterFactory.class, new GrReferenceHighlighterFactory(project, registrar));
}
}
}
| |
package orst.stratagusai.stratsim.planner;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.math.linear.Array2DRowRealMatrix;
import org.apache.commons.math.linear.RealMatrix;
import org.apache.commons.math.optimization.RealPointValuePair;
import org.apache.commons.math.stat.StatUtils;
import org.apache.log4j.Appender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
import orst.stratagusai.stratplan.StrategicPlan;
import orst.stratagusai.stratplan.model.StrategicState;
import orst.stratagusai.stratplan.mgr.StrategyController;
import orst.stratagusai.stratplan.model.GameState;
import orst.stratagusai.stratplan.persist.StrategicPlanWriter;
import orst.stratagusai.stratsim.analysis.GameMatrixSolver;
import orst.stratagusai.stratsim.analysis.GameSolution;
import orst.stratagusai.stratsim.analysis.GameStateEvaluator;
import orst.stratagusai.stratsim.io.UnitsGameStateWriter;
import orst.stratagusai.stratsim.io.YamlTable;
import orst.stratagusai.stratsim.model.SimController;
import orst.stratagusai.stratsim.model.SimState;
import orst.stratagusai.util.Randomizer;
/**
* Select plans by Nash equilibrium.
*
* @author Brian
*/
public class SwitchingPlanner extends BasePlanner {
private static final Logger log = Logger.getLogger(SwitchingPlanner.class);
private static Logger simlog = Logger.getLogger("game_sim_event");
// how to choose strategy from game matrix.
public static final String CHOOSE_NASH = "Nash";
public static final String CHOOSE_MAXIMIN = "maximin";
public static final String CHOOSE_MONOTONE = "monotone";
public static final String CHOOSE_MINIMAX = "minimax";
public static final String CHOOSE_MAX = "max";
protected int playerId = -1;
/** name of strategy set to use. */
protected String strategy_set;
// strategy evaluation about .25 sec.
// 5 strategies gives 25 matrix values. Evaluation ~ 6 seconds.
//
protected StrategyTemplate[] strategies;
private int nStrats;
protected boolean simReplan = true;
/** the game matrix */
protected double[][] values;
/** planners to use for each player. It's necessary that GoalDrivenPlanners
* not hold state between planning calls.
*/
protected GoalDrivenPlanner [] planners;
protected GameGoal goal = new GameGoal();
/** player name for logging statistics */
protected String playerName;
/** opponent planner or strategy name for statistics */
protected String opponentName;
/** choose strategy by Nash equilibrium, maximin, or max. */
protected String choiceMethod = CHOOSE_NASH;
/** monotone value is the maximum of the current maximin + accumlated reward
* and the previous monotone value. */
protected double monotone_v = Double.NEGATIVE_INFINITY;
/** index of previously choosen strategy */
protected int prevStrategy = -1;
protected GameStateEvaluator evaluator = new GameStateEvaluator();
protected int[] log_pair;
/** name of logfile if planner is logging matrix values. */
protected String logMatrix;
public SwitchingPlanner() {
}
/** return the named strategy set. */
public static StrategyTemplate[] getStrategies(String name) {
if ("atk-dfnd".equals(name)) {
// reduced set of strategies that do not secure chokepoints.
return new StrategyTemplate[] {
StrategyTemplate.getDefendAttack(5, false),
StrategyTemplate.getDefendAttack(5, true),
StrategyTemplate.getDefendAttack(7, false),
StrategyTemplate.getDefendAttack(7, true),
StrategyTemplate.getAttackDefend(5, false),
StrategyTemplate.getAttackDefend(5, true),
StrategyTemplate.getAttackDefend(7, false),
StrategyTemplate.getAttackDefend(7, true),
StrategyTemplate.getOffensiveOnly(5, true),
StrategyTemplate.getOffensiveOnly(7, true),
};
} else if ("2011-11-01".equals(name)) {
// stategy set used for results on 2011-11-01.
return new StrategyTemplate[] {
StrategyTemplate.getDefensive(7, false),
StrategyTemplate.getBalanced(7, false),
StrategyTemplate.getBalanced(7, true),
StrategyTemplate.getBalanced(9, false),
StrategyTemplate.getBalanced(9, true),
StrategyTemplate.getRush(7, false),
StrategyTemplate.getRush(7, true),
StrategyTemplate.getRush(9, false),
StrategyTemplate.getOffensiveOnly(5, true),
StrategyTemplate.getOffensiveOnly(7, true),
StrategyTemplate.getSecureChokepoint(6)
};
} else if ("2012-02-05".equals(name)) {
// stategy 2011-11-01 with defensive_7 removed. defensive_7 wins
// in simulation, but loses when played in the Stratagus Engine,
// so it may be favored too much when it is in the strategy set.
return new StrategyTemplate[] {
StrategyTemplate.getBalanced(7, false),
StrategyTemplate.getBalanced(7, true),
StrategyTemplate.getBalanced(9, false),
StrategyTemplate.getBalanced(9, true),
StrategyTemplate.getRush(7, false),
StrategyTemplate.getRush(7, true),
StrategyTemplate.getRush(9, false),
StrategyTemplate.getOffensiveOnly(5, true),
StrategyTemplate.getOffensiveOnly(7, true),
StrategyTemplate.getSecureChokepoint(6)
};
} else if ("synth".equals(name)) {
// strategy set created by StrategyTrainer on 2012-01-27
// doesn't perform as well as strategy set 2011-11-01 against
// builtin AI script.
//
return new StrategyTemplate[] {
StrategyTemplate.getStrategy("synth0",1,6,0,1,true,0.70F,0.00F,0.90F,0.00F),
StrategyTemplate.getStrategy("synth1",6,5,5,0,false,0.50F,0.00F,0.80F,0.00F),
StrategyTemplate.getStrategy("synth2",4,6,5,0,false,0.00F,0.00F,-0.10F,0.00F),
StrategyTemplate.getStrategy("synth3",2,7,4,4,false,0.80F,0.00F,0.80F,0.00F),
StrategyTemplate.getStrategy("synth4",3,6,0,1,true,0.10F,0.00F,-0.20F,0.00F),
StrategyTemplate.getStrategy("synth5",9,9,0,2,true,0.30F,0.00F,-1.00F,0.00F),
StrategyTemplate.getStrategy("synth6",7,4,0,2,true,0.00F,0.00F,-0.90F,0.00F),
StrategyTemplate.getStrategy("synth7",6,8,0,1,false,0.80F,0.00F,-0.70F,0.00F),
StrategyTemplate.getStrategy("synth8",0,8,0,5,true,0.90F,0.00F,-0.20F,0.00F),
StrategyTemplate.getStrategy("synth9",0,6,0,5,true,0.00F,0.00F,0.00F,0.00F),
};
} else {
throw new RuntimeException("unknown strategy set '" + name + "'");
}
}
@Override
public void configure(Map params) {
// configure strategies
strategy_set = (String) params.get("strategy_set");
strategies = getStrategies(strategy_set);
nStrats = strategies.length;
values = new double[nStrats][nStrats];
planners = new GoalDrivenPlanner[nStrats];
for (int i = 0; i < strategies.length; i++) {
planners[i] = new GoalDrivenPlanner();
planners[i].setTemplate(strategies[i]);
}
// configure logging info.
playerName = (String) params.get("player");
opponentName = (String) params.get("opponent");
logMatrix = (String) params.get("logMatrix");
// configure switching method
Boolean b = (Boolean) params.get("simReplan");
assert b != null : "simReplan must be set in configuration.";
simReplan = b.booleanValue();
log.debug("simReplan=" + simReplan);
String c = (String) params.get("choice_method");
if (!CHOOSE_NASH.equals(c) &&
!CHOOSE_MAXIMIN.equals(c) &&
!CHOOSE_MONOTONE.equals(c) &&
!CHOOSE_MINIMAX.equals(c) &&
!CHOOSE_MAX.equals(c)) {
throw new RuntimeException("Unknown strategy choice method " + c);
}
choiceMethod = c;
log.debug("choose stratagy by " + choiceMethod);
}
public Map getConfiguration() {
Map params = new LinkedHashMap();
params.put("strategy_set", strategy_set);
params.put("player", playerName);
params.put("opponent", opponentName);
params.put("simReplan", simReplan);
params.put("choice_method", choiceMethod);
return params;
}
public void setSimulationReplanning(boolean replan) {
simReplan = replan;
}
/** get the configured strategy set. */
public StrategyTemplate[] getStrategies() {
return strategies;
}
/** get game matrix values */
public double[][] getValues() {
return values;
}
public String getChoiceMethod() {
return choiceMethod;
}
/**
* log the simulated game events for strategy pair i,j.
*/
public void setLogEventsPair(int[] pair) {
log_pair = pair;
}
public StrategicPlan makePlan(int playerId, StrategicState state) {
// initialize monotone variables.
this.monotone_v = Double.NEGATIVE_INFINITY;
this.prevStrategy = -1;
return simSelect(playerId, null, state);
}
public StrategicPlan replan(int playerId, StrategicPlan plan, StrategicState state) {
return simSelect(playerId, plan, state);
}
protected StrategicPlan simSelect(int playerId, StrategicPlan prevPlan, StrategicState state) {
assert playerId == 0 || playerId == 1;
this.playerId = playerId;
// simulate each pair of plans generated by planners.
long start = System.currentTimeMillis();
for (int i = 0; i < nStrats; i++) {
for (int j = 0; j < nStrats; j++) {
simulate(i, j, prevPlan, state);
}
}
// select strategy according to equilibrium distribution.
StrategyTemplate strategy = selectStrategy(state.getGameState());
System.out.println(String.format("Player %d selects %s at cycle %d.",playerId, strategy.getName(), state.getCycle()));
System.out.println(String.format("Game matrix evaluation in %.2f sec.",
(System.currentTimeMillis() - start)/1000.0));
if (logMatrix != null) {
logMatrix(state.getGameState());
}
GoalDrivenPlanner planner = new GoalDrivenPlanner();
planner.setTemplate(strategy);
if (prevPlan == null) {
return planner.makePlan(playerId, state);
} else {
return planner.replan(playerId, prevPlan, state);
}
}
/**
* select strategy using the game matrix
*
* @return
*/
protected StrategyTemplate selectStrategy(GameState game) {
int cycle = game.getCycle();
if (CHOOSE_NASH.equals(choiceMethod)) {
return chooseNash(cycle);
} else if (CHOOSE_MAXIMIN.equals(choiceMethod)) {
return chooseMaximin(cycle);
} else if (CHOOSE_MONOTONE.equals(choiceMethod)) {
return chooseMonotone(game);
} else if (CHOOSE_MINIMAX.equals(choiceMethod)) {
return chooseMinimax(cycle);
} else if (CHOOSE_MAX.equals(choiceMethod)) {
return chooseMax(cycle);
}
throw new RuntimeException("Unknown strategy choice method " + choiceMethod);
}
protected StrategyTemplate chooseNash(int cycle) {
RealMatrix A = new Array2DRowRealMatrix(values);
// solve for row player as maximizer.
GameSolution soln = GameMatrixSolver.solveGame(A);
RealPointValuePair solution = soln.getRowSolution();
double [] x = solution.getPoint();
double r = Randomizer.nextFloat();
double cumulative = 0;
int i = 0;
for (; i < x.length-1; i++) {
cumulative += x[i];
if (cumulative >= r) {
break;
}
}
StrategyTemplate selected = planners[i].getTemplate();
logPredictionStats(selected, solution.getValue());
return selected;
}
/**
* Choose strategy that maximizes the player's minimum payoff.
* This is the strategy the player chooses assuming that
* once the player has choosen a strategy, the opponent can
* choose a strategy to minimize the result.
* For player i, opponent j
*
* argmax min V(i,j) (x)
* i j
*
* See "Essentials of Game Theory", Leyton-Brown, Shoham, pg. 15.
*/
protected StrategyTemplate chooseMaximin(int cycle) {
// find the minumum of each row (the minimum across the column players
// choices), then choose a maximum of these minimums.
double[] mins = new double[values.length];
for (int row = 0; row < values.length; row++) {
mins[row] = StatUtils.min(values[row]);
}
// find a maxmin. There may be several rows with the same maximin
// value, so we select one randomly.
List<Integer> indexes = new ArrayList<Integer>();
double maximin = StatUtils.max(mins);
for (int row = 0; row < values.length; row++) {
// if the min of this row equals the maximin,
// we can choose the strategy of this row.
if (StatUtils.min(values[row]) == maximin) {
indexes.add(row);
}
}
int i = (Integer) Randomizer.select(indexes);
StrategyTemplate selected = planners[i].getTemplate();
logPredictionStats(selected, maximin);
return selected;
}
/**
* Choose strategy that maximizes the player's minimum payoff,
* but don't switch unless maximin value exceeds previous maximin value.
*
* argmax min V(i,j) (x)
* i j
*/
protected StrategyTemplate chooseMonotone(GameState game) {
int cycle = game.getCycle();
int reward = game.getScores()[playerId]; // reward so far.
// find the minumum of each row (the minimum across the column players
// choices), then choose a maximum of these minimums.
double[] mins = new double[values.length];
for (int row = 0; row < values.length; row++) {
mins[row] = StatUtils.min(values[row]);
}
// find a maxmin. There may be several rows with the same maximin
// value, so we select one randomly.
List<Integer> indexes = new ArrayList<Integer>();
double maximin = StatUtils.max(mins);
for (int row = 0; row < values.length; row++) {
// if the min of this row equals the maximin,
// we can choose the strategy of this row.
if (StatUtils.min(values[row]) == maximin) {
indexes.add(row);
}
}
int i = (Integer) Randomizer.select(indexes);
StrategyTemplate selected;
if (maximin + reward > monotone_v) {
selected = planners[i].getTemplate();
prevStrategy = i;
System.out.println("monotone switches to strategy " + selected.getName() + " at " + cycle + ". maximin: " + maximin + ", previous maximin:" + monotone_v);
monotone_v = maximin + reward;
} else {
selected = planners[prevStrategy].getTemplate();
System.out.println("monotone stays with strategy " + selected.getName() + " at " + cycle + ". maximin: " + maximin);
}
logPredictionStats(selected, maximin);
return selected;
}
/**
* Choose a strategy that minimizes the opponents's maximum payoff.
* This assumes opponent chooses first and player can maximize its own score
* given opponent's choice.
*
* min max -V(i,j) (x)
* i j
*
* opponent first commits to strategy j, then player chooses strategy i to
* minimize opponents maximum.
*
* See "Essentials of Game Theory", Leyton-Brown, Shoham, pg. 15.
*/
protected StrategyTemplate chooseMinimax(int cycle) {
// find the maximum of each column, then choose the
// min of these maxima.
double[] maxs = new double[values[0].length];
for (int col = 0; col < values[0].length; col++) {
double max = Double.NEGATIVE_INFINITY;
for (int row = 0; row < values.length; row++) {
if (values[row][col] > max) {
max = values[row][col];
}
}
maxs[col] = max;
}
int i = -1;
double min = Double.POSITIVE_INFINITY;
for (int col = 0; col < values.length; col++) {
if (maxs[col] < min) {
i = col;
min = maxs[col];
}
}
StrategyTemplate selected = planners[i].getTemplate();
logPredictionStats(selected, min);
return selected;
}
protected StrategyTemplate chooseMax(int cycle) {
double max = Double.NEGATIVE_INFINITY;
int i = -1;
for (int row = 0; row < values.length; row++) {
for (int col = 0; col < values[row].length; col++) {
if (values[row][col] > max) {
i = row;
max = values[row][col];
}
}
}
StrategyTemplate selected = planners[i].getTemplate();
logPredictionStats(selected, max);
return selected;
}
public void simulate(int i, int j, StrategicPlan prevPlan, StrategicState s) {
int opponentId = playerId == 0 ? 1 : 0;
StrategicPlan allyPlan;
StrategicPlan opponentPlan;
SimState simstate = new SimState(s); // copy groups from StrategicState
if (prevPlan == null) {
allyPlan = planners[i].makePlan(playerId, simstate);
opponentPlan = planners[j].makePlan(opponentId, simstate);
if (logPair(i,j)) {
logSimState(i,j,simstate);
}
} else {
allyPlan = planners[i].replan(playerId, prevPlan, simstate);
// currently the previous plan is not used in the
// GoalDrivenPlanner.
opponentPlan = planners[j].replan(opponentId, null, simstate);
}
if (logPair(i,j)) {
logPlan(playerId,allyPlan);
logPlan(opponentId,opponentPlan);
}
allyPlan.intialize();
opponentPlan.intialize();
SimController sim = new SimController(simstate);
sim.setPlan(playerId, allyPlan);
sim.setPlan(opponentId, opponentPlan);
logEvents(i,j); // start simulation game event log.
sim.simulate(StrategyController.REPLAN_CYCLES);
simlog.removeAllAppenders(); // end simulation game event log.
if (logPair(i,j)) {
logSimState(i,j,sim.getState());
logScores(sim.getState());
}
while (!sim.isTerminal()) {
if (simReplan) {
sim.update(); // prepare for planning: remove dead units, remove commands, update groups.
allyPlan = planners[i].replan(playerId, allyPlan, simstate);
opponentPlan = planners[j].replan(opponentId, opponentPlan, simstate);
sim.setPlan(playerId, allyPlan);
sim.setPlan(opponentId, opponentPlan);
}
sim.simulate(StrategyController.REPLAN_CYCLES);
}
values[i][j] = evaluator.evaluate(simstate.getGameState(), playerId);
}
private void logPredictionStats(StrategyTemplate selected, double gameValue) {
if (stats == null) {
return;
}
stats.setValue("player ID", playerId);
stats.setValue("player", choiceMethod);
stats.setValue("strategy", selected.getName());
stats.setValue("simReplan", simReplan ? 1 : 0);
stats.setValue("opponent", opponentName);
double v = gameValue;
stats.setValue("predicted", v > 0 ? "0" : "1"); // assuming row player is player 0.
stats.setValue("predicted diff", String.format("%.2f", v));
}
/**
* log available strategies for documentation.
* @throws IOException
*/
private static void logStrategies(String name, String dir) throws IOException {
StrategyTemplate[] strategies = SwitchingPlanner.getStrategies(name);
String[] rowhdr = new String[strategies.length];
String[] colhdr = {"Strategy","base","enemy","chkpt.","base","enemy", "chkpt.","Units"};
String[][] table = new String[strategies.length][colhdr.length];
for (int i = 0; i < strategies.length; i++) {
StrategyTemplate s = strategies[i];
rowhdr[i] = i + ". ";
table[i][0] = s.getName();
table[i][1] = String.valueOf(s.getPriority(GoalType.SECURE_ALLIED_BASE));
table[i][2] = String.valueOf(s.getPriority(GoalType.SECURE_ENEMY_BASE));
table[i][3] = String.valueOf(s.getPriority(GoalType.SECURE_CHOKEPOINT));
int allyForce = s.getForce(GoalType.SECURE_ALLIED_BASE);
int enemyBaseForce = s.getForce(GoalType.SECURE_ENEMY_BASE);
int chokepointForce = s.getForce(GoalType.SECURE_CHOKEPOINT);
table[i][4] = String.valueOf(allyForce);
table[i][5] = String.valueOf(enemyBaseForce);
table[i][6] = String.valueOf(chokepointForce);
table[i][7] = String.valueOf(allyForce+enemyBaseForce+chokepointForce);
}
String caption = "Strategy Set "+ name + ".";
String label = "strategy_defs_" + name;
String filepath = "sw_strategies_" + name + ".yaml";
String comment = "table written by " + SwitchingPlanner.class.getSimpleName();
System.out.println("write strategy table to " + filepath);
YamlTable.write_YAML_table(table, colhdr, rowhdr, label, caption, filepath, comment);
}
private void logSimState(int i, int j, StrategicState s) {
final String filename = "game_state_sim.txt";
try {
// open for append.
BufferedWriter out = new BufferedWriter(new FileWriter(filename, true));
UnitsGameStateWriter wr = new UnitsGameStateWriter();
// wr.setObjectWriter(UnitGroupSim.class, new UnitGroupSimWriter());
out.write(String.format("# simulated game state for strategy pair %d, %d.%s", i, j, NL));
wr.write(out, s.getGameState());
out.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void logPlan(int playerId, StrategicPlan plan) {
final String filename = "plans" + playerId + "_sim.txt";
try {
// open for append.
BufferedWriter out = new BufferedWriter(new FileWriter(filename, true));
StrategicPlanWriter.write(plan, out);
out.close();
} catch (IOException ex) {
throw new RuntimeException("unable to write " + filename, ex);
}
}
/**
* log matrix values produced by SwitchingPlanner's simulation.
*/
private void logMatrix(GameState state) {
assert logMatrix != null;
double[][] v = getValues(); // get matrix produced by SwitchingPlanner simulation.
// transpose for presentation
double[][] vt = new double[v[0].length][v.length];
for (int i = 0; i < v.length; i++) {
for (int j = 0; j < v[0].length; j++) {
vt[j][i] = v[i][j];
}
}
v = vt;
String gameName = state.getMap().getName();
if (gameName == null) {
gameName = "";
} else if (playerId == 1) {
gameName += "_switched";
}
String[] colhdr = new String[strategies.length];
String[] rowhdr = new String[strategies.length];
for (int i = 0; i < rowhdr.length; i++) {
rowhdr[i] = i + ". " + strategies[i].getName().replace("_", " ");
}
for (int j = 0; j < colhdr.length; j++) {
colhdr[j] = j + ". ";
}
String caption = String.format("%s vs. %s Simulation Matrix on %s at %d.",
choiceMethod,
opponentName,
gameName.replace("_"," "),
state.getCycle());
Map<String,Integer> properties = new LinkedHashMap<String,Integer>();
properties.put("cycle", state.getCycle());
String label = "sim_planner_matrix_" + gameName;
File f = new File(".",logMatrix);
try {
BufferedWriter doc = new BufferedWriter(new FileWriter(f,true)); // append
String comment = "table written by " + SwitchingPlanner.class.getSimpleName();
YamlTable.write_YAML_table(properties,v, colhdr, rowhdr, label, caption, doc, comment);
doc.close();
} catch (IOException e) {
log.error("Unable to write file " + logMatrix);
}
}
/**
* Write strategy definitions to YAML file.
*/
public static void main(String[] args) throws Exception {
String dir = ".";
if (args.length > 0) {
dir = args[0];
}
logStrategies("atk-dfnd",dir);
logStrategies("synth",dir);
logStrategies("2011-11-01",dir);
logStrategies("2012-02-05",dir);
}
private boolean logPair(int i, int j) {
return log_pair != null && log_pair[0] == i && log_pair[1] == j;
}
private void logEvents(int i, int j) {
if (logPair(i,j)) {
simlog.removeAllAppenders();
String filename = "game_events_sim.txt";
Layout layout = new SimpleLayout();
try {
Appender append = new FileAppender(layout, filename, true);
simlog.addAppender(append);
simlog.setLevel(Level.INFO);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
simlog.info("SwitchingPlanner simulation of " +
planners[i].getTemplate().getName() + " vs. " +
planners[j].getTemplate().getName());
}
}
private void logScores(StrategicState state) {
final String filename = "game_scores_sim.txt";
try {
// open for append.
BufferedWriter out = new BufferedWriter(new FileWriter(filename, true));
int[] scores = state.getGameState().getScores();
out.write(
String.format("cycle:%d\tscore[0]:%d\tscore[1]%d\tdiff:%d%s",
state.getCycle(),scores[0],scores[1],scores[0]-scores[1],NL));
out.close();
} catch (IOException ex) {
throw new RuntimeException("unable to write " + filename, ex);
}
}
}
| |
/**
* This file is part of the AMEE Java Client Library.
*
* Copyright (c) 2008 AMEE UK Ltd. (http://www.amee.com)
*
* The AMEE Java Client Library is free software, released under the MIT
* license. See mit-license.txt for details.
*/
package com.amee.client;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import com.amee.client.model.base.AmeeCategory;
import com.amee.client.model.base.AmeeItem;
import com.amee.client.model.base.AmeeObjectReference;
import com.amee.client.model.base.AmeeObjectType;
import com.amee.client.model.base.AmeeValue;
import com.amee.client.model.data.AmeeDataCategory;
import com.amee.client.model.data.AmeeDataItem;
import com.amee.client.model.data.AmeeDrillDown;
import com.amee.client.model.profile.AmeeProfile;
import com.amee.client.model.profile.AmeeProfileCategory;
import com.amee.client.model.profile.AmeeProfileItem;
import com.amee.client.service.AmeeContext;
import com.amee.client.service.AmeeObjectFactory;
import com.amee.client.util.Choice;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class AmeeTest {
public static void main(String[] args) throws AmeeException {
long start = Calendar.getInstance().getTimeInMillis();
System.out.println("Start: " + start);
AmeeContext.getInstance().setUsername("USER");
AmeeContext.getInstance().setPassword("PASS");
AmeeContext.getInstance().setBaseUrl("http://stage.amee.com");
// AmeeObjectFactory.getInstance().setCache(null);
// testObjectReference();
// testDataCategoryA();
// testDataCategoryPagination();
// testDataCategoryTree();
// testDrillDown();
// testAuthRenewal(null);
// testNewProfile();
// testProfileCategoryPagination();
long end = Calendar.getInstance().getTimeInMillis();
System.out.println("End: " + end);
System.out.println("Duration: " + (end - start));
}
private static long startAR=-1;
public static void testAuthRenewal(final String puid){
JFrame jf = new JFrame();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JButton idleTimeButton = new JButton("Print idle time");
final JTextArea jta = new JTextArea();
final JButton sendButton = new JButton("Send request");
jf.getContentPane().add(idleTimeButton,BorderLayout.NORTH);
jf.getContentPane().add(sendButton,BorderLayout.SOUTH);
ActionListener al = new ActionListener(){
public void actionPerformed(ActionEvent evt){
AmeeObjectFactory objectFactory=null;
long currentTime = Calendar.getInstance().getTimeInMillis();
long diff = currentTime-startAR;
System.err.println("Idle time (sec) = "+diff/1000);
if(evt.getSource().equals(sendButton)){
startAR = currentTime;
System.err.println("======= "+startAR);
if(objectFactory==null)
objectFactory = AmeeObjectFactory.getInstance();
try {
AmeeProfile profile = null;
if(puid!=null)
profile = objectFactory.getProfile(puid);
else
profile = objectFactory.addProfile();
System.err.println("profile UID = "+profile.getUid());
} catch (AmeeException ex) {
ex.printStackTrace();
}
}
}
};
idleTimeButton.addActionListener(al);
sendButton.addActionListener(al);
jf.pack();
jf.setVisible(true);
}
public static void testDataCategoryA() throws AmeeException {
AmeeObjectFactory ameeObjectFactory = AmeeObjectFactory.getInstance();
AmeeDataCategory dataCategory = ameeObjectFactory.getDataCategory("home/appliances/computers/generic");
while (dataCategory != null) {
printCategory(dataCategory);
dataCategory = (AmeeDataCategory) dataCategory.getParent();
}
}
public static void testDataCategoryPagination() throws AmeeException {
AmeeObjectFactory ameeObjectFactory = AmeeObjectFactory.getInstance();
AmeeDataCategory dataCategory = ameeObjectFactory.getDataCategory("home/appliances/kitchen/generic");
for (int i = 1; i <= dataCategory.getItemsPager().getLastPage(); i++) {
dataCategory.setPage(i);
dataCategory.fetch();
System.out.println("Page: " + i);
printCategory(dataCategory);
}
}
public static void testDataCategoryTree() throws AmeeException {
AmeeObjectFactory ameeObjectFactory = AmeeObjectFactory.getInstance();
printCategoryTree(ameeObjectFactory.getDataCategoryRoot());
}
public static void printCategoryTree(AmeeCategory category) throws AmeeException {
String out;
AmeeProfileCategory profileCategory;
for (AmeeCategory childCategory : category.getCategories()) {
out = childCategory.getUri();
if (childCategory instanceof AmeeProfileCategory) {
profileCategory = (AmeeProfileCategory) childCategory;
out = out + " (Amount=" + profileCategory.getAmount() + ")";
}
System.out.println(out);
printCategoryTree(childCategory);
}
for (AmeeItem childItem : category.getItems()) {
System.out.println(childItem.getUri() + "=" + childItem.getLabel());
for (AmeeValue value : childItem.getValues()) {
System.out.println(value.getUri() + "=" + value.getValue());
value.fetch();
}
}
}
public static void printCategory(AmeeCategory category) throws AmeeException {
System.out.println(category.getUri());
for (AmeeCategory childCategory : category.getCategories()) {
System.out.println(childCategory.getUri());
}
for (AmeeItem childItem : category.getItems()) {
System.out.println(childItem.getUri() + "=" + childItem.getLabel());
for (AmeeValue value : childItem.getValues()) {
System.out.println(value.getUri() + "=" + value.getValue());
value.fetch();
}
childItem.fetch();
}
}
public static void testDrillDown() throws AmeeException {
AmeeObjectFactory objectFactory = AmeeObjectFactory.getInstance();
AmeeDrillDown ameeDrillDown = objectFactory.getDrillDown("home/appliances/computers/generic/drill");
while (ameeDrillDown.hasChoices()) {
ameeDrillDown.addSelection(ameeDrillDown.getChoiceName(), ameeDrillDown.getChoices().get(0).getValue());
ameeDrillDown.fetch();
}
AmeeDataItem ameeDataItem = ameeDrillDown.getDataItem();
if (ameeDataItem != null) {
System.out.println("DataItem Label: " + ameeDataItem.getLabel());
System.out.println("DataItem UID: " + ameeDataItem.getUid());
}
}
public static void testExistingProfile(String profileUid) throws AmeeException {
AmeeObjectFactory objectFactory = AmeeObjectFactory.getInstance();
AmeeProfile profile = objectFactory.getProfile(profileUid);
//printCategoryTree(profile);
}
public static void testNewProfile() throws AmeeException {
List<Choice> values;
AmeeObjectFactory objectFactory = AmeeObjectFactory.getInstance();
// create the profile
AmeeProfile profile = objectFactory.addProfile();
// get a category
AmeeProfileCategory profileCategory = objectFactory.getProfileCategory(profile, "home/appliances/computers/generic");
profileCategory.getItemsPager().goNextPage();
// create an item
values = new ArrayList<Choice>();
values.add(new Choice("numberOwned", "20"));
AmeeProfileItem profileItem = profileCategory.addProfileItem("B32624F8CD5F", values);
// print the profile
System.out.println("*** After adding an item ***");
printCategoryTree(profile);
// update the value
AmeeValue value = profileItem.getValue("numberOwned");
value.setValue("30");
value.save();
// print the profile
System.out.println("*** After updating a value directly ***");
printCategoryTree(profile);
// update the item
values = new ArrayList<Choice>();
values.add(new Choice("numberOwned", "40"));
profileItem.setValues(values);
// print the profile
System.out.println("*** After updating values via in item ***");
printCategoryTree(profile);
// delete the item
profileItem.delete();
// print the profile
System.out.println("*** After deleting the item ***");
printCategoryTree(profile);
// delete the profile
profile.delete();
System.out.println("*** done ***");
}
public static void testProfileCategoryPagination() throws AmeeException {
AmeeObjectFactory objectFactory = AmeeObjectFactory.getInstance();
AmeeProfile profile = objectFactory.addProfile();
AmeeProfileCategory profileCategory = objectFactory.getProfileCategory(profile, "home/appliances/kitchen/generic");
AmeeDrillDown drillDown = objectFactory.getDrillDown("home/appliances/kitchen/generic/drill");
testProfileCategoryPagination(profileCategory, drillDown);
for (int i = 1; i <= profileCategory.getItemsPager().getLastPage(); i++) {
profileCategory.setPage(i);
profileCategory.fetch();
System.out.println("Page: " + i);
printCategoryTree(profileCategory);
}
}
public static void testProfileCategoryPagination(AmeeProfileCategory profileCategory, AmeeDrillDown drillDown) throws AmeeException {
String dataItemUid = drillDown.getDataItemPathSegment();
AmeeDrillDown newDrillDown;
if (dataItemUid == null) {
// drill further
for (Choice choice: drillDown.getChoices()) {
newDrillDown = (AmeeDrillDown) drillDown.getCopy();
newDrillDown.addSelection(drillDown.getChoiceName(), choice.getValue());
newDrillDown.fetch();
testProfileCategoryPagination(profileCategory, newDrillDown);
}
} else {
// stop drilling - add profile item
System.out.println("Adding: " + dataItemUid);
profileCategory.addProfileItem(dataItemUid);
}
}
public static void testObjectReference() throws AmeeException {
printObjectReference(new AmeeObjectReference("", AmeeObjectType.UNKNOWN));
printObjectReference(new AmeeObjectReference("/", AmeeObjectType.UNKNOWN));
printObjectReference(new AmeeObjectReference("/hello.txt", AmeeObjectType.UNKNOWN));
printObjectReference(new AmeeObjectReference("big/hello.txt", AmeeObjectType.UNKNOWN));
printObjectReference(new AmeeObjectReference("very/big/hello.txt", AmeeObjectType.UNKNOWN));
printObjectReference(new AmeeObjectReference("/very/big/hello.txt", AmeeObjectType.UNKNOWN));
printObjectReference(new AmeeObjectReference("/very/big/", AmeeObjectType.UNKNOWN));
printObjectReference(new AmeeObjectReference("/very/", AmeeObjectType.UNKNOWN));
printObjectReference(new AmeeObjectReference("very", AmeeObjectType.UNKNOWN));
printObjectReference(new AmeeObjectReference("very/big", AmeeObjectType.UNKNOWN));
}
public static void printObjectReference(AmeeObjectReference ref) {
System.out.println("Path: " + ref.getUri());
System.out.println(" LocalPath: " + ref.getLocalPart());
System.out.println(" ParentPath: " + ref.getParentUri());
}
}
| |
/*******************************************************************************
* Copyright (c) 2010, 2015 IBM Corporation and others.
* 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:
* IBM Corporation - initial API and implementation
* Philipp Bumann <bumannp@gmail.com> - Bug 477602
******************************************************************************/
package org.eclipse.e4.ui.progress.internal;
import java.lang.reflect.InvocationTargetException;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.inject.Inject;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.IJobManager;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.e4.core.di.annotations.Optional;
import org.eclipse.e4.ui.di.UISynchronize;
import org.eclipse.e4.ui.progress.IProgressConstants;
import org.eclipse.e4.ui.progress.IProgressService;
import org.eclipse.e4.ui.progress.UIJob;
import org.eclipse.e4.ui.progress.internal.legacy.EventLoopProgressMonitor;
import org.eclipse.e4.ui.progress.internal.legacy.PlatformUI;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.operation.IRunnableContext;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class ProgressServiceImpl implements IProgressService {
private static final String IMAGE_KEY = "org.eclipse.ui.progress.images"; //$NON-NLS-1$
private Hashtable<Object, String> imageKeyTable = new Hashtable<>();
@Inject
@Optional
ProgressManager progressManager;
@Inject
@Optional
FinishedJobs finishedJobs;
@Inject
@Optional
ContentProviderFactory contentProviderFactory;
@Inject
@Optional
UISynchronize uiSynchronize;
@Override
public int getLongOperationTime() {
return 800;
}
@Override
public void registerIconForFamily(ImageDescriptor icon, Object family) {
String key = IMAGE_KEY + String.valueOf(imageKeyTable.size());
imageKeyTable.put(family, key);
ImageRegistry registry = JFaceResources.getImageRegistry();
// Avoid registering twice
if (registry.getDescriptor(key) == null) {
registry.put(key, icon);
}
}
@Override
public void runInUI(IRunnableContext context,
IRunnableWithProgress runnable, ISchedulingRule rule)
throws InvocationTargetException, InterruptedException {
final RunnableWithStatus runnableWithStatus = new RunnableWithStatus(
context,
runnable, rule);
uiSynchronize.syncExec(new Runnable() {
@Override
public void run() {
BusyIndicator.showWhile(getDisplay(), runnableWithStatus);
}
});
IStatus status = runnableWithStatus.getStatus();
if (!status.isOK()) {
Throwable exception = status.getException();
if (exception instanceof InvocationTargetException)
throw (InvocationTargetException) exception;
else if (exception instanceof InterruptedException)
throw (InterruptedException) exception;
else // should be OperationCanceledException
throw new InterruptedException(exception.getMessage());
}
}
@Override
public Image getIconFor(Job job) {
Enumeration<Object> families = imageKeyTable.keys();
while (families.hasMoreElements()) {
Object next = families.nextElement();
if (job.belongsTo(next)) {
return JFaceResources.getImageRegistry().get(imageKeyTable.get(next));
}
}
return null;
}
@Override
public void busyCursorWhile(final IRunnableWithProgress runnable)
throws InvocationTargetException, InterruptedException {
final ProgressMonitorJobsDialog dialog = new ProgressMonitorJobsDialog(
ProgressManagerUtil.getDefaultParent(), this, progressManager,
contentProviderFactory, finishedJobs);
dialog.setOpenOnRun(false);
final InvocationTargetException[] invokes = new InvocationTargetException[1];
final InterruptedException[] interrupt = new InterruptedException[1];
// show a busy cursor until the dialog opens
Runnable dialogWaitRunnable = new Runnable() {
@Override
public void run() {
try {
dialog.setOpenOnRun(false);
setUserInterfaceActive(false);
dialog.run(true, true, runnable);
} catch (InvocationTargetException e) {
invokes[0] = e;
} catch (InterruptedException e) {
interrupt[0] = e;
} finally {
setUserInterfaceActive(true);
}
}
};
busyCursorWhile(dialogWaitRunnable, dialog);
if (invokes[0] != null) {
throw invokes[0];
}
if (interrupt[0] != null) {
throw interrupt[0];
}
}
@Override
public void run(boolean fork, boolean cancelable,
IRunnableWithProgress runnable) throws InvocationTargetException,
InterruptedException {
if (fork == false || cancelable == false) {
// backward compatible code
final ProgressMonitorJobsDialog dialog = new ProgressMonitorJobsDialog(
null, this, progressManager, contentProviderFactory,
finishedJobs);
dialog.run(fork, cancelable, runnable);
return;
}
busyCursorWhile(runnable);
}
@Override
public void showInDialog(Shell shell, Job job) {
if (shouldRunInBackground()) {
return;
}
final ProgressMonitorFocusJobDialog dialog = new ProgressMonitorFocusJobDialog(
shell, this, progressManager, contentProviderFactory,
finishedJobs);
dialog.show(job, shell);
}
/**
* Return whether or not dialogs should be run in the background
*
* @return <code>true</code> if the dialog should not be shown.
*/
protected boolean shouldRunInBackground() {
return Preferences.getBoolean(IProgressConstants.RUN_IN_BACKGROUND);
}
private class RunnableWithStatus implements Runnable {
IStatus status = Status.OK_STATUS;
private final IRunnableContext context;
private final IRunnableWithProgress runnable;
private final ISchedulingRule rule;
public RunnableWithStatus(IRunnableContext context,
IRunnableWithProgress runnable, ISchedulingRule rule) {
this.context = context;
this.runnable = runnable;
this.rule = rule;
}
@Override
public void run() {
IJobManager manager = Job.getJobManager();
try {
manager.beginRule(rule, getEventLoopMonitor());
context.run(false, false, runnable);
} catch (InvocationTargetException e) {
status = new Status(IStatus.ERROR, IProgressConstants.PLUGIN_ID, e
.getMessage(), e);
} catch (InterruptedException e) {
status = new Status(IStatus.ERROR, IProgressConstants.PLUGIN_ID, e
.getMessage(), e);
} catch (OperationCanceledException e) {
status = new Status(IStatus.ERROR, IProgressConstants.PLUGIN_ID, e
.getMessage(), e);
} finally {
manager.endRule(rule);
}
}
/**
* Get a progress monitor that forwards to an event loop monitor.
* Override #setBlocked() so that we always open the blocked dialog.
*
* @return the monitor on the event loop
*/
private IProgressMonitor getEventLoopMonitor() {
if (PlatformUI.isWorkbenchStarting())
return new NullProgressMonitor();
return new EventLoopProgressMonitor(new NullProgressMonitor()) {
@Override
public void setBlocked(IStatus reason) {
// Set a shell to open with as we want to create
// this
// even if there is a modal shell.
Dialog.getBlockedHandler().showBlocked(
ProgressManagerUtil.getDefaultParent(), this,
reason, getTaskName());
}
};
}
public IStatus getStatus() {
return status;
}
}
/**
* Show the busy cursor while the runnable is running. Schedule a job to
* replace it with a progress dialog.
*
* @param dialogWaitRunnable
* @param dialog
*/
private void busyCursorWhile(Runnable dialogWaitRunnable,
ProgressMonitorJobsDialog dialog) {
// create the job that will open the dialog after a delay
scheduleProgressMonitorJob(dialog);
final Display display = getDisplay();
if (display == null) {
return;
}
// show a busy cursor until the dialog opens
BusyIndicator.showWhile(display, dialogWaitRunnable);
}
/**
* Schedule the job that will open the progress monitor dialog
*
* @param dialog
* the dialog to open
*/
private void scheduleProgressMonitorJob(
final ProgressMonitorJobsDialog dialog) {
final Job updateJob = new UIJob(
ProgressMessages.ProgressManager_openJobName) {
@Override
public IStatus runInUIThread(IProgressMonitor monitor) {
setUserInterfaceActive(true);
if (ProgressManagerUtil.safeToOpen(dialog, null)) {
dialog.open();
}
return Status.OK_STATUS;
}
};
updateJob.setSystem(true);
updateJob.schedule(getLongOperationTime());
}
/**
* Iterate through all of the windows and set them to be disabled or enabled
* as appropriate.'
*
* @param active
* The set the windows will be set to.
*/
private void setUserInterfaceActive(boolean active) {
Shell[] shells = getDisplay().getShells();
if (active) {
for (int i = 0; i < shells.length; i++) {
if (!shells[i].isDisposed()) {
shells[i].setEnabled(active);
}
}
} else {
// Deactive shells in reverse order
for (int i = shells.length - 1; i >= 0; i--) {
if (!shells[i].isDisposed()) {
shells[i].setEnabled(active);
}
}
}
}
protected Display getDisplay() {
return Services.getInstance().getDisplay();
}
}
| |
/*
* Copyright 2021 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.server.newsecurity.filterchains;
import com.thoughtworks.go.config.SecurityAuthConfig;
import com.thoughtworks.go.domain.AccessToken;
import com.thoughtworks.go.http.mocks.HttpRequestBuilder;
import com.thoughtworks.go.http.mocks.MockHttpServletRequest;
import com.thoughtworks.go.http.mocks.MockHttpServletResponse;
import com.thoughtworks.go.http.mocks.MockHttpServletResponseAssert;
import com.thoughtworks.go.server.newsecurity.filters.*;
import com.thoughtworks.go.server.newsecurity.handlers.BasicAuthenticationWithChallengeFailureResponseHandler;
import com.thoughtworks.go.server.newsecurity.models.AnonymousCredential;
import com.thoughtworks.go.server.newsecurity.models.AuthenticationToken;
import com.thoughtworks.go.server.newsecurity.models.UsernamePassword;
import com.thoughtworks.go.server.newsecurity.providers.AccessTokenBasedPluginAuthenticationProvider;
import com.thoughtworks.go.server.newsecurity.providers.AnonymousAuthenticationProvider;
import com.thoughtworks.go.server.newsecurity.providers.PasswordBasedPluginAuthenticationProvider;
import com.thoughtworks.go.server.newsecurity.utils.SessionUtils;
import com.thoughtworks.go.server.security.AuthorityGranter;
import com.thoughtworks.go.server.security.GoAuthority;
import com.thoughtworks.go.server.service.*;
import com.thoughtworks.go.util.SystemEnvironment;
import com.thoughtworks.go.util.TestingClock;
import org.junit.Rule;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.junit.rules.TemporaryFolder;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import static com.thoughtworks.go.helper.AccessTokenMother.randomAccessTokenForUser;
import static com.thoughtworks.go.server.newsecurity.filterchains.DenyGoCDAccessForArtifactsFilterChainTest.wrap;
import static com.thoughtworks.go.server.newsecurity.filters.InvalidateAuthenticationOnSecurityConfigChangeFilter.SECURITY_CONFIG_LAST_CHANGE;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
@EnableRuleMigrationSupport
public class AuthenticationFilterChainTest {
@Rule
public final TemporaryFolder temporaryFolder = new TemporaryFolder();
private MockHttpServletResponse response;
private MockHttpServletRequest request;
private FilterChain filterChain;
private SecurityService securityService;
private TestingClock clock;
private SystemEnvironment systemEnvironment;
private AssumeAnonymousUserFilter assumeAnonymousUserFilter;
@BeforeEach
void setUp() throws IOException {
response = new MockHttpServletResponse();
filterChain = mock(FilterChain.class);
securityService = mock(SecurityService.class);
clock = new TestingClock();
systemEnvironment = new SystemEnvironment();
final AnonymousAuthenticationProvider anonymousAuthenticationProvider = new AnonymousAuthenticationProvider(clock, new AuthorityGranter(securityService));
assumeAnonymousUserFilter = new AssumeAnonymousUserFilter(securityService, anonymousAuthenticationProvider);
temporaryFolder.create();
}
@AfterEach
void tearDown() {
temporaryFolder.delete();
}
@Nested
class SecurityEnabled {
@BeforeEach
void setUp() {
when(securityService.isSecurityEnabled()).thenReturn(true);
}
@ParameterizedTest
@ValueSource(strings = {"/remoting/blah"})
void shouldErrorOutWithStatusCode403WhenNoAgentTokenProvidedInRequest(String url) throws IOException, ServletException {
request = HttpRequestBuilder.GET(url)
.build();
final AgentAuthenticationFilter agentAuthenticationFilter = new AgentAuthenticationFilter(null, clock, null);
final AuthenticationFilterChain authenticationFilterChain = new AuthenticationFilterChain(agentAuthenticationFilter, null, null, null, null, null, null, null);
authenticationFilterChain.doFilter(request, response, filterChain);
verifyZeroInteractions(filterChain);
MockHttpServletResponseAssert.assertThat(response).isForbidden();
assertThat(SessionUtils.getAuthenticationToken(request)).isNull();
}
@ParameterizedTest
@ValueSource(strings = {"/api/config-repository.git/git-upload-something", "/cctray.xml", "/api/foo", "/blah"})
void shouldInvalidateAuthenticationIfSecurityConfigIsChanged(String url) throws IOException, ServletException {
request = HttpRequestBuilder.GET(url)
.withRequestedSessionIdFromSession()
.build();
final AuthenticationToken authenticationToken = mock(AuthenticationToken.class);
SessionUtils.setAuthenticationTokenAfterRecreatingSession(authenticationToken, request);
request.getSession(false).setAttribute(SECURITY_CONFIG_LAST_CHANGE, clock.currentTimeMillis());
final InvalidateAuthenticationOnSecurityConfigChangeFilter invalidateAuthenticationOnSecurityConfigChangeFilter = new InvalidateAuthenticationOnSecurityConfigChangeFilter(
mock(GoConfigService.class), clock, mock(AuthorizationExtensionCacheService.class), mock(PluginRoleService.class));
clock.addSeconds(1000);
invalidateAuthenticationOnSecurityConfigChangeFilter.onPluginRoleChange();
final Filter filter = mock(Filter.class);
final AuthenticationFilterChain authenticationFilterChain = new AuthenticationFilterChain(null, invalidateAuthenticationOnSecurityConfigChangeFilter, filter, filter, null, null, null, assumeAnonymousUserFilter);
authenticationFilterChain.doFilter(request, response, filterChain);
verify(filter).doFilter(wrap(request), wrap(response), any());
verify(authenticationToken).invalidate();
MockHttpServletResponseAssert.assertThat(response).isOk();
assertThat(SessionUtils.getAuthenticationToken(request)).isNotNull();
}
@ParameterizedTest
@ValueSource(strings = {"/api/config-repository.git/git-upload-something", "/cctray.xml", "/api/foo", "/blah"})
void shouldReauthenticateIfAuthenticationTokenIsInvalid(String url) throws IOException, ServletException {
request = HttpRequestBuilder.GET(url)
.build();
final UsernamePassword credentials = new UsernamePassword("bob", "p@ssword");
final AuthenticationToken<UsernamePassword> authenticationToken = new AuthenticationToken<>(null, credentials, null, 0, null);
SessionUtils.setAuthenticationTokenAfterRecreatingSession(authenticationToken, request);
final PasswordBasedPluginAuthenticationProvider pluginAuthenticationProvider = mock(PasswordBasedPluginAuthenticationProvider.class);
final AuthenticationToken reauthenticatedToken = mock(AuthenticationToken.class);
when(pluginAuthenticationProvider.reauthenticate(authenticationToken)).thenReturn(reauthenticatedToken);
new AuthenticationFilterChain(null, new NoOpFilter(),
new ReAuthenticationWithRedirectToLoginFilter(securityService, systemEnvironment, clock, pluginAuthenticationProvider, null, null),
new ReAuthenticationWithChallengeFilter(securityService, systemEnvironment, clock, mock(BasicAuthenticationWithChallengeFailureResponseHandler.class), pluginAuthenticationProvider, null, null),
new NoOpFilter(),
new NoOpFilter(),
new NoOpFilter(),
assumeAnonymousUserFilter)
.doFilter(request, response, filterChain);
verify(filterChain).doFilter(wrap(request), wrap(response));
MockHttpServletResponseAssert.assertThat(response).isOk();
assertThat(SessionUtils.getAuthenticationToken(request)).isSameAs(reauthenticatedToken);
}
@ParameterizedTest
@ValueSource(strings = {"/add-on/blah", "/api/webhooks/bitbucket/notify", "/api/webhooks/github/notify", "/api/webhooks/foo/notify"})
void shouldAllowAnonymousAccessForWebhookAndAddonApis(String url) throws IOException, ServletException {
request = HttpRequestBuilder.GET(url)
.build();
new AuthenticationFilterChain(null, null,
null,
null,
null,
null,
null,
assumeAnonymousUserFilter)
.doFilter(request, response, filterChain);
verify(filterChain).doFilter(wrap(request), wrap(response));
MockHttpServletResponseAssert.assertThat(response).isOk();
assertThat(SessionUtils.getAuthenticationToken(request).getCredentials()).isSameAs(AnonymousCredential.INSTANCE);
}
@ParameterizedTest
@ValueSource(strings = {"/api/config-repository.git/git-upload-something", "/cctray.xml", "/api/foo", "/blah"})
void shouldAuthenticateUsingBasicAuthForAllCalls(String url) throws IOException, ServletException {
request = HttpRequestBuilder.GET(url)
.withBasicAuth("bob", "password")
.build();
HttpSession originalSession = request.getSession();
final PasswordBasedPluginAuthenticationProvider pluginAuthenticationProvider = mock(PasswordBasedPluginAuthenticationProvider.class);
final AuthenticationToken<UsernamePassword> authenticationToken = mock(AuthenticationToken.class);
when(pluginAuthenticationProvider.authenticate(new UsernamePassword("bob", "password"), null)).thenReturn(authenticationToken);
new AuthenticationFilterChain(null,
new NoOpFilter(),
new NoOpFilter(),
new NoOpFilter(),
new BasicAuthenticationWithChallengeFilter(securityService, new BasicAuthenticationWithChallengeFailureResponseHandler(securityService), pluginAuthenticationProvider),
new BasicAuthenticationWithRedirectToLoginFilter(securityService, pluginAuthenticationProvider), new NoOpFilter(),
assumeAnonymousUserFilter).doFilter(request, response, filterChain);
verify(filterChain).doFilter(wrap(request), wrap(response));
MockHttpServletResponseAssert.assertThat(response).isOk();
assertThat(SessionUtils.getAuthenticationToken(request)).isSameAs(authenticationToken);
assertThat(request.getSession(false)).isNotSameAs(originalSession);
}
@ParameterizedTest
@ValueSource(strings = {"/cctray.xml", "/api/foo", "/api/blah", "/files/some-artifact", "/properties/moo"})
void shouldAuthenticateUsingAccessTokenAuthenticationFilter(String url) throws IOException, ServletException {
final AccessTokenService accessTokenService = mock(AccessTokenService.class);
final SecurityAuthConfigService securityAuthConfigService = mock(SecurityAuthConfigService.class);
final AccessTokenBasedPluginAuthenticationProvider provider = mock(AccessTokenBasedPluginAuthenticationProvider.class);
final AccessToken accessToken = randomAccessTokenForUser("bob");
request = HttpRequestBuilder.GET(url)
.withBearerAuth("some-access-token")
.build();
when(securityAuthConfigService.findProfile(anyString())).thenReturn(new SecurityAuthConfig());
HttpSession originalSession = request.getSession();
when(accessTokenService.findByAccessToken("some-access-token")).thenReturn(accessToken);
final AuthenticationToken authenticationToken = mock(AuthenticationToken.class);
when(provider.authenticateUser(any(), any())).thenReturn(authenticationToken);
final AccessTokenAuthenticationFilter accessTokenAuthenticationFilter = new AccessTokenAuthenticationFilter(securityService, accessTokenService, securityAuthConfigService, provider);
new AuthenticationFilterChain(null,
new NoOpFilter(), new NoOpFilter(), new NoOpFilter(),
new NoOpFilter(), new NoOpFilter(), accessTokenAuthenticationFilter,
assumeAnonymousUserFilter).doFilter(request, response, filterChain);
verify(filterChain).doFilter(wrap(request), wrap(response));
MockHttpServletResponseAssert.assertThat(response).isOk();
assertThat(SessionUtils.getAuthenticationToken(request)).isSameAs(authenticationToken);
assertThat(request.getSession(false)).isNotSameAs(originalSession);
}
}
@Nested
class SecurityDisabled {
@BeforeEach
void setUp() {
when(securityService.isSecurityEnabled()).thenReturn(false);
}
@ParameterizedTest
@ValueSource(strings = {
"/api/config-repository.git/git-upload-something", "/cctray.xml", "/api/foo",
"/auth/login", "/auth/logout", "/plugin/foo/login", "/plugin/foo/authenticate", "/blah"
})
void shouldAuthenticateAsAnonymousWhenSecurityIsDisabled(String url) throws IOException, ServletException {
request = HttpRequestBuilder.GET(url).build();
new AuthenticationFilterChain(null,
new NoOpFilter(),
new NoOpFilter(),
new NoOpFilter(),
new NoOpFilter(),
new NoOpFilter(),
new NoOpFilter(),
assumeAnonymousUserFilter).doFilter(request, response, filterChain);
verify(filterChain).doFilter(wrap(request), wrap(response));
MockHttpServletResponseAssert.assertThat(response).isOk();
final AuthenticationToken<?> authenticationToken = SessionUtils.getAuthenticationToken(request);
assertThat(authenticationToken).isNotNull();
assertThat(authenticationToken.getCredentials()).isEqualTo(AnonymousCredential.INSTANCE);
assertThat(authenticationToken.getPluginId()).isEqualTo(null);
assertThat(authenticationToken.getAuthConfigId()).isEqualTo(null);
assertThat(authenticationToken.getUser().getUsername()).isEqualTo("anonymous");
assertThat(authenticationToken.getUser().getDisplayName()).isEqualTo("anonymous");
assertThat(authenticationToken.getUser().getAuthorities()).isEqualTo(GoAuthority.ALL_AUTHORITIES);
}
@ParameterizedTest
@ValueSource(strings = {"/remoting/foo"})
void shouldNotApplyAnonymousAuthenticationFilterOnUrls(String url) throws IOException, ServletException {
request = HttpRequestBuilder.GET(url).build();
new AuthenticationFilterChain(
new NoOpFilter(),
new NoOpFilter(),
new NoOpFilter(),
new NoOpFilter(),
new NoOpFilter(),
new NoOpFilter(),
null,
assumeAnonymousUserFilter).doFilter(request, response, filterChain);
verify(filterChain).doFilter(wrap(request), wrap(response));
MockHttpServletResponseAssert.assertThat(response).isOk();
assertThat(SessionUtils.getAuthenticationToken(request)).isNull();
}
}
}
| |
package com.constantinnovationsinc.livemultimedia.servers;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.StringTokenizer;
public class SimpleWebServer extends NanoHTTPD {
private static final String TAG = SimpleWebServer.class.getCanonicalName();
/**
* Common mime type for dynamic content: binary
*/
public static final String MIME_DEFAULT_BINARY = "application/octet-stream";
/**
* Default Index file names.
*/
public static final List<String> INDEX_FILE_NAMES = new ArrayList<String>() {{
add("index.html");
add("index.htm");
}};
/**
* Hashtable mapping (String)FILENAME_EXTENSION -> (String)MIME_TYPE
*/
private static final Map<String, String> MIME_TYPES = new HashMap<String, String>() {{
put("css", "text/css");
put("htm", "text/html");
put("html", "text/html");
put("xml", "text/xml");
put("java", "text/x-java-source, text/java");
put("md", "text/plain");
put("txt", "text/plain");
put("asc", "text/plain");
put("gif", "image/gif");
put("jpg", "image/jpeg");
put("jpeg", "image/jpeg");
put("png", "image/png");
put("mp3", "audio/mpeg");
put("m3u", "audio/mpeg-url");
put("mp4", "video/mp4");
put("ogv", "video/ogg");
put("flv", "video/x-flv");
put("mov", "video/quicktime");
put("swf", "application/x-shockwave-flash");
put("js", "application/javascript");
put("pdf", "application/pdf");
put("doc", "application/msword");
put("ogg", "application/x-ogg");
put("zip", "application/octet-stream");
put("exe", "application/octet-stream");
put("class", "application/octet-stream");
}};
/**
* The distribution licence
*/
private static final String LICENCE =
"Copyright (c) 2012-2013 by Paul S. Hawke, 2001,2005-2013 by Jarno Elonen, 2010 by Konstantinos Togias\n"
+ "\n"
+ "Redistribution and use in source and binary forms, with or without\n"
+ "modification, are permitted provided that the following conditions\n"
+ "are met:\n"
+ "\n"
+ "Redistributions of source code must retain the above copyright notice,\n"
+ "this list of conditions and the following disclaimer. Redistributions in\n"
+ "binary form must reproduce the above copyright notice, this list of\n"
+ "conditions and the following disclaimer in the documentation and/or other\n"
+ "materials provided with the distribution. The name of the author may not\n"
+ "be used to endorse or promote products derived from this software without\n"
+ "specific prior written permission. \n"
+ " \n"
+ "THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n"
+ "IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n"
+ "OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n"
+ "IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n"
+ "INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n"
+ "NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n"
+ "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n"
+ "THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n"
+ "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n"
+ "OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.";
private static Map<String, WebServerPlugin> mimeTypeHandlers = new HashMap<>();
private final List<File> rootDirs;
private final boolean quiet;
public SimpleWebServer(String host, int port, File wwwroot, boolean quiet) {
super(host, port);
this.quiet = quiet;
this.rootDirs = new ArrayList<>();
this.rootDirs.add(wwwroot);
this.init();
}
public SimpleWebServer(String host, int port, List<File> wwwroots, boolean quiet) {
super(host, port);
this.quiet = quiet;
this.rootDirs = new ArrayList<>(wwwroots);
this.init();
}
/**
* Used to initialize and customize the server.
*/
public void init() {
Log.d(TAG, "Init Web Server");
}
/**
* Starts as a standalone file server and waits for Enter.
*/
public static void main(String[] args) {
// Defaults
int port = 8080;
String host = "127.0.0.1";
List<File> rootDirs = new ArrayList<>();
boolean quiet = false;
Map<String, String> options = new HashMap<>();
// Parse command-line, with short and long versions of the options.
for (int i = 0; i < args.length; ++i) {
if (args[i].equalsIgnoreCase("-h") || args[i].equalsIgnoreCase("--host")) {
host = args[i + 1];
} else if (args[i].equalsIgnoreCase("-p") || args[i].equalsIgnoreCase("--port")) {
port = Integer.parseInt(args[i + 1]);
} else if (args[i].equalsIgnoreCase("-q") || args[i].equalsIgnoreCase("--quiet")) {
quiet = true;
} else if (args[i].equalsIgnoreCase("-d") || args[i].equalsIgnoreCase("--dir")) {
rootDirs.add(new File(args[i + 1]).getAbsoluteFile());
} else if (args[i].equalsIgnoreCase("--licence")) {
System.out.println(LICENCE + "\n");
} else if (args[i].startsWith("-X:")) {
int dot = args[i].indexOf('=');
if (dot > 0) {
String name = args[i].substring(0, dot);
String value = args[i].substring(dot + 1, args[i].length());
options.put(name, value);
}
}
}
if (rootDirs.isEmpty()) {
rootDirs.add(new File(".").getAbsoluteFile());
}
options.put("host", host);
options.put("port", ""+port);
options.put("quiet", String.valueOf(quiet));
StringBuilder sb = new StringBuilder();
for (File dir : rootDirs) {
if (sb.length() > 0) {
sb.append(":");
}
try {
sb.append(dir.getCanonicalPath());
} catch (IOException ignored) {}
}
options.put("home", sb.toString());
ServiceLoader<WebServerPluginInfo> serviceLoader = ServiceLoader.load(WebServerPluginInfo.class);
for (WebServerPluginInfo info : serviceLoader) {
String[] mimeTypes = info.getMimeTypes();
for (String mime : mimeTypes) {
String[] indexFiles = info.getIndexFilesForMimeType(mime);
if (!quiet) {
System.out.print("# Found plugin for Mime type: \"" + mime + "\"");
if (indexFiles != null) {
System.out.print(" (serving index files: ");
for (String indexFile : indexFiles) {
System.out.print(indexFile + " ");
}
}
System.out.println(").");
}
registerPluginForMimeType(indexFiles, mime, info.getWebServerPlugin(mime), options);
}
}
ServerRunner.executeInstance(new SimpleWebServer(host, port, rootDirs, quiet));
}
protected static void registerPluginForMimeType(String[] indexFiles, String mimeType, WebServerPlugin plugin, Map<String, String> commandLineOptions) {
if (mimeType == null || plugin == null) {
return;
}
if (indexFiles != null) {
for (String filename : indexFiles) {
int dot = filename.lastIndexOf('.');
if (dot >= 0) {
String extension = filename.substring(dot + 1).toLowerCase();
MIME_TYPES.put(extension, mimeType);
}
}
INDEX_FILE_NAMES.addAll(Arrays.asList(indexFiles));
}
mimeTypeHandlers.put(mimeType, plugin);
plugin.initialize(commandLineOptions);
}
private File getRootDir() {
return rootDirs.get(0);
}
private List<File> getRootDirs() {
return rootDirs;
}
private void addWwwRootDir(File wwwroot) {
rootDirs.add(wwwroot);
}
/**
* URL-encodes everything between "/"-characters. Encodes spaces as '%20' instead of '+'.
*/
private String encodeUri(String uri) {
String newUri = "";
StringTokenizer st = new StringTokenizer(uri, "/ ", true);
while (st.hasMoreTokens()) {
String tok = st.nextToken();
switch(tok) {
case "/":
newUri += "/";
break;
case " ":
newUri += "%20";
break;
default:
try {
newUri += URLEncoder.encode(tok, "UTF-8");
} catch (UnsupportedEncodingException ignored) {
Log.e(TAG, ignored.getMessage());
}
}
}
return newUri;
}
public Response serve(IHTTPSession session) {
Map<String, String> header = session.getHeaders();
Map<String, String> parms = session.getParms();
String uri = session.getUri();
if (!quiet) {
System.out.println(session.getMethod() + " '" + uri + "' ");
Iterator<String> e = header.keySet().iterator();
while (e.hasNext()) {
String value = e.next();
System.out.println(" HDR: '" + value + "' = '" + header.get(value) + "'");
}
e = parms.keySet().iterator();
while (e.hasNext()) {
String value = e.next();
System.out.println(" PRM: '" + value + "' = '" + parms.get(value) + "'");
}
}
for (File homeDir : getRootDirs()) {
// Make sure we won't die of an exception later
if (!homeDir.isDirectory()) {
return getInternalErrorResponse("given path is not a directory (" + homeDir + ").");
}
}
return respond(Collections.unmodifiableMap(header), session, uri);
}
private Response respond(Map<String, String> headers, IHTTPSession session, String uri) {
// Remove URL arguments
uri = uri.trim().replace(File.separatorChar, '/');
if (uri.indexOf('?') >= 0) {
uri = uri.substring(0, uri.indexOf('?'));
}
// Prohibit getting out of current directory
if (uri.startsWith("src/main") || uri.endsWith("src/main") || uri.contains("../")) {
return getForbiddenResponse("Won't serve ../ for security reasons.");
}
boolean canServeUri = false;
File homeDir = null;
List<File> roots = getRootDirs();
for (int i = 0; !canServeUri && i < roots.size(); i++) {
homeDir = roots.get(i);
canServeUri = canServeUri(uri, homeDir);
}
if (!canServeUri) {
return getNotFoundResponse();
}
// Browsers get confused without '/' after the directory, send a redirect.
File f = new File(homeDir, uri);
if (f.isDirectory() && !uri.endsWith("/")) {
uri += "/";
Response res = createResponse(Response.Status.REDIRECT, NanoHTTPD.MIME_HTML, "<html><body>Redirected: <a href=\"" +
uri + "\">" + uri + "</a></body></html>");
res.addHeader("Location", uri);
return res;
}
if (f.isDirectory()) {
// First look for index files (index.html, index.htm, etc) and if none found, list the directory if readable.
String indexFile = findIndexFileInDirectory(f);
if (indexFile == null) {
if (f.canRead()) {
// No index file, list the directory if it is readable
return createResponse(Response.Status.OK, NanoHTTPD.MIME_HTML, listDirectory(uri, f));
} else {
return getForbiddenResponse("No directory listing.");
}
} else {
return respond(headers, session, uri + indexFile);
}
}
String mimeTypeForFile = getMimeTypeForFile(uri);
WebServerPlugin plugin = mimeTypeHandlers.get(mimeTypeForFile);
Response response;
if (plugin != null) {
response = plugin.serveFile(uri, headers, session, f, mimeTypeForFile);
if (response != null && response instanceof InternalRewrite) {
InternalRewrite rewrite = (InternalRewrite) response;
return respond(rewrite.getHeaders(), session, rewrite.getUri());
}
} else {
response = serveFile(uri, headers, f, mimeTypeForFile);
}
return response != null ? response : getNotFoundResponse();
}
protected Response getNotFoundResponse() {
return createResponse(Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT,
"Error 404, file not found.");
}
protected Response getForbiddenResponse(String s) {
return createResponse(Response.Status.FORBIDDEN, NanoHTTPD.MIME_PLAINTEXT, "FORBIDDEN: "
+ s);
}
protected Response getInternalErrorResponse(String s) {
return createResponse(Response.Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT,
"INTERNAL ERRROR: " + s);
}
private boolean canServeUri(String uri, File homeDir) {
boolean canServeUri;
File f = new File(homeDir, uri);
canServeUri = f.exists();
if (!canServeUri) {
String mimeTypeForFile = getMimeTypeForFile(uri);
WebServerPlugin plugin = mimeTypeHandlers.get(mimeTypeForFile);
if (plugin != null) {
canServeUri = plugin.canServeUri(uri, homeDir);
}
}
return canServeUri;
}
/**
* Serves file from homeDir and its' subdirectories (only). Uses only URI, ignores all headers and HTTP parameters.
*/
Response serveFile(String uri, Map<String, String> header, File file, String mime) {
Response res;
try {
// Calculate etag
String etag = Integer.toHexString((file.getAbsolutePath() + file.lastModified() + "" + file.length()).hashCode());
// Support (simple) skipping:
long startFrom = 0;
long endAt = -1;
String range = header.get("range");
if (range != null) {
if (range.startsWith("bytes=")) {
range = range.substring("bytes=".length());
int minus = range.indexOf('-');
try {
if (minus > 0) {
startFrom = Long.parseLong(range.substring(0, minus));
endAt = Long.parseLong(range.substring(minus + 1));
}
} catch (NumberFormatException ignored) {
}
}
}
// Change return code and add Content-Range header when skipping is requested
long fileLen = file.length();
if (range != null && startFrom >= 0) {
if (startFrom >= fileLen) {
res = createResponse(Response.Status.RANGE_NOT_SATISFIABLE, NanoHTTPD.MIME_PLAINTEXT, "");
res.addHeader("Content-Range", "bytes 0-0/" + fileLen);
res.addHeader("ETag", etag);
} else {
if (endAt < 0) {
endAt = fileLen - 1;
}
long newLen = endAt - startFrom + 1;
if (newLen < 0) {
newLen = 0;
}
final long dataLen = newLen;
FileInputStream fis = new FileInputStream(file) {
@Override
public int available() throws IOException {
return (int) dataLen;
}
};
fis.skip(startFrom);
res = createResponse(Response.Status.PARTIAL_CONTENT, mime, fis);
res.addHeader("Content-Length", "" + dataLen);
res.addHeader("Content-Range", "bytes " + startFrom + "-" + endAt + "/" + fileLen);
res.addHeader("ETag", etag);
}
} else {
if (etag.equals(header.get("if-none-match")))
res = createResponse(Response.Status.NOT_MODIFIED, mime, "");
else {
res = createResponse(Response.Status.OK, mime, new FileInputStream(file));
res.addHeader("Content-Length", "" + fileLen);
res.addHeader("ETag", etag);
}
}
} catch (IOException ioe) {
res = getForbiddenResponse("Reading file failed.");
}
return res;
}
// Get MIME type from file name extension, if possible
private String getMimeTypeForFile(String uri) {
int dot = uri.lastIndexOf('.');
String mime = null;
if (dot >= 0) {
mime = MIME_TYPES.get(uri.substring(dot + 1).toLowerCase());
}
return mime == null ? MIME_DEFAULT_BINARY : mime;
}
// Announce that the file server accepts partial content requests
private Response createResponse(Response.Status status, String mimeType, InputStream message) {
Response res = new Response(status, mimeType, message);
res.addHeader("Accept-Ranges", "bytes");
return res;
}
// Announce that the file server accepts partial content requests
private Response createResponse(Response.Status status, String mimeType, String message) {
Response res = new Response(status, mimeType, message);
res.addHeader("Accept-Ranges", "bytes");
return res;
}
private String findIndexFileInDirectory(File directory) {
for (String fileName : INDEX_FILE_NAMES) {
File indexFile = new File(directory, fileName);
if (indexFile.exists()) {
return fileName;
}
}
return null;
}
protected String listDirectory(String uri, File f) {
String heading = "Directory " + uri;
StringBuilder msg = new StringBuilder("<html><head><title>" + heading + "</title><style><!--\n" +
"span.dirname { font-weight: bold; }\n" +
"span.filesize { font-size: 75%; }\n" +
"// -->\n" +
"</style>" +
"</head><body><h1>" + heading + "</h1>");
String up = null;
if (uri.length() > 1) {
String u = uri.substring(0, uri.length() - 1);
int slash = u.lastIndexOf('/');
if (slash >= 0 && slash < u.length()) {
up = uri.substring(0, slash + 1);
}
}
List<String> files = Arrays.asList(f.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return new File(dir, name).isFile();
}
}));
Collections.sort(files);
List<String> directories = Arrays.asList(f.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return new File(dir, name).isDirectory();
}
}));
Collections.sort(directories);
if (up != null || directories.size() + files.size() > 0) {
msg.append("<ul>");
if (up != null || directories.size() > 0) {
msg.append("<section class=\"directories\">");
if (up != null) {
msg.append("<li><a rel=\"directory\" href=\"").append(up).append("\"><span class=\"dirname\">..</span></a></b></li>");
}
for (String directory : directories) {
String dir = directory + "/";
msg.append("<li><a rel=\"directory\" href=\"").append(encodeUri(uri + dir)).append("\"><span class=\"dirname\">").append(dir).append("</span></a></b></li>");
}
msg.append("</section>");
}
if (files.size() > 0) {
msg.append("<section class=\"files\">");
for (String file : files) {
msg.append("<li><a href=\"").append(encodeUri(uri + file)).append("\"><span class=\"filename\">").append(file).append("</span></a>");
File curFile = new File(f, file);
long len = curFile.length();
msg.append(" <span class=\"filesize\">(");
if (len < 1024) {
msg.append(len).append(" bytes");
} else if (len < 1024 * 1024) {
msg.append(len / 1024).append(".").append(len % 1024 / 10 % 100).append(" KB");
} else {
msg.append(len / (1024 * 1024)).append(".").append(len % (1024 * 1024) / 10 % 100).append(" MB");
}
msg.append(")</span></li>");
}
msg.append("</section>");
}
msg.append("</ul>");
}
msg.append("</body></html>");
return msg.toString();
}
}
| |
package org.gwtbootstrap3.client.ui.constants;
/*
* #%L
* GwtBootstrap3
* %%
* Copyright (C) 2013 GwtBootstrap3
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import org.gwtbootstrap3.client.ui.base.helper.EnumHelper;
import com.google.gwt.dom.client.Style;
/**
* You can use the fontawesome-enum-helper.js to grab and enum names (located in the client/resource/css folder
*
* @author Sven Jacobs
* @author Joshua Godi
*/
public enum IconType implements Type, Style.HasCssName {
_500PX("fa-500px"),
ADJUST("fa-adjust"),
ADN("fa-adn"),
ALIGN_CENTER("fa-align-center"),
ALIGN_JUSTIFY("fa-align-justify"),
ALIGN_LEFT("fa-align-left"),
ALIGN_RIGHT("fa-align-right"),
AMAZON("fa-amazon"),
AMBULANCE("fa-ambulance"),
ANCHOR("fa-anchor"),
ANDROID("fa-android"),
ANGELLIST("fa-angellist"),
ANGLE_DOUBLE_DOWN("fa-angle-double-down"),
ANGLE_DOUBLE_LEFT("fa-angle-double-left"),
ANGLE_DOUBLE_RIGHT("fa-angle-double-right"),
ANGLE_DOUBLE_UP("fa-angle-double-up"),
ANGLE_DOWN("fa-angle-down"),
ANGLE_LEFT("fa-angle-left"),
ANGLE_RIGHT("fa-angle-right"),
ANGLE_UP("fa-angle-up"),
APPLE("fa-apple"),
ARCHIVE("fa-archive"),
AREA_CHART("fa-area-chart"),
ARROWS("fa-arrows"),
ARROWS_ALT("fa-arrows-alt"),
ARROWS_H("fa-arrows-h"),
ARROWS_V("fa-arrows-v"),
ARROW_CIRCLE_DOWN("fa-arrow-circle-down"),
ARROW_CIRCLE_LEFT("fa-arrow-circle-left"),
ARROW_CIRCLE_O_DOWN("fa-arrow-circle-o-down"),
ARROW_CIRCLE_O_LEFT("fa-arrow-circle-o-left"),
ARROW_CIRCLE_O_RIGHT("fa-arrow-circle-o-right"),
ARROW_CIRCLE_O_UP("fa-arrow-circle-o-up"),
ARROW_CIRCLE_RIGHT("fa-arrow-circle-right"),
ARROW_CIRCLE_UP("fa-arrow-circle-up"),
ARROW_DOWN("fa-arrow-down"),
ARROW_LEFT("fa-arrow-left"),
ARROW_RIGHT("fa-arrow-right"),
ARROW_UP("fa-arrow-up"),
ASTERISK("fa-asterisk"),
AT("fa-at"),
AUTOMOBILE("fa-automobile"),
BACKWARD("fa-backward"),
BALANCE_SCALE("fa-balance-scale"),
BAN("fa-ban"),
BANK("fa-bank"),
BARCODE("fa-barcode"),
BARS("fa-bars"),
BAR_CHART("fa-bar-chart"),
BAR_CHART_O("fa-bar-chart-o"),
BATTERY_0("fa-battery-0"),
BATTERY_1("fa-battery-1"),
BATTERY_2("fa-battery-2"),
BATTERY_3("fa-battery-3"),
BATTERY_4("fa-battery-4"),
BATTERY_EMPTY("fa-battery-empty"),
BATTERY_FULL("fa-battery-full"),
BATTERY_HALF("fa-battery-half"),
BATTERY_QUARTER("fa-battery-quarter"),
BATTERY_THREE_QUARTERS("fa-battery-three-quarters"),
BED("fa-bed"),
BEER("fa-beer"),
BEHANCE("fa-behance"),
BEHANCE_SQUARE("fa-behance-square"),
BELL("fa-bell"),
BELL_O("fa-bell-o"),
BELL_SLASH("fa-bell-slash"),
BELL_SLASH_O("fa-bell-slash-o"),
BICYCLE("fa-bicycle"),
BINOCULARS("fa-binoculars"),
BIRTHDAY_CAKE("fa-birthday-cake"),
BITBUCKET("fa-bitbucket"),
BITBUCKET_SQUARE("fa-bitbucket-square"),
BITCOIN("fa-bitcoin"),
BLACK_TIE("fa-black-tie"),
BOLD("fa-bold"),
BOLT("fa-bolt"),
BOMB("fa-bomb"),
BOOK("fa-book"),
BOOKMARK("fa-bookmark"),
BOOKMARK_O("fa-bookmark-o"),
BRIEFCASE("fa-briefcase"),
BTC("fa-btc"),
BUG("fa-bug"),
BUILDING("fa-building"),
BUILDING_O("fa-building-o"),
BULLHORN("fa-bullhorn"),
BULLSEYE("fa-bullseye"),
BUS("fa-bus"),
BUYSELLADS("fa-buysellads"),
CAB("fa-cab"),
CALCULATOR("fa-calculator"),
CALENDAR("fa-calendar"),
CALENDAR_CHECK_O("fa-calendar-check-o"),
CALENDAR_MINUS_O("fa-calendar-minus-o"),
CALENDAR_O("fa-calendar-o"),
CALENDAR_PLUS_O("fa-calendar-plus-o"),
CALENDAR_TIMES_O("fa-calendar-times-o"),
CAMERA("fa-camera"),
CAMERA_RETRO("fa-camera-retro"),
CAR("fa-car"),
CARET_DOWN("fa-caret-down"),
CARET_LEFT("fa-caret-left"),
CARET_RIGHT("fa-caret-right"),
CARET_SQUARE_O_DOWN("fa-caret-square-o-down"),
CARET_SQUARE_O_LEFT("fa-caret-square-o-left"),
CARET_SQUARE_O_RIGHT("fa-caret-square-o-right"),
CARET_SQUARE_O_UP("fa-caret-square-o-up"),
CARET_UP("fa-caret-up"),
CART_ARROW_DOWN("fa-cart-arrow-down"),
CART_PLUS("fa-cart-plus"),
CC("fa-cc"),
CC_AMEX("fa-cc-amex"),
CC_DINERS_CLUB("fa-cc-diners-club"),
CC_DISCOVER("fa-cc-discover"),
CC_JCB("fa-cc-jcb"),
CC_MASTERCARD("fa-cc-mastercard"),
CC_PAYPAL("fa-cc-paypal"),
CC_STRIPE("fa-cc-stripe"),
CC_VISA("fa-cc-visa"),
CERTIFICATE("fa-certificate"),
CHAIN("fa-chain"),
CHAIN_BROKEN("fa-chain-broken"),
CHECK("fa-check"),
CHECK_CIRCLE("fa-check-circle"),
CHECK_CIRCLE_O("fa-check-circle-o"),
CHECK_SQUARE("fa-check-square"),
CHECK_SQUARE_O("fa-check-square-o"),
CHEVRON_CIRCLE_DOWN("fa-chevron-circle-down"),
CHEVRON_CIRCLE_LEFT("fa-chevron-circle-left"),
CHEVRON_CIRCLE_RIGHT("fa-chevron-circle-right"),
CHEVRON_CIRCLE_UP("fa-chevron-circle-up"),
CHEVRON_DOWN("fa-chevron-down"),
CHEVRON_LEFT("fa-chevron-left"),
CHEVRON_RIGHT("fa-chevron-right"),
CHEVRON_UP("fa-chevron-up"),
CHILD("fa-child"),
CHROME("fa-chrome"),
CIRCLE("fa-circle"),
CIRCLE_O("fa-circle-o"),
CIRCLE_O_NOTCH("fa-circle-o-notch"),
CIRCLE_THIN("fa-circle-thin"),
CLIPBOARD("fa-clipboard"),
CLOCK_O("fa-clock-o"),
CLONE("fa-clone"),
CLOSE("fa-close"),
CLOUD("fa-cloud"),
CLOUD_DOWNLOAD("fa-cloud-download"),
CLOUD_UPLOAD("fa-cloud-upload"),
CNY("fa-cny"),
CODE("fa-code"),
CODEPEN("fa-codepen"),
CODE_FORK("fa-code-fork"),
COFFEE("fa-coffee"),
COG("fa-cog"),
COGS("fa-cogs"),
COLUMNS("fa-columns"),
COMMENT("fa-comment"),
COMMENTING("fa-commenting"),
COMMENTING_O("fa-commenting-o"),
COMMENTS("fa-comments"),
COMMENTS_O("fa-comments-o"),
COMMENT_O("fa-comment-o"),
COMPASS("fa-compass"),
COMPRESS("fa-compress"),
CONNECTDEVELOP("fa-connectdevelop"),
CONTAO("fa-contao"),
COPY("fa-copy"),
COPYRIGHT("fa-copyright"),
CREATIVE_COMMONS("fa-creative-commons"),
CREDIT_CARD("fa-credit-card"),
CROP("fa-crop"),
CROSSHAIRS("fa-crosshairs"),
CSS3("fa-css3"),
CUBE("fa-cube"),
CUBES("fa-cubes"),
CUT("fa-cut"),
CUTLERY("fa-cutlery"),
DASHBOARD("fa-dashboard"),
DASHCUBE("fa-dashcube"),
DATABASE("fa-database"),
DEDENT("fa-dedent"),
DELICIOUS("fa-delicious"),
DESKTOP("fa-desktop"),
DEVIANTART("fa-deviantart"),
DIAMOND("fa-diamond"),
DIGG("fa-digg"),
DOLLAR("fa-dollar"),
DOT_CIRCLE_O("fa-dot-circle-o"),
DOWNLOAD("fa-download"),
DRIBBBLE("fa-dribbble"),
DROPBOX("fa-dropbox"),
DRUPAL("fa-drupal"),
EDIT("fa-edit"),
EJECT("fa-eject"),
ELLIPSIS_H("fa-ellipsis-h"),
ELLIPSIS_V("fa-ellipsis-v"),
EMPIRE("fa-empire"),
ENVELOPE("fa-envelope"),
ENVELOPE_O("fa-envelope-o"),
ENVELOPE_SQUARE("fa-envelope-square"),
ERASER("fa-eraser"),
EUR("fa-eur"),
EURO("fa-euro"),
EXCHANGE("fa-exchange"),
EXCLAMATION("fa-exclamation"),
EXCLAMATION_CIRCLE("fa-exclamation-circle"),
EXCLAMATION_TRIANGLE("fa-exclamation-triangle"),
EXPAND("fa-expand"),
EXPEDITEDSSL("fa-expeditedssl"),
EXTERNAL_LINK("fa-external-link"),
EXTERNAL_LINK_SQUARE("fa-external-link-square"),
EYE("fa-eye"),
EYEDROPPER("fa-eyedropper"),
EYE_SLASH("fa-eye-slash"),
FACEBOOK("fa-facebook"),
FACEBOOK_F("fa-facebook-f"),
FACEBOOK_OFFICIAL("fa-facebook-official"),
FACEBOOK_SQUARE("fa-facebook-square"),
FAST_BACKWARD("fa-fast-backward"),
FAST_FORWARD("fa-fast-forward"),
FAX("fa-fax"),
FEED("fa-feed"),
FEMALE("fa-female"),
FIGHTER_JET("fa-fighter-jet"),
FILE("fa-file"),
FILES_O("fa-files-o"),
FILE_ARCHIVE_O("fa-file-archive-o"),
FILE_AUDIO_O("fa-file-audio-o"),
FILE_CODE_O("fa-file-code-o"),
FILE_EXCEL_O("fa-file-excel-o"),
FILE_IMAGE_O("fa-file-image-o"),
FILE_MOVIE_O("fa-file-movie-o"),
FILE_O("fa-file-o"),
FILE_PDF_O("fa-file-pdf-o"),
FILE_PHOTO_O("fa-file-photo-o"),
FILE_PICTURE_O("fa-file-picture-o"),
FILE_POWERPOINT_O("fa-file-powerpoint-o"),
FILE_SOUND_O("fa-file-sound-o"),
FILE_TEXT("fa-file-text"),
FILE_TEXT_O("fa-file-text-o"),
FILE_VIDEO_O("fa-file-video-o"),
FILE_WORD_O("fa-file-word-o"),
FILE_ZIP_O("fa-file-zip-o"),
FILM("fa-film"),
FILTER("fa-filter"),
FIRE("fa-fire"),
FIREFOX("fa-firefox"),
FIRE_EXTINGUISHER("fa-fire-extinguisher"),
FLAG("fa-flag"),
FLAG_CHECKERED("fa-flag-checkered"),
FLAG_O("fa-flag-o"),
FLASH("fa-flash"),
FLASK("fa-flask"),
FLICKR("fa-flickr"),
FLOPPY_O("fa-floppy-o"),
FOLDER("fa-folder"),
FOLDER_O("fa-folder-o"),
FOLDER_OPEN("fa-folder-open"),
FOLDER_OPEN_O("fa-folder-open-o"),
FONT("fa-font"),
FONTICONS("fa-fonticons"),
FORUMBEE("fa-forumbee"),
FORWARD("fa-forward"),
FOURSQUARE("fa-foursquare"),
FROWN_O("fa-frown-o"),
FUTBOL_O("fa-futbol-o"),
GAMEPAD("fa-gamepad"),
GAVEL("fa-gavel"),
GBP("fa-gbp"),
GE("fa-ge"),
GEAR("fa-gear"),
GEARS("fa-gears"),
GENDERLESS("fa-genderless"),
GET_POCKET("fa-get-pocket"),
GG("fa-gg"),
GG_CIRCLE("fa-gg-circle"),
GIFT("fa-gift"),
GIT("fa-git"),
GITHUB("fa-github"),
GITHUB_ALT("fa-github-alt"),
GITHUB_SQUARE("fa-github-square"),
GITTIP("fa-gittip"),
GIT_SQUARE("fa-git-square"),
GLASS("fa-glass"),
GLOBE("fa-globe"),
GOOGLE("fa-google"),
GOOGLE_PLUS("fa-google-plus"),
GOOGLE_PLUS_SQUARE("fa-google-plus-square"),
GOOGLE_WALLET("fa-google-wallet"),
GRADUATION_CAP("fa-graduation-cap"),
GRATIPAY("fa-gratipay"),
GROUP("fa-group"),
HACKER_NEWS("fa-hacker-news"),
HAND_GRAB_O("fa-hand-grab-o"),
HAND_LIZARD_O("fa-hand-lizard-o"),
HAND_O_DOWN("fa-hand-o-down"),
HAND_O_LEFT("fa-hand-o-left"),
HAND_O_RIGHT("fa-hand-o-right"),
HAND_O_UP("fa-hand-o-up"),
HAND_PAPER_O("fa-hand-paper-o"),
HAND_PEACE_O("fa-hand-peace-o"),
HAND_POINTER_O("fa-hand-pointer-o"),
HAND_ROCK_O("fa-hand-rock-o"),
HAND_SCISSORS_O("fa-hand-scissors-o"),
HAND_SPOCK_O("fa-hand-spock-o"),
HAND_STOP_O("fa-hand-stop-o"),
HDD_O("fa-hdd-o"),
HEADER("fa-header"),
HEADPHONES("fa-headphones"),
HEART("fa-heart"),
HEARTBEAT("fa-heartbeat"),
HEART_O("fa-heart-o"),
HISTORY("fa-history"),
HOME("fa-home"),
HOSPITAL_O("fa-hospital-o"),
HOTEL("fa-hotel"),
HOURGLASS("fa-hourglass"),
HOURGLASS_1("fa-hourglass-1"),
HOURGLASS_2("fa-hourglass-2"),
HOURGLASS_3("fa-hourglass-3"),
HOURGLASS_END("fa-hourglass-end"),
HOURGLASS_HALF("fa-hourglass-half"),
HOURGLASS_O("fa-hourglass-o"),
HOURGLASS_START("fa-hourglass-start"),
HOUZZ("fa-houzz"),
HTML5("fa-html5"),
H_SQUARE("fa-h-square"),
ILS("fa-ils"),
IMAGE("fa-image"),
INBOX("fa-inbox"),
INDENT("fa-indent"),
INDUSTRY("fa-industry"),
INFO("fa-info"),
INFO_CIRCLE("fa-info-circle"),
INR("fa-inr"),
INSTAGRAM("fa-instagram"),
INSTITUTION("fa-institution"),
INTERNET_EXPLORER("fa-internet-explorer"),
INTERSEX("fa-intersex"),
IOXHOST("fa-ioxhost"),
ITALIC("fa-italic"),
I_CURSOR("fa-i-cursor"),
JOOMLA("fa-joomla"),
JPY("fa-jpy"),
JSFIDDLE("fa-jsfiddle"),
KEY("fa-key"),
KEYBOARD_O("fa-keyboard-o"),
KRW("fa-krw"),
LANGUAGE("fa-language"),
LAPTOP("fa-laptop"),
LASTFM("fa-lastfm"),
LASTFM_SQUARE("fa-lastfm-square"),
LEAF("fa-leaf"),
LEANPUB("fa-leanpub"),
LEGAL("fa-legal"),
LEMON_O("fa-lemon-o"),
LEVEL_DOWN("fa-level-down"),
LEVEL_UP("fa-level-up"),
LIFE_BOUY("fa-life-bouy"),
LIFE_BUOY("fa-life-buoy"),
LIFE_RING("fa-life-ring"),
LIFE_SAVER("fa-life-saver"),
LIGHTBULB_O("fa-lightbulb-o"),
LINE_CHART("fa-line-chart"),
LINK("fa-link"),
LINKEDIN("fa-linkedin"),
LINKEDIN_SQUARE("fa-linkedin-square"),
LINUX("fa-linux"),
LIST("fa-list"),
LIST_ALT("fa-list-alt"),
LIST_OL("fa-list-ol"),
LIST_UL("fa-list-ul"),
LOCATION_ARROW("fa-location-arrow"),
LOCK("fa-lock"),
LONG_ARROW_DOWN("fa-long-arrow-down"),
LONG_ARROW_LEFT("fa-long-arrow-left"),
LONG_ARROW_RIGHT("fa-long-arrow-right"),
LONG_ARROW_UP("fa-long-arrow-up"),
MAGIC("fa-magic"),
MAGNET("fa-magnet"),
MAIL_FORWARD("fa-mail-forward"),
MAIL_REPLY("fa-mail-reply"),
MAIL_REPLY_ALL("fa-mail-reply-all"),
MALE("fa-male"),
MAP("fa-map"),
MAP_MARKER("fa-map-marker"),
MAP_O("fa-map-o"),
MAP_PIN("fa-map-pin"),
MAP_SIGNS("fa-map-signs"),
MARS("fa-mars"),
MARS_DOUBLE("fa-mars-double"),
MARS_STROKE("fa-mars-stroke"),
MARS_STROKE_H("fa-mars-stroke-h"),
MARS_STROKE_V("fa-mars-stroke-v"),
MAXCDN("fa-maxcdn"),
MEANPATH("fa-meanpath"),
MEDIUM("fa-medium"),
MEDKIT("fa-medkit"),
MEH_O("fa-meh-o"),
MERCURY("fa-mercury"),
MICROPHONE("fa-microphone"),
MICROPHONE_SLASH("fa-microphone-slash"),
MINUS("fa-minus"),
MINUS_CIRCLE("fa-minus-circle"),
MINUS_SQUARE("fa-minus-square"),
MINUS_SQUARE_O("fa-minus-square-o"),
MOBILE("fa-mobile"),
MOBILE_PHONE("fa-mobile-phone"),
MONEY("fa-money"),
MOON_O("fa-moon-o"),
MORTAR_BOARD("fa-mortar-board"),
MOTORCYCLE("fa-motorcycle"),
MOUSE_POINTER("fa-mouse-pointer"),
MUSIC("fa-music"),
NAVICON("fa-navicon"),
NEUTER("fa-neuter"),
NEWSPAPER_O("fa-newspaper-o"),
OBJECT_GROUP("fa-object-group"),
OBJECT_UNGROUP("fa-object-ungroup"),
ODNOKLASSNIKI("fa-odnoklassniki"),
ODNOKLASSNIKI_SQUARE("fa-odnoklassniki-square"),
OPENCART("fa-opencart"),
OPENID("fa-openid"),
OPERA("fa-opera"),
OPTIN_MONSTER("fa-optin-monster"),
OUTDENT("fa-outdent"),
PAGELINES("fa-pagelines"),
PAINT_BRUSH("fa-paint-brush"),
PAPERCLIP("fa-paperclip"),
PAPER_PLANE("fa-paper-plane"),
PAPER_PLANE_O("fa-paper-plane-o"),
PARAGRAPH("fa-paragraph"),
PASTE("fa-paste"),
PAUSE("fa-pause"),
PAW("fa-paw"),
PAYPAL("fa-paypal"),
PENCIL("fa-pencil"),
PENCIL_SQUARE("fa-pencil-square"),
PENCIL_SQUARE_O("fa-pencil-square-o"),
PHONE("fa-phone"),
PHONE_SQUARE("fa-phone-square"),
PHOTO("fa-photo"),
PICTURE_O("fa-picture-o"),
PIED_PIPER("fa-pied-piper"),
PIED_PIPER_ALT("fa-pied-piper-alt"),
PIE_CHART("fa-pie-chart"),
PINTEREST("fa-pinterest"),
PINTEREST_P("fa-pinterest-p"),
PINTEREST_SQUARE("fa-pinterest-square"),
PLANE("fa-plane"),
PLAY("fa-play"),
PLAY_CIRCLE("fa-play-circle"),
PLAY_CIRCLE_O("fa-play-circle-o"),
PLUG("fa-plug"),
PLUS("fa-plus"),
PLUS_CIRCLE("fa-plus-circle"),
PLUS_SQUARE("fa-plus-square"),
PLUS_SQUARE_O("fa-plus-square-o"),
POWER_OFF("fa-power-off"),
PRINT("fa-print"),
PUZZLE_PIECE("fa-puzzle-piece"),
QQ("fa-qq"),
QRCODE("fa-qrcode"),
QUESTION("fa-question"),
QUESTION_CIRCLE("fa-question-circle"),
QUOTE_LEFT("fa-quote-left"),
QUOTE_RIGHT("fa-quote-right"),
RA("fa-ra"),
RANDOM("fa-random"),
REBEL("fa-rebel"),
RECYCLE("fa-recycle"),
REDDIT("fa-reddit"),
REDDIT_SQUARE("fa-reddit-square"),
REFRESH("fa-refresh"),
REGISTERED("fa-registered"),
REMOVE("fa-remove"),
RENREN("fa-renren"),
REORDER("fa-reorder"),
REPEAT("fa-repeat"),
REPLY("fa-reply"),
REPLY_ALL("fa-reply-all"),
RETWEET("fa-retweet"),
RMB("fa-rmb"),
ROAD("fa-road"),
ROCKET("fa-rocket"),
ROTATE_LEFT("fa-rotate-left"),
ROTATE_RIGHT("fa-rotate-right"),
ROUBLE("fa-rouble"),
RSS("fa-rss"),
RSS_SQUARE("fa-rss-square"),
RUB("fa-rub"),
RUBLE("fa-ruble"),
RUPEE("fa-rupee"),
SAFARI("fa-safari"),
SAVE("fa-save"),
SCISSORS("fa-scissors"),
SEARCH("fa-search"),
SEARCH_MINUS("fa-search-minus"),
SEARCH_PLUS("fa-search-plus"),
SELLSY("fa-sellsy"),
SEND("fa-send"),
SEND_O("fa-send-o"),
SERVER("fa-server"),
SHARE("fa-share"),
SHARE_ALT("fa-share-alt"),
SHARE_ALT_SQUARE("fa-share-alt-square"),
SHARE_SQUARE("fa-share-square"),
SHARE_SQUARE_O("fa-share-square-o"),
SHEKEL("fa-shekel"),
SHEQEL("fa-sheqel"),
SHIELD("fa-shield"),
SHIP("fa-ship"),
SHIRTSINBULK("fa-shirtsinbulk"),
SHOPPING_CART("fa-shopping-cart"),
SIGNAL("fa-signal"),
SIGN_IN("fa-sign-in"),
SIGN_OUT("fa-sign-out"),
SIMPLYBUILT("fa-simplybuilt"),
SITEMAP("fa-sitemap"),
SKYATLAS("fa-skyatlas"),
SKYPE("fa-skype"),
SLACK("fa-slack"),
SLIDERS("fa-sliders"),
SLIDESHARE("fa-slideshare"),
SMILE_O("fa-smile-o"),
SOCCER_BALL_O("fa-soccer-ball-o"),
SORT("fa-sort"),
SORT_ALPHA_ASC("fa-sort-alpha-asc"),
SORT_ALPHA_DESC("fa-sort-alpha-desc"),
SORT_AMOUNT_ASC("fa-sort-amount-asc"),
SORT_AMOUNT_DESC("fa-sort-amount-desc"),
SORT_ASC("fa-sort-asc"),
SORT_DESC("fa-sort-desc"),
SORT_DOWN("fa-sort-down"),
SORT_NUMERIC_ASC("fa-sort-numeric-asc"),
SORT_NUMERIC_DESC("fa-sort-numeric-desc"),
SORT_UP("fa-sort-up"),
SOUNDCLOUD("fa-soundcloud"),
SPACE_SHUTTLE("fa-space-shuttle"),
SPINNER("fa-spinner"),
SPOON("fa-spoon"),
SPOTIFY("fa-spotify"),
SQUARE("fa-square"),
SQUARE_O("fa-square-o"),
STACK_EXCHANGE("fa-stack-exchange"),
STACK_OVERFLOW("fa-stack-overflow"),
STAR("fa-star"),
STAR_HALF("fa-star-half"),
STAR_HALF_EMPTY("fa-star-half-empty"),
STAR_HALF_FULL("fa-star-half-full"),
STAR_HALF_O("fa-star-half-o"),
STAR_O("fa-star-o"),
STEAM("fa-steam"),
STEAM_SQUARE("fa-steam-square"),
STEP_BACKWARD("fa-step-backward"),
STEP_FORWARD("fa-step-forward"),
STETHOSCOPE("fa-stethoscope"),
STICKY_NOTE("fa-sticky-note"),
STICKY_NOTE_O("fa-sticky-note-o"),
STOP("fa-stop"),
STREET_VIEW("fa-street-view"),
STRIKETHROUGH("fa-strikethrough"),
STUMBLEUPON("fa-stumbleupon"),
STUMBLEUPON_CIRCLE("fa-stumbleupon-circle"),
SUBSCRIPT("fa-subscript"),
SUBWAY("fa-subway"),
SUITCASE("fa-suitcase"),
SUN_O("fa-sun-o"),
SUPERSCRIPT("fa-superscript"),
SUPPORT("fa-support"),
TABLE("fa-table"),
TABLET("fa-tablet"),
TACHOMETER("fa-tachometer"),
TAG("fa-tag"),
TAGS("fa-tags"),
TASKS("fa-tasks"),
TAXI("fa-taxi"),
TELEVISION("fa-television"),
TENCENT_WEIBO("fa-tencent-weibo"),
TERMINAL("fa-terminal"),
TEXT_HEIGHT("fa-text-height"),
TEXT_WIDTH("fa-text-width"),
TH("fa-th"),
THUMBS_DOWN("fa-thumbs-down"),
THUMBS_O_DOWN("fa-thumbs-o-down"),
THUMBS_O_UP("fa-thumbs-o-up"),
THUMBS_UP("fa-thumbs-up"),
THUMB_TACK("fa-thumb-tack"),
TH_LARGE("fa-th-large"),
TH_LIST("fa-th-list"),
TICKET("fa-ticket"),
TIMES("fa-times"),
TIMES_CIRCLE("fa-times-circle"),
TIMES_CIRCLE_O("fa-times-circle-o"),
TINT("fa-tint"),
TOGGLE_DOWN("fa-toggle-down"),
TOGGLE_LEFT("fa-toggle-left"),
TOGGLE_OFF("fa-toggle-off"),
TOGGLE_ON("fa-toggle-on"),
TOGGLE_RIGHT("fa-toggle-right"),
TOGGLE_UP("fa-toggle-up"),
TRADEMARK("fa-trademark"),
TRAIN("fa-train"),
TRANSGENDER("fa-transgender"),
TRANSGENDER_ALT("fa-transgender-alt"),
TRASH("fa-trash"),
TRASH_O("fa-trash-o"),
TREE("fa-tree"),
TRELLO("fa-trello"),
TRIPADVISOR("fa-tripadvisor"),
TROPHY("fa-trophy"),
TRUCK("fa-truck"),
TRY("fa-try"),
TTY("fa-tty"),
TUMBLR("fa-tumblr"),
TUMBLR_SQUARE("fa-tumblr-square"),
TURKISH_LIRA("fa-turkish-lira"),
TV("fa-tv"),
TWITCH("fa-twitch"),
TWITTER("fa-twitter"),
TWITTER_SQUARE("fa-twitter-square"),
UMBRELLA("fa-umbrella"),
UNDERLINE("fa-underline"),
UNDO("fa-undo"),
UNIVERSITY("fa-university"),
UNLINK("fa-unlink"),
UNLOCK("fa-unlock"),
UNLOCK_ALT("fa-unlock-alt"),
UNSORTED("fa-unsorted"),
UPLOAD("fa-upload"),
USD("fa-usd"),
USER("fa-user"),
USERS("fa-users"),
USER_MD("fa-user-md"),
USER_PLUS("fa-user-plus"),
USER_SECRET("fa-user-secret"),
USER_TIMES("fa-user-times"),
VENUS("fa-venus"),
VENUS_DOUBLE("fa-venus-double"),
VENUS_MARS("fa-venus-mars"),
VIACOIN("fa-viacoin"),
VIDEO_CAMERA("fa-video-camera"),
VIMEO("fa-vimeo"),
VIMEO_SQUARE("fa-vimeo-square"),
VINE("fa-vine"),
VK("fa-vk"),
VOLUME_DOWN("fa-volume-down"),
VOLUME_OFF("fa-volume-off"),
VOLUME_UP("fa-volume-up"),
WARNING("fa-warning"),
WECHAT("fa-wechat"),
WEIBO("fa-weibo"),
WEIXIN("fa-weixin"),
WHATSAPP("fa-whatsapp"),
WHEELCHAIR("fa-wheelchair"),
WIFI("fa-wifi"),
WIKIPEDIA_W("fa-wikipedia-w"),
WINDOWS("fa-windows"),
WON("fa-won"),
WORDPRESS("fa-wordpress"),
WRENCH("fa-wrench"),
XING("fa-xing"),
XING_SQUARE("fa-xing-square"),
YAHOO("fa-yahoo"),
YC("fa-yc"),
YC_SQUARE("fa-yc-square"),
YELP("fa-yelp"),
YEN("fa-yen"),
YOUTUBE("fa-youtube"),
YOUTUBE_PLAY("fa-youtube-play"),
YOUTUBE_SQUARE("fa-youtube-square"),
Y_COMBINATOR("fa-y-combinator"),
Y_COMBINATOR_SQUARE("fa-y-combinator-square"),
;
private final String cssClass;
private IconType(final String cssClass) {
this.cssClass = cssClass;
}
@Override
public String getCssName() {
return cssClass;
}
public static IconType fromStyleName(final String styleName) {
return EnumHelper.fromStyleName(styleName, IconType.class, null);
}
}
| |
package de.kuei.metafora.server.planningtool.util;
import java.util.HashMap;
import java.util.Vector;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import de.kuei.metafora.server.planningtool.StartupServlet;
import de.kuei.metafora.server.planningtool.mysql.MysqlConnector;
import de.kuei.metafora.server.planningtool.mysql.MysqlInitConnector;
import de.kuei.metafora.server.planningtool.mysql.ServerDescription;
import de.kuei.metafora.server.planningtool.xml.Classification;
import de.kuei.metafora.server.planningtool.xml.CommonFormatCreator;
import de.kuei.metafora.server.planningtool.xml.Role;
import de.kuei.metafora.server.planningtool.xml.XMLException;
import de.kuei.metafora.server.planningtool.xml.XMLUtils;
public class NodeTypeManager {
private static NodeTypeManager instance = null;
public static NodeTypeManager getInstance() {
if (instance == null) {
instance = new NodeTypeManager();
}
return instance;
}
private String urlprefix = "http://static.metafora-project.info";
private Vector<String> languages;
private NodeTypeManager() {
languages = MysqlConnector.getInstance().getNodeLanguages();
urlprefix = StartupServlet.apache;
}
public String[] getNodeTypes(String shortlangname, Vector<String> users,
String token, String groupId, String challengeName,
String challengeId) {
if (languages.isEmpty() || !languages.contains(shortlangname)) {
return new String[0];
}
HashMap<String, Vector<String>> template = null;
try {
int cid = Integer.parseInt(challengeId);
String tpl = MysqlConnector.getInstance().getChallengeTemplate(cid);
if (tpl != null) {
TemplateParser parser = new TemplateParser();
parser.parseTemplate(tpl);
template = parser.getTemplate();
}
} catch (Exception e) {
System.err.println("NodeTypeManager: " + e.getMessage());
}
Vector<String[]> icons = MysqlConnector.getInstance()
.getNodeTypesForLanguage(shortlangname);
if (template != null) {
icons = filterNodes(icons, template);
}
String[] xmldescs = new String[icons.size()];
for (int i = 0; i < icons.size(); i++) {
String[] icon = icons.get(i);
if (!icon[0].startsWith("http:")) {
icon[0] = urlprefix + icon[0];
}
if (icon[1] != null && icon[1].startsWith("<")) {
int pos = icon[1].indexOf('>', 1);
if (pos > 0) {
String server = icon[1].substring(1, pos);
Vector<ServerDescription> servers = MysqlInitConnector
.getInstance().getServer(server);
if (servers.size() > 0) {
ServerDescription serverdesc = servers.firstElement();
icon[1] = serverdesc.getServer()
+ icon[1].substring(pos + 1, icon[1].length());
System.err.println("Tool: " + icon[1]);
}
}
}
xmldescs[i] = getXmlForUrl(icon[0], icon[1], icon[2], icon[3], i,
icon[4], icon[5], icon[6], users, token, groupId,
challengeName, challengeId);
}
return xmldescs;
}
private Vector<String[]> filterNodes(Vector<String[]> icons,
HashMap<String, Vector<String>> template) {
Vector<String> categoryOrder = template.get("categoryorder");
HashMap<String, HashMap<String, String[]>> cards = new HashMap<String, HashMap<String, String[]>>();
for (String[] icon : icons) {
HashMap<String, String[]> category = null;
if (cards.containsKey(icon[5])) {
category = cards.get(icon[5]);
} else {
category = new HashMap<String, String[]>();
cards.put(icon[5], category);
}
category.put(icon[6], icon);
}
Vector<String[]> filteredIcons = new Vector<String[]>();
for (String categoryId : categoryOrder) {
Vector<String> category = template.get(categoryId);
for (String nodeId : category) {
HashMap<String, String[]> cat = cards.get(categoryId);
if (cat != null) {
String[] card = cat.get(nodeId);
if (card != null) {
filteredIcons.add(card);
}
} else {
System.err.println("NodeTypeManager: filterNodes: "
+ categoryId + " not found!");
}
}
}
return filteredIcons;
}
private String getXmlForUrl(String imageUrl, String toolUrl,
String nameStr, String categorieStr, int index, String scalefactor,
String cateogryId, String iconid, Vector<String> users,
String token, String groupId, String challengeName,
String challengeId) {
try {
CommonFormatCreator creator = null;
creator = new CommonFormatCreator(System.currentTimeMillis(),
Classification.create, "CREATE_NODE", StartupServlet.logged);
creator.addContentProperty("SENDING_TOOL",
StartupServlet.sending_tool);
for (String user : users) {
creator.addUser(user, token, Role.originator);
}
Document content = XMLUtils.createDocument();
Element obj = content.createElement("object");
content.appendChild(obj);
Element node = content.createElement("node");
node.setAttribute("id", "palette_node_" + index);
obj.appendChild(node);
Element graphics = content.createElement("graphics");
node.appendChild(graphics);
Element scale = content.createElement("scalefactor");
scale.setAttribute("value", scalefactor);
graphics.appendChild(scale);
Element bordercolor = content.createElement("bordercolor");
bordercolor.setAttribute("value", "#AAAAAA");
graphics.appendChild(bordercolor);
Element position = content.createElement("position");
position.setAttribute("x", "100");
position.setAttribute("y", "100");
graphics.appendChild(position);
Element text = content.createElement("text");
text.setAttribute("value", "");
node.appendChild(text);
Element properties = content.createElement("properties");
node.appendChild(properties);
Element pictureurl = content.createElement("pictureurl");
pictureurl.setAttribute("value", imageUrl);
properties.appendChild(pictureurl);
Element tool = content.createElement("tool");
tool.setAttribute("value", toolUrl);
properties.appendChild(tool);
Element categorie = content.createElement("categorie");
categorie.setAttribute("value", categorieStr);
properties.appendChild(categorie);
Element name = content.createElement("name");
name.setAttribute("value", nameStr);
properties.appendChild(name);
String contentxml = XMLUtils
.documentToString(content,
StartupServlet.planningtoolformat);
creator.setObject("palette_node_" + index, contentxml);
creator.addContentProperty("GROUP_ID", groupId);
creator.addContentProperty("CHALLENGE_ID", challengeId);
creator.addContentProperty("CHALLENGE_NAME", challengeName);
creator.addContentProperty("CATEGORY_ID", cateogryId);
creator.addContentProperty("ICON_ID", iconid);
return creator.getDocument();
} catch (XMLException e) {
e.printStackTrace();
}
return null;
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.network.fluent;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.http.rest.PagedFlux;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.Response;
import com.azure.core.management.polling.PollResult;
import com.azure.core.util.Context;
import com.azure.core.util.polling.PollerFlux;
import com.azure.core.util.polling.SyncPoller;
import com.azure.resourcemanager.network.fluent.models.SubnetInner;
import com.azure.resourcemanager.network.models.PrepareNetworkPoliciesRequest;
import java.nio.ByteBuffer;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/** An instance of this class provides access to all the operations defined in SubnetsClient. */
public interface SubnetsClient {
/**
* Deletes the specified subnet.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param subnetName The name of the subnet.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<Flux<ByteBuffer>>> deleteWithResponseAsync(
String resourceGroupName, String virtualNetworkName, String subnetName);
/**
* Deletes the specified subnet.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param subnetName The name of the subnet.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
PollerFlux<PollResult<Void>, Void> beginDeleteAsync(
String resourceGroupName, String virtualNetworkName, String subnetName);
/**
* Deletes the specified subnet.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param subnetName The name of the subnet.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
SyncPoller<PollResult<Void>, Void> beginDelete(
String resourceGroupName, String virtualNetworkName, String subnetName);
/**
* Deletes the specified subnet.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param subnetName The name of the subnet.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
SyncPoller<PollResult<Void>, Void> beginDelete(
String resourceGroupName, String virtualNetworkName, String subnetName, Context context);
/**
* Deletes the specified subnet.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param subnetName The name of the subnet.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Void> deleteAsync(String resourceGroupName, String virtualNetworkName, String subnetName);
/**
* Deletes the specified subnet.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param subnetName The name of the subnet.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
void delete(String resourceGroupName, String virtualNetworkName, String subnetName);
/**
* Deletes the specified subnet.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param subnetName The name of the subnet.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
void delete(String resourceGroupName, String virtualNetworkName, String subnetName, Context context);
/**
* Gets the specified subnet by virtual network and resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param subnetName The name of the subnet.
* @param expand Expands referenced resources.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the specified subnet by virtual network and resource group.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<SubnetInner>> getWithResponseAsync(
String resourceGroupName, String virtualNetworkName, String subnetName, String expand);
/**
* Gets the specified subnet by virtual network and resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param subnetName The name of the subnet.
* @param expand Expands referenced resources.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the specified subnet by virtual network and resource group.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<SubnetInner> getAsync(String resourceGroupName, String virtualNetworkName, String subnetName, String expand);
/**
* Gets the specified subnet by virtual network and resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param subnetName The name of the subnet.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the specified subnet by virtual network and resource group.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<SubnetInner> getAsync(String resourceGroupName, String virtualNetworkName, String subnetName);
/**
* Gets the specified subnet by virtual network and resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param subnetName The name of the subnet.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the specified subnet by virtual network and resource group.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
SubnetInner get(String resourceGroupName, String virtualNetworkName, String subnetName);
/**
* Gets the specified subnet by virtual network and resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param subnetName The name of the subnet.
* @param expand Expands referenced resources.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the specified subnet by virtual network and resource group.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<SubnetInner> getWithResponse(
String resourceGroupName, String virtualNetworkName, String subnetName, String expand, Context context);
/**
* Creates or updates a subnet in the specified virtual network.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param subnetName The name of the subnet.
* @param subnetParameters Subnet in a virtual network resource.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return subnet in a virtual network resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<Flux<ByteBuffer>>> createOrUpdateWithResponseAsync(
String resourceGroupName, String virtualNetworkName, String subnetName, SubnetInner subnetParameters);
/**
* Creates or updates a subnet in the specified virtual network.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param subnetName The name of the subnet.
* @param subnetParameters Subnet in a virtual network resource.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return subnet in a virtual network resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
PollerFlux<PollResult<SubnetInner>, SubnetInner> beginCreateOrUpdateAsync(
String resourceGroupName, String virtualNetworkName, String subnetName, SubnetInner subnetParameters);
/**
* Creates or updates a subnet in the specified virtual network.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param subnetName The name of the subnet.
* @param subnetParameters Subnet in a virtual network resource.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return subnet in a virtual network resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
SyncPoller<PollResult<SubnetInner>, SubnetInner> beginCreateOrUpdate(
String resourceGroupName, String virtualNetworkName, String subnetName, SubnetInner subnetParameters);
/**
* Creates or updates a subnet in the specified virtual network.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param subnetName The name of the subnet.
* @param subnetParameters Subnet in a virtual network resource.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return subnet in a virtual network resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
SyncPoller<PollResult<SubnetInner>, SubnetInner> beginCreateOrUpdate(
String resourceGroupName,
String virtualNetworkName,
String subnetName,
SubnetInner subnetParameters,
Context context);
/**
* Creates or updates a subnet in the specified virtual network.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param subnetName The name of the subnet.
* @param subnetParameters Subnet in a virtual network resource.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return subnet in a virtual network resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<SubnetInner> createOrUpdateAsync(
String resourceGroupName, String virtualNetworkName, String subnetName, SubnetInner subnetParameters);
/**
* Creates or updates a subnet in the specified virtual network.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param subnetName The name of the subnet.
* @param subnetParameters Subnet in a virtual network resource.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return subnet in a virtual network resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
SubnetInner createOrUpdate(
String resourceGroupName, String virtualNetworkName, String subnetName, SubnetInner subnetParameters);
/**
* Creates or updates a subnet in the specified virtual network.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param subnetName The name of the subnet.
* @param subnetParameters Subnet in a virtual network resource.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return subnet in a virtual network resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
SubnetInner createOrUpdate(
String resourceGroupName,
String virtualNetworkName,
String subnetName,
SubnetInner subnetParameters,
Context context);
/**
* Prepares a subnet by applying network intent policies.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param subnetName The name of the subnet.
* @param prepareNetworkPoliciesRequestParameters Details of PrepareNetworkPolicies for Subnet.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<Flux<ByteBuffer>>> prepareNetworkPoliciesWithResponseAsync(
String resourceGroupName,
String virtualNetworkName,
String subnetName,
PrepareNetworkPoliciesRequest prepareNetworkPoliciesRequestParameters);
/**
* Prepares a subnet by applying network intent policies.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param subnetName The name of the subnet.
* @param prepareNetworkPoliciesRequestParameters Details of PrepareNetworkPolicies for Subnet.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
PollerFlux<PollResult<Void>, Void> beginPrepareNetworkPoliciesAsync(
String resourceGroupName,
String virtualNetworkName,
String subnetName,
PrepareNetworkPoliciesRequest prepareNetworkPoliciesRequestParameters);
/**
* Prepares a subnet by applying network intent policies.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param subnetName The name of the subnet.
* @param prepareNetworkPoliciesRequestParameters Details of PrepareNetworkPolicies for Subnet.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
SyncPoller<PollResult<Void>, Void> beginPrepareNetworkPolicies(
String resourceGroupName,
String virtualNetworkName,
String subnetName,
PrepareNetworkPoliciesRequest prepareNetworkPoliciesRequestParameters);
/**
* Prepares a subnet by applying network intent policies.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param subnetName The name of the subnet.
* @param prepareNetworkPoliciesRequestParameters Details of PrepareNetworkPolicies for Subnet.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
SyncPoller<PollResult<Void>, Void> beginPrepareNetworkPolicies(
String resourceGroupName,
String virtualNetworkName,
String subnetName,
PrepareNetworkPoliciesRequest prepareNetworkPoliciesRequestParameters,
Context context);
/**
* Prepares a subnet by applying network intent policies.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param subnetName The name of the subnet.
* @param prepareNetworkPoliciesRequestParameters Details of PrepareNetworkPolicies for Subnet.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Void> prepareNetworkPoliciesAsync(
String resourceGroupName,
String virtualNetworkName,
String subnetName,
PrepareNetworkPoliciesRequest prepareNetworkPoliciesRequestParameters);
/**
* Prepares a subnet by applying network intent policies.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param subnetName The name of the subnet.
* @param prepareNetworkPoliciesRequestParameters Details of PrepareNetworkPolicies for Subnet.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
void prepareNetworkPolicies(
String resourceGroupName,
String virtualNetworkName,
String subnetName,
PrepareNetworkPoliciesRequest prepareNetworkPoliciesRequestParameters);
/**
* Prepares a subnet by applying network intent policies.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param subnetName The name of the subnet.
* @param prepareNetworkPoliciesRequestParameters Details of PrepareNetworkPolicies for Subnet.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
void prepareNetworkPolicies(
String resourceGroupName,
String virtualNetworkName,
String subnetName,
PrepareNetworkPoliciesRequest prepareNetworkPoliciesRequestParameters,
Context context);
/**
* Unprepares a subnet by removing network intent policies.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param subnetName The name of the subnet.
* @param serviceName The name of the service for which subnet is being unprepared for.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<Flux<ByteBuffer>>> unprepareNetworkPoliciesWithResponseAsync(
String resourceGroupName, String virtualNetworkName, String subnetName, String serviceName);
/**
* Unprepares a subnet by removing network intent policies.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param subnetName The name of the subnet.
* @param serviceName The name of the service for which subnet is being unprepared for.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
PollerFlux<PollResult<Void>, Void> beginUnprepareNetworkPoliciesAsync(
String resourceGroupName, String virtualNetworkName, String subnetName, String serviceName);
/**
* Unprepares a subnet by removing network intent policies.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param subnetName The name of the subnet.
* @param serviceName The name of the service for which subnet is being unprepared for.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
SyncPoller<PollResult<Void>, Void> beginUnprepareNetworkPolicies(
String resourceGroupName, String virtualNetworkName, String subnetName, String serviceName);
/**
* Unprepares a subnet by removing network intent policies.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param subnetName The name of the subnet.
* @param serviceName The name of the service for which subnet is being unprepared for.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
SyncPoller<PollResult<Void>, Void> beginUnprepareNetworkPolicies(
String resourceGroupName, String virtualNetworkName, String subnetName, String serviceName, Context context);
/**
* Unprepares a subnet by removing network intent policies.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param subnetName The name of the subnet.
* @param serviceName The name of the service for which subnet is being unprepared for.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Void> unprepareNetworkPoliciesAsync(
String resourceGroupName, String virtualNetworkName, String subnetName, String serviceName);
/**
* Unprepares a subnet by removing network intent policies.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param subnetName The name of the subnet.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Void> unprepareNetworkPoliciesAsync(String resourceGroupName, String virtualNetworkName, String subnetName);
/**
* Unprepares a subnet by removing network intent policies.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param subnetName The name of the subnet.
* @param serviceName The name of the service for which subnet is being unprepared for.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
void unprepareNetworkPolicies(
String resourceGroupName, String virtualNetworkName, String subnetName, String serviceName);
/**
* Unprepares a subnet by removing network intent policies.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param subnetName The name of the subnet.
* @param serviceName The name of the service for which subnet is being unprepared for.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
void unprepareNetworkPolicies(
String resourceGroupName, String virtualNetworkName, String subnetName, String serviceName, Context context);
/**
* Unprepares a subnet by removing network intent policies.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param subnetName The name of the subnet.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
void unprepareNetworkPolicies(String resourceGroupName, String virtualNetworkName, String subnetName);
/**
* Gets all subnets in a virtual network.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all subnets in a virtual network.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedFlux<SubnetInner> listAsync(String resourceGroupName, String virtualNetworkName);
/**
* Gets all subnets in a virtual network.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all subnets in a virtual network.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<SubnetInner> list(String resourceGroupName, String virtualNetworkName);
/**
* Gets all subnets in a virtual network.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkName The name of the virtual network.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all subnets in a virtual network.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<SubnetInner> list(String resourceGroupName, String virtualNetworkName, Context context);
}
| |
/*
* #%L
* Wisdom-Framework
* %%
* Copyright (C) 2013 - 2015 Wisdom Framework
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.wisdom.executors;
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wisdom.api.concurrent.*;
import java.util.*;
import java.util.concurrent.*;
/**
* Common methods used in the different
* {@link org.wisdom.api.concurrent.ManagedExecutorService} implementations.
*/
public abstract class AbstractManagedExecutorService implements ManagedExecutorService {
protected final String name;
protected final long hungTime;
protected ListeningExecutorService executor;
protected ThreadPoolExecutor internalPool;
protected final Set<Task<?>> tasks = new LinkedHashSet<>();
protected final Logger logger;
protected ExecutionStatistics statistics = new ExecutionStatistics();
protected List<ExecutionContextService> ecs;
protected AbstractManagedExecutorService(String name, long hungTime, List<ExecutionContextService> ecs) {
Preconditions.checkNotNull(name);
this.name = name;
this.logger = LoggerFactory.getLogger("executor-" + name);
this.hungTime = hungTime;
this.ecs = ecs;
}
protected AbstractManagedExecutorService setInternalPool(ThreadPoolExecutor executor) {
this.internalPool = executor;
this.executor = MoreExecutors.listeningDecorator(this.internalPool);
return this;
}
protected ThreadPoolExecutor getInternalPool() {
return internalPool;
}
protected ListeningExecutorService getExecutor() {
return executor;
}
public String name() {
return this.name;
}
@Override
public ExecutionStatistics getExecutionTimeStatistics() {
return statistics.copy();
}
@Override
public Collection<ManagedFutureTask> getHungTasks() {
List<ManagedFutureTask> hung = new ArrayList<>();
for (ManagedFutureTask task : tasks) {
if (task.isTaskHang()) {
hung.add(task);
}
}
return hung;
}
@Override
public void shutdown() {
executor.shutdown();
}
@Override
public List<Runnable> shutdownNow() {
for (Task task : tasks) {
task.cancel(true);
}
return executor.shutdownNow();
}
protected ExecutionContext createExecutionContext() {
if (ecs == null) {
return null;
}
List<ExecutionContextService> copy = new ArrayList<>(ecs);
List<ExecutionContext> ec = new ArrayList<>();
for (ExecutionContextService svc : copy) {
ec.add(svc.prepare());
}
return CompositeExecutionContext.create(ec);
}
@Override
public boolean isShutdown() {
return executor.isShutdown();
}
/**
* Returns {@code true} if all tasks have completed following shut down.
* Note that {@code isTerminated} is never {@code true} unless
* either {@code shutdown} or {@code shutdownNow} was called first.
*
* @return {@code true} if all tasks have completed following shut down
*/
@Override
public boolean isTerminated() {
return executor.isTerminated();
}
@Override
public boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException {
return executor.awaitTermination(timeout, unit);
}
@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException {
List<Future<T>> futures = executor.invokeAll(tasks);
List<Future<T>> manageable = new ArrayList<>(futures.size());
int i = 0;
for (Callable<T> callable : tasks) {
Task task = getNewTaskFor(callable);
task.submitted(futures.get(i));
manageable.add(task);
i++;
}
return manageable;
}
protected abstract <T> Task getNewTaskFor(Callable<T> callable);
protected abstract <V> Task<V> getNewTaskFor(Runnable task, V result);
@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException {
List<Future<T>> futures = executor.invokeAll(tasks, timeout, unit);
List<Future<T>> manageable = new ArrayList<>(futures.size());
int i = 0;
for (Callable<T> callable : tasks) {
Task task = getNewTaskFor(callable);
task.submitted(futures.get(i));
manageable.add(task);
i++;
}
return manageable;
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
throws InterruptedException, ExecutionException {
return executor.invokeAny(tasks);
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
return executor.invokeAny(tasks, timeout, unit);
}
@Override
public void execute(Runnable command) {
Task<Void> task = getNewTaskFor(command, null);
task.execute();
}
/**
* Returns the largest number of threads that have ever
* simultaneously been in the pool.
*
* @return the number of threads
*/
@Override
public int getLargestPoolSize() {
return internalPool.getLargestPoolSize();
}
/**
* Returns the maximum allowed number of threads.
*
* @return the maximum allowed number of threads
*/
@Override
public int getMaximumPoolSize() {
return internalPool.getMaximumPoolSize();
}
/**
* Returns the current number of threads in the pool.
*
* @return the number of threads
*/
@Override
public int getPoolSize() {
return internalPool.getPoolSize();
}
/**
* Returns the core number of threads.
*
* @return the core number of threads
*/
@Override
public int getCorePoolSize() {
return internalPool.getCorePoolSize();
}
/**
* Returns the approximate total number of tasks that have
* completed execution. Because the states of tasks and threads
* may change dynamically during computation, the returned value
* is only an approximation, but one that does not ever decrease
* across successive calls.
*
* @return the number of tasks
*/
@Override
public long getCompletedTaskCount() {
return internalPool.getCompletedTaskCount();
}
/**
* Returns the approximate number of threads that are actively
* executing tasks.
*
* @return the number of threads
*/
@Override
public int getActiveCount() {
return internalPool.getActiveCount();
}
/**
* Returns the task queue used by this executor. Access to the
* task queue is intended primarily for debugging and monitoring.
* This queue may be in active use. Retrieving the task queue
* does not prevent queued tasks from executing.
*
* @return the task queue
*/
@Override
public BlockingQueue<Runnable> getQueue() {
return internalPool.getQueue();
}
/**
* Tries to remove from the work queue all {@link java.util.concurrent.Future}
* tasks that have been cancelled. This method can be useful as a
* storage reclamation operation, that has no other impact on
* functionality. Cancelled tasks are never executed, but may
* accumulate in work queues until worker threads can actively
* remove them. Invoking this method instead tries to remove them now.
* However, this method may fail to remove tasks in
* the presence of interference by other threads.
*/
@Override
public void purge() {
internalPool.purge();
}
/**
* Removes this task from the executor's internal queue if it is
* present, thus causing it not to be run if it has not already
* started.
* <p>
* <p>This method may be useful as one part of a cancellation
* scheme. It may fail to remove tasks that have been converted
* into other forms before being placed on the internal queue. For
* example, a task entered using {@code submit} might be
* converted into a form that maintains {@code Future} status.
* However, in such cases, method {@link #purge} may be used to
* remove those Futures that have been cancelled.
*
* @param task the task to remove
* @return {@code true} if the task was removed
*/
@Override
public boolean remove(Runnable task) {
return internalPool.remove(task);
}
/**
* Returns the approximate total number of tasks that have ever been
* scheduled for execution. Because the states of tasks and
* threads may change dynamically during computation, the returned
* value is only an approximation.
*
* @return the number of tasks
*/
@Override
public long getTaskCount() {
return internalPool.getTaskCount();
}
/**
* Returns the thread keep-alive time, which is the amount of time
* that threads in excess of the core pool size may remain
* idle before being terminated.
*
* @param unit the desired time unit of the result
* @return the time limit
*/
@Override
public long getKeepAliveTime(TimeUnit unit) {
return internalPool.getKeepAliveTime(unit);
}
@Override
public <T> ManagedFutureTask<T> submit(Callable<T> task) {
if (task == null) {
throw new NullPointerException();
}
return getNewTaskFor(task).execute();
}
@Override
public <T> ManagedFutureTask<T> submit(Runnable task, T result) {
if (task == null) {
throw new NullPointerException();
}
final Task t = getNewTaskFor(task, result).execute();
t.addListener(new Runnable() {
@Override
public void run() {
tasks.remove(t);
}
});
tasks.add(t);
return t;
}
@Override
public ManagedFutureTask<?> submit(Runnable task) {
// Passing null may lead to issue as submit ask for a non-null parameter.
return submit(task, null); //NOSONAR
}
/**
* Computes the execution time of the completed task (given), and add it to the statistics.
*
* @param task the completed task
*/
protected void addToStatistics(Task task) {
statistics.accept(task.getTaskCompletionTime() - task.getTaskStartTime());
}
}
| |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.editor.ex;
import com.intellij.accessibility.AccessibilityUtils;
import com.intellij.ide.ui.UINumericRange;
import com.intellij.lang.Language;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.*;
import com.intellij.openapi.editor.actions.CaretStopOptions;
import com.intellij.openapi.editor.impl.softwrap.SoftWrapAppliancePlaces;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.serviceContainer.NonInjectable;
import com.intellij.ui.breadcrumbs.BreadcrumbsProvider;
import org.intellij.lang.annotations.MagicConstant;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@State(name = "EditorSettings", storages = @Storage("editor.xml"), category = SettingsCategory.CODE)
public class EditorSettingsExternalizable implements PersistentStateComponent<EditorSettingsExternalizable.OptionSet> {
@NonNls
public static final String PROP_VIRTUAL_SPACE = "VirtualSpace";
@NonNls
public static final String PROP_BREADCRUMBS_PER_LANGUAGE = "BreadcrumbsPerLanguage";
@NonNls
public static final String PROP_DOC_COMMENT_RENDERING = "DocCommentRendering";
public static final UINumericRange BLINKING_RANGE = new UINumericRange(500, 10, 1500);
public static final UINumericRange TOOLTIPS_DELAY_RANGE = new UINumericRange(500, 1, 5000);
private static final String SOFT_WRAP_FILE_MASKS_ENABLED_DEFAULT = "*";
@NonNls private static final String SOFT_WRAP_FILE_MASKS_DISABLED_DEFAULT = "*.md; *.txt; *.rst; *.adoc";
//Q: make it interface?
public static final class OptionSet {
public String LINE_SEPARATOR;
public String USE_SOFT_WRAPS;
public String SOFT_WRAP_FILE_MASKS;
public boolean USE_CUSTOM_SOFT_WRAP_INDENT = true;
public int CUSTOM_SOFT_WRAP_INDENT = 0;
public boolean IS_VIRTUAL_SPACE = false;
public boolean IS_CARET_INSIDE_TABS;
@NonNls public String STRIP_TRAILING_SPACES = STRIP_TRAILING_SPACES_CHANGED;
public boolean IS_ENSURE_NEWLINE_AT_EOF = false;
public boolean REMOVE_TRAILING_BLANK_LINES = false;
public boolean SHOW_QUICK_DOC_ON_MOUSE_OVER_ELEMENT = true;
public boolean SHOW_INSPECTION_WIDGET = true;
public int TOOLTIPS_DELAY_MS = TOOLTIPS_DELAY_RANGE.initial;
public boolean SHOW_INTENTION_BULB = true;
public boolean IS_CARET_BLINKING = true;
public int CARET_BLINKING_PERIOD = BLINKING_RANGE.initial;
public boolean IS_RIGHT_MARGIN_SHOWN = true;
public boolean ARE_LINE_NUMBERS_SHOWN = true;
public boolean ARE_GUTTER_ICONS_SHOWN = true;
public boolean IS_FOLDING_OUTLINE_SHOWN = true;
public boolean SHOW_BREADCRUMBS_ABOVE = false;
public boolean SHOW_BREADCRUMBS = true;
public boolean ENABLE_RENDERED_DOC = false;
public boolean SHOW_INTENTION_PREVIEW = false;
public boolean USE_EDITOR_FONT_IN_INLAYS = false;
public boolean SMART_HOME = true;
public boolean IS_BLOCK_CURSOR = false;
public boolean IS_WHITESPACES_SHOWN = false;
public boolean IS_LEADING_WHITESPACES_SHOWN = true;
public boolean IS_INNER_WHITESPACES_SHOWN = true;
public boolean IS_TRAILING_WHITESPACES_SHOWN = true;
@SuppressWarnings("SpellCheckingInspection")
public boolean IS_ALL_SOFTWRAPS_SHOWN = false;
public boolean IS_INDENT_GUIDES_SHOWN = true;
public boolean IS_FOCUS_MODE = false;
public boolean IS_ANIMATED_SCROLLING = true;
public boolean IS_CAMEL_WORDS = false;
public boolean ADDITIONAL_PAGE_AT_BOTTOM = false;
public boolean IS_DND_ENABLED = true;
@SuppressWarnings("SpellCheckingInspection")
public boolean IS_WHEEL_FONTCHANGE_ENABLED = false;
public boolean IS_WHEEL_FONTCHANGE_PERSISTENT = false;
public boolean IS_MOUSE_CLICK_SELECTION_HONORS_CAMEL_WORDS = true;
public boolean RENAME_VARIABLES_INPLACE = true;
public boolean PRESELECT_RENAME = true;
public boolean SHOW_INLINE_DIALOG = true;
public boolean REFRAIN_FROM_SCROLLING = false;
public boolean ADD_CARETS_ON_DOUBLE_CTRL = true;
public BidiTextDirection BIDI_TEXT_DIRECTION = BidiTextDirection.CONTENT_BASED;
public boolean SHOW_PARAMETER_NAME_HINTS = true;
public boolean KEEP_TRAILING_SPACE_ON_CARET_LINE = true;
private final Map<String, Boolean> mapLanguageBreadcrumbs = new HashMap<>();
public Map<String, Boolean> getLanguageBreadcrumbsMap() {
return mapLanguageBreadcrumbs;
}
@SuppressWarnings("unused")
public void setLanguageBreadcrumbsMap(Map<String, Boolean> map) {
if (this.mapLanguageBreadcrumbs != map) {
this.mapLanguageBreadcrumbs.clear();
this.mapLanguageBreadcrumbs.putAll(map);
}
}
}
@State(
name = "OsSpecificEditorSettings",
storages = @Storage(value = "editor.os-specific.xml", roamingType = RoamingType.PER_OS),
category = SettingsCategory.CODE
)
public static final class OsSpecificState implements PersistentStateComponent<OsSpecificState> {
public CaretStopOptions CARET_STOP_OPTIONS = new CaretStopOptions();
@Override
public OsSpecificState getState() {
return this;
}
@Override
public void loadState(@NotNull OsSpecificState state) {
CARET_STOP_OPTIONS = state.CARET_STOP_OPTIONS;
}
}
private static final String COMPOSITE_PROPERTY_SEPARATOR = ":";
@NotNull private final OsSpecificState myOsSpecificState;
private final Set<SoftWrapAppliancePlaces> myPlacesToUseSoftWraps = EnumSet.noneOf(SoftWrapAppliancePlaces.class);
private OptionSet myOptions = new OptionSet();
private final PropertyChangeSupport myPropertyChangeSupport = new PropertyChangeSupport(this);
private final Map<String, Boolean> myDefaultBreadcrumbVisibility = new HashMap<>();
private int myBlockIndent;
@NonNls public static final String STRIP_TRAILING_SPACES_NONE = "None";
@NonNls public static final String STRIP_TRAILING_SPACES_CHANGED = "Changed";
@NonNls public static final String STRIP_TRAILING_SPACES_WHOLE = "Whole";
@MagicConstant(stringValues = {STRIP_TRAILING_SPACES_NONE, STRIP_TRAILING_SPACES_CHANGED, STRIP_TRAILING_SPACES_WHOLE})
public @interface StripTrailingSpaces {}
public EditorSettingsExternalizable() {
this(ApplicationManager.getApplication().getService(OsSpecificState.class));
}
@NonInjectable
public EditorSettingsExternalizable(@NotNull OsSpecificState state) {
myOsSpecificState = state;
}
public static EditorSettingsExternalizable getInstance() {
return ApplicationManager.getApplication().getService(EditorSettingsExternalizable.class);
}
public void addPropertyChangeListener(@NotNull PropertyChangeListener listener, @NotNull Disposable disposable) {
myPropertyChangeSupport.addPropertyChangeListener(listener);
Disposer.register(disposable, () -> myPropertyChangeSupport.removePropertyChangeListener(listener));
}
@NotNull
@Override
public OptionSet getState() {
return myOptions;
}
@Override
public void loadState(@NotNull OptionSet state) {
myOptions = state;
parseRawSoftWraps();
}
private void parseRawSoftWraps() {
myPlacesToUseSoftWraps.clear();
if (StringUtil.isEmpty(myOptions.USE_SOFT_WRAPS)) {
return;
}
String[] placeNames = myOptions.USE_SOFT_WRAPS.split(COMPOSITE_PROPERTY_SEPARATOR);
for (String placeName : placeNames) {
try {
SoftWrapAppliancePlaces place = SoftWrapAppliancePlaces.valueOf(placeName);
myPlacesToUseSoftWraps.add(place);
}
catch (IllegalArgumentException e) {
// Ignore bad value
}
}
// There is a possible case that there were invalid/old format values. We want to replace them by up-to-date data.
storeRawSoftWraps();
}
private void storeRawSoftWraps() {
StringBuilder buffer = new StringBuilder();
for (SoftWrapAppliancePlaces placeToStore : myPlacesToUseSoftWraps) {
buffer.append(placeToStore).append(COMPOSITE_PROPERTY_SEPARATOR);
}
if (buffer.length() > 0) {
buffer.setLength(buffer.length() - 1);
}
myOptions.USE_SOFT_WRAPS = buffer.toString();
}
public OptionSet getOptions() {
return myOptions;
}
public boolean isRightMarginShown() {
return myOptions.IS_RIGHT_MARGIN_SHOWN;
}
public void setRightMarginShown(boolean val) {
myOptions.IS_RIGHT_MARGIN_SHOWN = val;
}
public boolean isLineNumbersShown() {
return myOptions.ARE_LINE_NUMBERS_SHOWN;
}
public void setLineNumbersShown(boolean val) {
myOptions.ARE_LINE_NUMBERS_SHOWN = val;
}
public boolean areGutterIconsShown() {
return myOptions.ARE_GUTTER_ICONS_SHOWN;
}
public void setGutterIconsShown(boolean val) {
myOptions.ARE_GUTTER_ICONS_SHOWN = val;
}
public boolean isFoldingOutlineShown() {
return myOptions.IS_FOLDING_OUTLINE_SHOWN;
}
public void setFoldingOutlineShown(boolean val) {
myOptions.IS_FOLDING_OUTLINE_SHOWN = val;
}
/**
* @return {@code true} if breadcrumbs should be shown above the editor, {@code false} otherwise
*/
public boolean isBreadcrumbsAbove() {
return myOptions.SHOW_BREADCRUMBS_ABOVE;
}
/**
* @param value {@code true} if breadcrumbs should be shown above the editor, {@code false} otherwise
* @return {@code true} if an option was modified, {@code false} otherwise
*/
public boolean setBreadcrumbsAbove(boolean value) {
if (myOptions.SHOW_BREADCRUMBS_ABOVE == value) return false;
myOptions.SHOW_BREADCRUMBS_ABOVE = value;
return true;
}
/**
* @return {@code true} if breadcrumbs should be shown, {@code false} otherwise
*/
public boolean isBreadcrumbsShown() {
return myOptions.SHOW_BREADCRUMBS;
}
/**
* @param value {@code true} if breadcrumbs should be shown, {@code false} otherwise
* @return {@code true} if an option was modified, {@code false} otherwise
*/
public boolean setBreadcrumbsShown(boolean value) {
if (myOptions.SHOW_BREADCRUMBS == value) return false;
myOptions.SHOW_BREADCRUMBS = value;
return true;
}
/**
* @param languageID the language identifier to configure
* @return {@code true} if breadcrumbs should be shown for the specified language, {@code false} otherwise
*/
public boolean isBreadcrumbsShownFor(String languageID) {
Boolean visible = myOptions.mapLanguageBreadcrumbs.get(languageID);
if (visible == null) {
Boolean defaultVisible = myDefaultBreadcrumbVisibility.get(languageID);
if (defaultVisible == null) {
for (BreadcrumbsProvider provider : BreadcrumbsProvider.EP_NAME.getExtensionList()) {
for (Language language : provider.getLanguages()) {
myDefaultBreadcrumbVisibility.put(language.getID(), provider.isShownByDefault());
}
}
defaultVisible = myDefaultBreadcrumbVisibility.get(languageID);
}
return defaultVisible == null || defaultVisible;
}
return visible;
}
public void resetDefaultBreadcrumbVisibility() {
myDefaultBreadcrumbVisibility.clear();
}
public boolean hasBreadcrumbSettings(String languageID) {
return myOptions.mapLanguageBreadcrumbs.containsKey(languageID);
}
/**
* @param languageID the language identifier to configure
* @param value {@code true} if breadcrumbs should be shown for the specified language, {@code false} otherwise
* @return {@code true} if an option was modified, {@code false} otherwise
*/
public boolean setBreadcrumbsShownFor(String languageID, boolean value) {
Boolean visible = myOptions.mapLanguageBreadcrumbs.put(languageID, value);
boolean newValue = (visible == null || visible) != value;
if (newValue) {
myPropertyChangeSupport.firePropertyChange(PROP_BREADCRUMBS_PER_LANGUAGE, visible, (Boolean)value);
}
return newValue;
}
public boolean isDocCommentRenderingEnabled() {
return myOptions.ENABLE_RENDERED_DOC;
}
public void setDocCommentRenderingEnabled(boolean value) {
boolean oldValue = myOptions.ENABLE_RENDERED_DOC;
myOptions.ENABLE_RENDERED_DOC = value;
if (oldValue != value) {
myPropertyChangeSupport.firePropertyChange(PROP_DOC_COMMENT_RENDERING, oldValue, value);
}
}
public boolean isBlockCursor() {
return myOptions.IS_BLOCK_CURSOR;
}
public void setBlockCursor(boolean val) {
myOptions.IS_BLOCK_CURSOR = val;
}
public boolean isCaretRowShown() {
return true;
}
public int getBlockIndent() {
return myBlockIndent;
}
public void setBlockIndent(int blockIndent) {
myBlockIndent = blockIndent;
}
public boolean isSmartHome() {
return myOptions.SMART_HOME;
}
public void setSmartHome(boolean val) {
myOptions.SMART_HOME = val;
}
public boolean isUseSoftWraps() {
return isUseSoftWraps(SoftWrapAppliancePlaces.MAIN_EDITOR);
}
public boolean isUseSoftWraps(@NotNull SoftWrapAppliancePlaces place) {
return myPlacesToUseSoftWraps.contains(place);
}
public void setUseSoftWraps(boolean use) {
setUseSoftWraps(use, SoftWrapAppliancePlaces.MAIN_EDITOR);
}
public void setUseSoftWraps(boolean use, @NotNull SoftWrapAppliancePlaces place) {
boolean update = use ^ myPlacesToUseSoftWraps.contains(place);
if (!update) {
return;
}
if (use) {
myPlacesToUseSoftWraps.add(place);
}
else {
myPlacesToUseSoftWraps.remove(place);
}
storeRawSoftWraps();
if (place == SoftWrapAppliancePlaces.MAIN_EDITOR) {
setSoftWrapFileMasks(getSoftWrapFileMasks());
}
}
public boolean isUseCustomSoftWrapIndent() {
return myOptions.USE_CUSTOM_SOFT_WRAP_INDENT;
}
public void setUseCustomSoftWrapIndent(boolean use) {
myOptions.USE_CUSTOM_SOFT_WRAP_INDENT = use;
}
public int getCustomSoftWrapIndent() {
return myOptions.CUSTOM_SOFT_WRAP_INDENT;
}
public void setCustomSoftWrapIndent(int indent) {
myOptions.CUSTOM_SOFT_WRAP_INDENT = indent;
}
public boolean isVirtualSpace() {
return myOptions.IS_VIRTUAL_SPACE;
}
public void setVirtualSpace(boolean val) {
boolean oldValue = myOptions.IS_VIRTUAL_SPACE;
myOptions.IS_VIRTUAL_SPACE = val;
myPropertyChangeSupport.firePropertyChange(PROP_VIRTUAL_SPACE, oldValue, val);
}
public boolean isCaretInsideTabs() {
return myOptions.IS_CARET_INSIDE_TABS;
}
public void setCaretInsideTabs(boolean val) {
myOptions.IS_CARET_INSIDE_TABS = val;
}
public boolean isBlinkCaret() {
return myOptions.IS_CARET_BLINKING;
}
public void setBlinkCaret(boolean blinkCaret) {
myOptions.IS_CARET_BLINKING = blinkCaret;
}
public int getBlinkPeriod() {
return BLINKING_RANGE.fit(myOptions.CARET_BLINKING_PERIOD);
}
public void setBlinkPeriod(int blinkInterval) {
myOptions.CARET_BLINKING_PERIOD = BLINKING_RANGE.fit(blinkInterval);
}
public boolean isEnsureNewLineAtEOF() {
return myOptions.IS_ENSURE_NEWLINE_AT_EOF;
}
public void setEnsureNewLineAtEOF(boolean ensure) {
myOptions.IS_ENSURE_NEWLINE_AT_EOF = ensure;
}
public boolean isRemoveTrailingBlankLines() {
return myOptions.REMOVE_TRAILING_BLANK_LINES;
}
public void setRemoveTrailingBlankLines(boolean remove) {
myOptions.REMOVE_TRAILING_BLANK_LINES = remove;
}
@StripTrailingSpaces
public String getStripTrailingSpaces() {
return myOptions.STRIP_TRAILING_SPACES;
} // TODO: move to CodeEditorManager or something else
public void setStripTrailingSpaces(@StripTrailingSpaces String stripTrailingSpaces) {
myOptions.STRIP_TRAILING_SPACES = stripTrailingSpaces;
}
public boolean isShowQuickDocOnMouseOverElement() {
return myOptions.SHOW_QUICK_DOC_ON_MOUSE_OVER_ELEMENT && !AccessibilityUtils.isScreenReaderDetected();
}
public void setShowQuickDocOnMouseOverElement(boolean show) {
myOptions.SHOW_QUICK_DOC_ON_MOUSE_OVER_ELEMENT = show;
}
public boolean isShowInspectionWidget() {
return myOptions.SHOW_INSPECTION_WIDGET;
}
public void setShowInspectionWidget(boolean show) {
myOptions.SHOW_INSPECTION_WIDGET = show;
}
/**
* @deprecated Use {@link #getTooltipsDelay()} instead
*/
@Deprecated
public int getQuickDocOnMouseOverElementDelayMillis() {
return getTooltipsDelay();
}
public int getTooltipsDelay() {
return TOOLTIPS_DELAY_RANGE.fit(myOptions.TOOLTIPS_DELAY_MS);
}
public void setTooltipsDelay(int delay) {
myOptions.TOOLTIPS_DELAY_MS = TOOLTIPS_DELAY_RANGE.fit(delay);
}
public boolean isShowIntentionBulb() {
return myOptions.SHOW_INTENTION_BULB;
}
public void setShowIntentionBulb(boolean show) {
myOptions.SHOW_INTENTION_BULB = show;
}
public boolean isRefrainFromScrolling() {
return myOptions.REFRAIN_FROM_SCROLLING;
}
public void setRefrainFromScrolling(boolean b) {
myOptions.REFRAIN_FROM_SCROLLING = b;
}
public boolean isShowNotificationAfterReformat() {
return Registry.is("editor.show.notification.after.reformat");
}
public boolean isShowNotificationAfterOptimizeImports() {
return Registry.is("editor.show.notification.after.optimize.imports");
}
public boolean isWhitespacesShown() {
return myOptions.IS_WHITESPACES_SHOWN;
}
public void setWhitespacesShown(boolean val) {
myOptions.IS_WHITESPACES_SHOWN = val;
}
public boolean isLeadingWhitespacesShown() {
return myOptions.IS_LEADING_WHITESPACES_SHOWN;
}
public void setLeadingWhitespacesShown(boolean val) {
myOptions.IS_LEADING_WHITESPACES_SHOWN = val;
}
public boolean isInnerWhitespacesShown() {
return myOptions.IS_INNER_WHITESPACES_SHOWN;
}
public void setInnerWhitespacesShown(boolean val) {
myOptions.IS_INNER_WHITESPACES_SHOWN = val;
}
public boolean isTrailingWhitespacesShown() {
return myOptions.IS_TRAILING_WHITESPACES_SHOWN;
}
public void setTrailingWhitespacesShown(boolean val) {
myOptions.IS_TRAILING_WHITESPACES_SHOWN = val;
}
public boolean isAllSoftWrapsShown() {
return myOptions.IS_ALL_SOFTWRAPS_SHOWN;
}
public void setAllSoftwrapsShown(boolean val) {
myOptions.IS_ALL_SOFTWRAPS_SHOWN = val;
}
public boolean isIndentGuidesShown() {
return myOptions.IS_INDENT_GUIDES_SHOWN;
}
public void setIndentGuidesShown(boolean val) {
myOptions.IS_INDENT_GUIDES_SHOWN = val;
}
public boolean isFocusMode() {
return myOptions.IS_FOCUS_MODE;
}
public void setFocusMode(boolean val) {
myOptions.IS_FOCUS_MODE = val;
}
public boolean isSmoothScrolling() {
return myOptions.IS_ANIMATED_SCROLLING;
}
public void setSmoothScrolling(boolean val){
myOptions.IS_ANIMATED_SCROLLING = val;
}
public boolean isCamelWords() {
return myOptions.IS_CAMEL_WORDS;
}
public void setCamelWords(boolean val) {
myOptions.IS_CAMEL_WORDS = val;
}
public boolean isAdditionalPageAtBottom() {
return myOptions.ADDITIONAL_PAGE_AT_BOTTOM;
}
public void setAdditionalPageAtBottom(boolean val) {
myOptions.ADDITIONAL_PAGE_AT_BOTTOM = val;
}
public boolean isDndEnabled() {
return myOptions.IS_DND_ENABLED;
}
public void setDndEnabled(boolean val) {
myOptions.IS_DND_ENABLED = val;
}
public boolean isWheelFontChangeEnabled() {
return myOptions.IS_WHEEL_FONTCHANGE_ENABLED;
}
public void setWheelFontChangeEnabled(boolean val) {
myOptions.IS_WHEEL_FONTCHANGE_ENABLED = val;
}
public boolean isWheelFontChangePersistent() {
return myOptions.IS_WHEEL_FONTCHANGE_PERSISTENT;
}
public void setWheelFontChangePersistent(boolean val) {
myOptions.IS_WHEEL_FONTCHANGE_PERSISTENT = val;
}
public boolean isMouseClickSelectionHonorsCamelWords() {
return myOptions.IS_MOUSE_CLICK_SELECTION_HONORS_CAMEL_WORDS;
}
public void setMouseClickSelectionHonorsCamelWords(boolean val) {
myOptions.IS_MOUSE_CLICK_SELECTION_HONORS_CAMEL_WORDS = val;
}
public boolean isVariableInplaceRenameEnabled() {
return myOptions.RENAME_VARIABLES_INPLACE;
}
public void setVariableInplaceRenameEnabled(final boolean val) {
myOptions.RENAME_VARIABLES_INPLACE = val;
}
public boolean isPreselectRename() {
return myOptions.PRESELECT_RENAME;
}
public void setPreselectRename(final boolean val) {
myOptions.PRESELECT_RENAME = val;
}
public boolean isShowInlineLocalDialog() {
return myOptions.SHOW_INLINE_DIALOG;
}
public void setShowInlineLocalDialog(final boolean val) {
myOptions.SHOW_INLINE_DIALOG = val;
}
public boolean addCaretsOnDoubleCtrl() {
return myOptions.ADD_CARETS_ON_DOUBLE_CTRL;
}
public void setAddCaretsOnDoubleCtrl(boolean val) {
myOptions.ADD_CARETS_ON_DOUBLE_CTRL = val;
}
public BidiTextDirection getBidiTextDirection() {
return myOptions.BIDI_TEXT_DIRECTION;
}
public void setBidiTextDirection(BidiTextDirection direction) {
myOptions.BIDI_TEXT_DIRECTION = direction;
}
public boolean isShowIntentionPreview() {
return myOptions.SHOW_INTENTION_PREVIEW;
}
public void setShowIntentionPreview(boolean show) {
myOptions.SHOW_INTENTION_PREVIEW = show;
}
/**
* @deprecated use {@link com.intellij.codeInsight.hints.HintUtilsKt#isParameterHintsEnabledForLanguage(Language)} instead
*/
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean isShowParameterNameHints() {
return myOptions.SHOW_PARAMETER_NAME_HINTS;
}
/**
* @deprecated use {@link com.intellij.codeInsight.hints.HintUtilsKt#setShowParameterHintsForLanguage(boolean, Language)} instead
*/
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public void setShowParameterNameHints(boolean value) {
myOptions.SHOW_PARAMETER_NAME_HINTS = value;
}
public boolean isKeepTrailingSpacesOnCaretLine() {
return myOptions.KEEP_TRAILING_SPACE_ON_CARET_LINE;
}
public void setKeepTrailingSpacesOnCaretLine(boolean keep) {
myOptions.KEEP_TRAILING_SPACE_ON_CARET_LINE = keep;
}
@NotNull
public String getSoftWrapFileMasks() {
String storedValue = myOptions.SOFT_WRAP_FILE_MASKS;
if (storedValue != null) {
return storedValue;
}
return isUseSoftWraps() ? SOFT_WRAP_FILE_MASKS_ENABLED_DEFAULT : SOFT_WRAP_FILE_MASKS_DISABLED_DEFAULT;
}
public void setSoftWrapFileMasks(@NotNull String value) {
myOptions.SOFT_WRAP_FILE_MASKS = value;
}
@NotNull
public CaretStopOptions getCaretStopOptions() {
return myOsSpecificState.CARET_STOP_OPTIONS;
}
public void setCaretStopOptions(@NotNull CaretStopOptions options) {
myOsSpecificState.CARET_STOP_OPTIONS = options;
}
public boolean isUseEditorFontInInlays() {
return myOptions.USE_EDITOR_FONT_IN_INLAYS;
}
public void setUseEditorFontInInlays(boolean value) {
myOptions.USE_EDITOR_FONT_IN_INLAYS = value;
}
}
| |
/*
* 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.phoenix.end2end;
import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
import static org.apache.phoenix.util.TestUtil.getAllSplits;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HRegionLocation;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.phoenix.jdbc.PhoenixConnection;
import org.apache.phoenix.query.ConnectionQueryServices;
import org.apache.phoenix.query.KeyRange;
import org.apache.phoenix.query.QueryServices;
import org.apache.phoenix.schema.stats.GuidePostsInfo;
import org.apache.phoenix.util.PropertiesUtil;
import org.apache.phoenix.util.QueryUtil;
import org.apache.phoenix.util.ReadOnlyProps;
import org.apache.phoenix.util.TestUtil;
import org.junit.BeforeClass;
import org.junit.Test;
import com.google.common.collect.Maps;
public class StatsCollectorWithSplitsAndMultiCFIT extends StatsCollectorAbstractIT {
private static final String STATS_TEST_TABLE_NAME_NEW = "S_NEW";
private static final byte[] STATS_TEST_TABLE_NEW_BYTES = Bytes.toBytes(STATS_TEST_TABLE_NAME_NEW);
@BeforeClass
public static void doSetup() throws Exception {
Map<String, String> props = Maps.newHashMapWithExpectedSize(3);
// Must update config before starting server
props.put(QueryServices.STATS_GUIDEPOST_WIDTH_BYTES_ATTRIB, Long.toString(1000));
props.put(QueryServices.EXPLAIN_CHUNK_COUNT_ATTRIB, Boolean.TRUE.toString());
props.put(QueryServices.QUEUE_SIZE_ATTRIB, Integer.toString(1024));
setUpTestDriver(new ReadOnlyProps(props.entrySet().iterator()));
}
@Test
public void testWithMultiCF() throws Exception {
int nRows = 20;
Connection conn;
PreparedStatement stmt;
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
conn = DriverManager.getConnection(getUrl(), props);
conn.createStatement().execute(
"CREATE TABLE " + STATS_TEST_TABLE_NAME_NEW
+ "(k VARCHAR PRIMARY KEY, a.v INTEGER, b.v INTEGER, c.v INTEGER NULL, d.v INTEGER NULL) ");
stmt = conn.prepareStatement("UPSERT INTO " + STATS_TEST_TABLE_NAME_NEW + " VALUES(?,?, ?, ?, ?)");
byte[] val = new byte[250];
for (int i = 0; i < nRows; i++) {
stmt.setString(1, Character.toString((char)('a' + i)) + Bytes.toString(val));
stmt.setInt(2, i);
stmt.setInt(3, i);
stmt.setInt(4, i);
stmt.setInt(5, i);
stmt.executeUpdate();
}
conn.commit();
stmt = conn.prepareStatement("UPSERT INTO " + STATS_TEST_TABLE_NAME_NEW + "(k, c.v, d.v) VALUES(?,?,?)");
for (int i = 0; i < 5; i++) {
stmt.setString(1, Character.toString((char)('a' + 'z' + i)) + Bytes.toString(val));
stmt.setInt(2, i);
stmt.setInt(3, i);
stmt.executeUpdate();
}
conn.commit();
ResultSet rs;
TestUtil.analyzeTable(conn, STATS_TEST_TABLE_NAME_NEW);
List<KeyRange> keyRanges = getAllSplits(conn, STATS_TEST_TABLE_NAME_NEW);
assertEquals(12, keyRanges.size());
rs = conn.createStatement().executeQuery("EXPLAIN SELECT * FROM " + STATS_TEST_TABLE_NAME_NEW);
assertEquals("CLIENT " + (12) + "-CHUNK " + "PARALLEL 1-WAY FULL SCAN OVER " + STATS_TEST_TABLE_NAME_NEW,
QueryUtil.getExplainPlan(rs));
ConnectionQueryServices services = conn.unwrap(PhoenixConnection.class).getQueryServices();
List<HRegionLocation> regions = services.getAllTableRegions(STATS_TEST_TABLE_NEW_BYTES);
assertEquals(1, regions.size());
rs = conn.createStatement().executeQuery(
"SELECT GUIDE_POSTS_COUNT, REGION_NAME, GUIDE_POSTS_ROW_COUNT FROM SYSTEM.STATS WHERE PHYSICAL_NAME='"
+ STATS_TEST_TABLE_NAME_NEW + "' AND REGION_NAME IS NOT NULL");
assertTrue(rs.next());
assertEquals(11, (rs.getLong(1)));
assertEquals(regions.get(0).getRegionInfo().getRegionNameAsString(), rs.getString(2));
// I get 25 here because for A there is an entry added with the default col
assertEquals(25, rs.getLong(3));
assertTrue(rs.next());
assertEquals(5, (rs.getLong(1)));
assertEquals(regions.get(0).getRegionInfo().getRegionNameAsString(), rs.getString(2));
// for b the count is lesser by 5
assertEquals(20, rs.getLong(3));
assertTrue(rs.next());
assertEquals(6, (rs.getLong(1)));
assertEquals(regions.get(0).getRegionInfo().getRegionNameAsString(), rs.getString(2));
assertEquals(25, rs.getLong(3));
assertTrue(rs.next());
assertEquals(6, (rs.getLong(1)));
assertEquals(regions.get(0).getRegionInfo().getRegionNameAsString(), rs.getString(2));
assertEquals(25, rs.getLong(3));
assertFalse(rs.next());
Collection<GuidePostsInfo> infos = TestUtil.getGuidePostsList(conn, STATS_TEST_TABLE_NAME_NEW);
long[] rowCountArr = new long[]{25, 20, 25, 25};
// CF A alone has double the bytecount because it has column qualifier A and column qualifier _0
long[] byteCountArr = new long[]{12120, 5540, 6652, 6652};
int i = 0;
for(GuidePostsInfo info : infos) {
assertRowCountAndByteCount(info, rowCountArr[i], byteCountArr[i]);
i++;
}
}
protected void assertRowCountAndByteCount(GuidePostsInfo info, long rowCount, long byteCount) {
assertEquals(info.getRowCount(), rowCount);
assertEquals(info.getByteCount(), byteCount);
}
@Test
public void testSplitUpdatesStats() throws Exception {
int nRows = 20;
Connection conn;
PreparedStatement stmt;
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
conn = DriverManager.getConnection(getUrl(), props);
conn.createStatement().execute(
"CREATE TABLE " + STATS_TEST_TABLE_NAME + "(k VARCHAR PRIMARY KEY, v INTEGER) "
+ HColumnDescriptor.KEEP_DELETED_CELLS + "=" + Boolean.FALSE);
stmt = conn.prepareStatement("UPSERT INTO " + STATS_TEST_TABLE_NAME + " VALUES(?,?)");
byte[] val = new byte[250];
for (int i = 0; i < nRows; i++) {
stmt.setString(1, Character.toString((char)('a' + i)) + Bytes.toString(val));
stmt.setInt(2, i);
stmt.executeUpdate();
}
conn.commit();
ResultSet rs;
TestUtil.analyzeTable(conn, STATS_TEST_TABLE_NAME);
Collection<GuidePostsInfo> infos = TestUtil.getGuidePostsList(conn, STATS_TEST_TABLE_NAME);
for (GuidePostsInfo info : infos) {
assertEquals(20, info.getRowCount());
assertEquals(11020, info.getByteCount());
break;
}
List<KeyRange> keyRanges = getAllSplits(conn, STATS_TEST_TABLE_NAME);
assertEquals((nRows / 2) + 1, keyRanges.size());
rs = conn.createStatement().executeQuery("EXPLAIN SELECT * FROM " + STATS_TEST_TABLE_NAME);
assertEquals("CLIENT " + ((nRows / 2) + 1) + "-CHUNK " + "PARALLEL 1-WAY FULL SCAN OVER "
+ STATS_TEST_TABLE_NAME, QueryUtil.getExplainPlan(rs));
ConnectionQueryServices services = conn.unwrap(PhoenixConnection.class).getQueryServices();
List<HRegionLocation> regions = services.getAllTableRegions(STATS_TEST_TABLE_BYTES);
assertEquals(1, regions.size());
rs = conn.createStatement().executeQuery(
"SELECT GUIDE_POSTS_COUNT, REGION_NAME, GUIDE_POSTS_ROW_COUNT FROM SYSTEM.STATS WHERE PHYSICAL_NAME='"
+ STATS_TEST_TABLE_NAME + "' AND REGION_NAME IS NOT NULL");
assertTrue(rs.next());
assertEquals(nRows / 2, (rs.getLong(1)));
assertEquals(regions.get(0).getRegionInfo().getRegionNameAsString(), rs.getString(2));
//PhoenixArray arr = (PhoenixArray)rs.getArray(3);
assertEquals(20, rs.getLong(3));
assertFalse(rs.next());
byte[] midPoint = Bytes.toBytes(Character.toString((char)('a' + (5))));
splitTable(conn, midPoint, STATS_TEST_TABLE_BYTES);
keyRanges = getAllSplits(conn, STATS_TEST_TABLE_NAME);
assertEquals(12, keyRanges.size()); // Same number as before because split was at guidepost
regions = services.getAllTableRegions(STATS_TEST_TABLE_BYTES);
assertEquals(2, regions.size());
rs = conn.createStatement().executeQuery(
"SELECT GUIDE_POSTS_COUNT, REGION_NAME, "
+ "GUIDE_POSTS_ROW_COUNT FROM SYSTEM.STATS WHERE PHYSICAL_NAME='" + STATS_TEST_TABLE_NAME
+ "' AND REGION_NAME IS NOT NULL");
assertTrue(rs.next());
assertEquals(2, rs.getLong(1));
assertEquals(regions.get(0).getRegionInfo().getRegionNameAsString(), rs.getString(2));
//assertEquals(5, rs.getLong(3));
assertTrue(rs.next());
assertEquals(8, rs.getLong(1));
assertEquals(regions.get(1).getRegionInfo().getRegionNameAsString(), rs.getString(2));
// This could even be 15 if the compaction thread completes after the update from split
//assertEquals(16, rs.getLong(3));
assertFalse(rs.next());
byte[] midPoint2 = Bytes.toBytes("cj");
splitTable(conn, midPoint2, STATS_TEST_TABLE_BYTES);
keyRanges = getAllSplits(conn, STATS_TEST_TABLE_NAME);
assertEquals((nRows / 2) + 3, keyRanges.size()); // One extra due to split between guideposts
regions = services.getAllTableRegions(STATS_TEST_TABLE_BYTES);
assertEquals(3, regions.size());
rs = conn.createStatement().executeQuery(
"SELECT GUIDE_POSTS_COUNT, REGION_NAME, GUIDE_POSTS_ROW_COUNT FROM SYSTEM.STATS WHERE PHYSICAL_NAME='"
+ STATS_TEST_TABLE_NAME + "' AND REGION_NAME IS NOT NULL");
assertTrue(rs.next());
assertEquals(1, rs.getLong(1));
assertEquals(regions.get(0).getRegionInfo().getRegionNameAsString(), rs.getString(2));
// This value varies based on whether compaction updates or split updates the GPs
//assertEquals(3, rs.getLong(3));
assertTrue(rs.next());
assertEquals(1, rs.getLong(1));
assertEquals(regions.get(1).getRegionInfo().getRegionNameAsString(), rs.getString(2));
//assertEquals(2, rs.getLong(3));
assertTrue(rs.next());
assertEquals(8, rs.getLong(1));
assertEquals(regions.get(2).getRegionInfo().getRegionNameAsString(), rs.getString(2));
//assertEquals(16, rs.getLong(3));
assertFalse(rs.next());
rs = conn.createStatement().executeQuery("EXPLAIN SELECT * FROM " + STATS_TEST_TABLE_NAME);
assertEquals("CLIENT " + ((nRows / 2) + 3) + "-CHUNK " + "PARALLEL 1-WAY FULL SCAN OVER "
+ STATS_TEST_TABLE_NAME, QueryUtil.getExplainPlan(rs));
TestUtil.analyzeTable(conn, STATS_TEST_TABLE_NAME);
rs = conn.createStatement().executeQuery("EXPLAIN SELECT * FROM " + STATS_TEST_TABLE_NAME);
assertEquals("CLIENT " + ((nRows / 2) + 2) + "-CHUNK " + "PARALLEL 1-WAY FULL SCAN OVER "
+ STATS_TEST_TABLE_NAME, QueryUtil.getExplainPlan(rs));
infos = TestUtil.getGuidePostsList(conn, STATS_TEST_TABLE_NAME);
for (GuidePostsInfo info : infos) {
assertEquals(20, info.getRowCount());
assertEquals(9918, info.getByteCount());
break;
}
conn.close();
}
}
| |
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2019 Serge Rider (serge@jkiss.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.dbeaver.ui.editors.sql.convert;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.*;
import org.eclipse.ui.commands.IElementUpdater;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.menus.UIElement;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.model.exec.DBCExecutionContext;
import org.jkiss.dbeaver.model.preferences.DBPPropertyDescriptor;
import org.jkiss.dbeaver.model.sql.SQLScriptElement;
import org.jkiss.dbeaver.ui.editors.sql.internal.SQLEditorMessages;
import org.jkiss.dbeaver.ui.editors.sql.registry.SQLConverterRegistry;
import org.jkiss.dbeaver.ui.editors.sql.registry.SQLTargetConverterDescriptor;
import org.jkiss.dbeaver.runtime.properties.PropertySourceCustom;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.ui.controls.StyledTextUtils;
import org.jkiss.dbeaver.ui.editors.sql.dialogs.BaseSQLDialog;
import org.jkiss.dbeaver.ui.editors.sql.SQLEditor;
import org.jkiss.dbeaver.ui.properties.PropertyTreeViewer;
import org.jkiss.dbeaver.utils.RuntimeUtils;
import org.jkiss.utils.CommonUtils;
import java.util.HashMap;
import java.util.Map;
public class CopySourceCodeHandler extends AbstractHandler implements IElementUpdater {
private static final Log log = Log.getLog(CopySourceCodeHandler.class);
@Override
public Object execute(ExecutionEvent event) throws ExecutionException
{
SQLEditor editor = RuntimeUtils.getObjectAdapter(HandlerUtil.getActiveEditor(event), SQLEditor.class);
if (editor == null) {
return null;
}
ISelection selection = editor.getSelectionProvider().getSelection();
if (selection.isEmpty() || !(selection instanceof TextSelection)) {
return null;
}
TextSelection textSelection = (TextSelection) selection;
if (textSelection.getLength() < 2) {
// Use active query
SQLScriptElement activeQuery = editor.extractActiveQuery();
if (activeQuery != null && activeQuery.getLength() > 1) {
textSelection = new TextSelection(editor.getDocument(), activeQuery.getOffset(), activeQuery.getLength());
}
}
TargetFormatDialog dialog = new TargetFormatDialog(editor, textSelection);
if (dialog.open() != IDialogConstants.OK_ID) {
return null;
}
UIUtils.setClipboardContents(Display.getCurrent(), TextTransfer.getInstance(), dialog.getConvertedText());
return null;
}
@Override
public void updateElement(UIElement element, Map parameters) {
element.setText(SQLEditorMessages.editors_sql_actions_copy_as_source_code);
element.setTooltip(SQLEditorMessages.editors_sql_actions_copy_as_source_code_tip);
}
private static class TargetFormatDialog extends BaseSQLDialog {
private static final String DIALOG_ID = "DBeaver.SQLTargetFormatDialog";//$NON-NLS-1$
private final SQLEditor editor;
private final TextSelection selection;
private PropertyTreeViewer propsViewer;
private StyledText targetText;
private SQLTargetConverterDescriptor curFormat;
private Map<String, Object> options = new HashMap<>();
private String result;
private PropertySourceCustom propertySource;
TargetFormatDialog(SQLEditor editor, TextSelection selection) {
super(editor.getSite(), SQLEditorMessages.sql_editor_menu_choose_format, null);
this.editor = editor;
this.selection = selection;
}
@Override
protected IDialogSettings getDialogBoundsSettings()
{
return UIUtils.getDialogSettings(DIALOG_ID);
}
@Override
protected Composite createDialogArea(Composite parent) {
String formatId = getDialogBoundsSettings().get("format");
if (formatId != null) {
curFormat = SQLConverterRegistry.getInstance().getTargetConverter(formatId);
if (curFormat == null) {
log.warn("Can't find SQL text converter '" + formatId + "'");
}
}
Composite composite = super.createDialogArea(parent);
((GridLayout)composite.getLayout()).numColumns = 2;
{
final SelectionAdapter formatChangeListener = new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (((Button)e.widget).getSelection()) {
if (curFormat == e.widget.getData()) {
return;
}
saveOptions();
curFormat = (SQLTargetConverterDescriptor) e.widget.getData();
loadOptions();
onFormatChange();
}
}
};
Composite formatPanel = UIUtils.createPlaceholder(composite, 1);
GridData gd = new GridData(GridData.FILL_BOTH);
gd.minimumWidth = 200;
formatPanel.setLayoutData(gd);
Group formatsGroup = UIUtils.createControlGroup(formatPanel, SQLEditorMessages.sql_editor_panel_format, 1, GridData.FILL_HORIZONTAL, 0);
for (SQLTargetConverterDescriptor converter : SQLConverterRegistry.getInstance().getTargetConverters()) {
Button formatButton = new Button(formatsGroup, SWT.RADIO);
formatButton.setText(converter.getLabel());
formatButton.setToolTipText(converter.getDescription());
formatButton.setData(converter);
if (curFormat == converter) {
formatButton.setSelection(true);
}
formatButton.addSelectionListener(formatChangeListener);
}
Group settingsGroup = UIUtils.createControlGroup(formatPanel, SQLEditorMessages.pref_page_sql_format_label_settings, 1, GridData.FILL_HORIZONTAL, 0);
settingsGroup.setLayoutData(new GridData(GridData.FILL_BOTH));
propsViewer = new PropertyTreeViewer(settingsGroup, SWT.BORDER);
propsViewer.getTree().addListener(SWT.Modify, new Listener() {
@Override
public void handleEvent(Event event) {
saveOptions();
refreshResult();
targetText.setText(result);
}
});
}
{
Composite previewPanel = new Composite(composite, SWT.NONE);
previewPanel.setLayoutData(new GridData(GridData.FILL_BOTH));
previewPanel.setLayout(new GridLayout(1, false));
SashForm sash = new SashForm(previewPanel, SWT.VERTICAL);
sash.setLayoutData(new GridData(GridData.FILL_BOTH));
createSQLPanel(sash);
Composite targetGroup = UIUtils.createPlaceholder(sash, 1, 5);
targetGroup.setLayoutData(new GridData(GridData.FILL_BOTH));
UIUtils.createControlLabel(targetGroup, SQLEditorMessages.controls_querylog_column_result_name);
targetText = new StyledText(targetGroup, SWT.BORDER | SWT.READ_ONLY | SWT.V_SCROLL | SWT.WRAP);
targetText.setLayoutData(new GridData(GridData.FILL_BOTH));
targetText.setFont(JFaceResources.getFont(JFaceResources.TEXT_FONT));
StyledTextUtils.fillDefaultStyledTextContextMenu(targetText);
}
loadOptions();
onFormatChange();
return composite;
}
private void loadOptions() {
options.clear();
if (curFormat != null) {
IDialogSettings formatSettings = UIUtils.getSettingsSection(getDialogBoundsSettings(), curFormat.getId());
for (DBPPropertyDescriptor prop : curFormat.getProperties()) {
Object propValue = formatSettings.get(CommonUtils.toString(prop.getId()));
if (propValue == null) {
propValue = prop.getDefaultValue();
}
if (propValue != null) {
options.put(CommonUtils.toString(prop.getId()), propValue);
}
}
}
}
private void saveOptions() {
if (propertySource != null && curFormat != null) {
IDialogSettings formatSettings = UIUtils.getSettingsSection(getDialogBoundsSettings(), curFormat.getId());
for (Map.Entry<Object, Object> entry : propertySource.getPropertiesWithDefaults().entrySet()) {
options.put(CommonUtils.toString(entry.getKey()), entry.getValue());
formatSettings.put(CommonUtils.toString(entry.getKey()), CommonUtils.toString(entry.getValue()));
}
}
}
private void onFormatChange() {
if (curFormat != null) {
propertySource = new PropertySourceCustom(curFormat.getProperties(), options);
propsViewer.loadProperties(propertySource);
refreshResult();
} else {
result = "Choose format";
}
targetText.setText(result);
}
private void refreshResult() {
try {
ISQLTextConverter converter = curFormat.createInstance(ISQLTextConverter.class);
result = converter.convertText(
editor.getSQLDialect(),
editor.getSyntaxManager(),
editor.getRuleManager(),
editor.getDocument(),
selection.getOffset(),
selection.getLength(),
options);
} catch (DBException e) {
log.error(e);
result = CommonUtils.notEmpty(e.getMessage());
}
}
@Override
protected void createButtonsForButtonBar(Composite parent)
{
super.createButtonsForButtonBar(parent);
Button okButton = getButton(IDialogConstants.OK_ID);
if (okButton != null) {
okButton.setText(SQLEditorMessages.dialog_view_sql_button_copy);
}
}
String getConvertedText() {
return result;
}
@Override
protected DBCExecutionContext getExecutionContext() {
return editor.getExecutionContext();
}
@Override
protected String getSQLText() {
return this.selection.getText();
}
@Override
protected void okPressed() {
if (curFormat != null) {
saveOptions();
IDialogSettings dialogSettings = getDialogBoundsSettings();
dialogSettings.put("format", curFormat.getId());
}
super.okPressed();
}
}
}
| |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.gluedatabrew.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/UpdateDataset" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UpdateDatasetRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The name of the dataset to be updated.
* </p>
*/
private String name;
/**
* <p>
* The file format of a dataset that is created from an Amazon S3 file or folder.
* </p>
*/
private String format;
private FormatOptions formatOptions;
private Input input;
/**
* <p>
* A set of options that defines how DataBrew interprets an Amazon S3 path of the dataset.
* </p>
*/
private PathOptions pathOptions;
/**
* <p>
* The name of the dataset to be updated.
* </p>
*
* @param name
* The name of the dataset to be updated.
*/
public void setName(String name) {
this.name = name;
}
/**
* <p>
* The name of the dataset to be updated.
* </p>
*
* @return The name of the dataset to be updated.
*/
public String getName() {
return this.name;
}
/**
* <p>
* The name of the dataset to be updated.
* </p>
*
* @param name
* The name of the dataset to be updated.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UpdateDatasetRequest withName(String name) {
setName(name);
return this;
}
/**
* <p>
* The file format of a dataset that is created from an Amazon S3 file or folder.
* </p>
*
* @param format
* The file format of a dataset that is created from an Amazon S3 file or folder.
* @see InputFormat
*/
public void setFormat(String format) {
this.format = format;
}
/**
* <p>
* The file format of a dataset that is created from an Amazon S3 file or folder.
* </p>
*
* @return The file format of a dataset that is created from an Amazon S3 file or folder.
* @see InputFormat
*/
public String getFormat() {
return this.format;
}
/**
* <p>
* The file format of a dataset that is created from an Amazon S3 file or folder.
* </p>
*
* @param format
* The file format of a dataset that is created from an Amazon S3 file or folder.
* @return Returns a reference to this object so that method calls can be chained together.
* @see InputFormat
*/
public UpdateDatasetRequest withFormat(String format) {
setFormat(format);
return this;
}
/**
* <p>
* The file format of a dataset that is created from an Amazon S3 file or folder.
* </p>
*
* @param format
* The file format of a dataset that is created from an Amazon S3 file or folder.
* @return Returns a reference to this object so that method calls can be chained together.
* @see InputFormat
*/
public UpdateDatasetRequest withFormat(InputFormat format) {
this.format = format.toString();
return this;
}
/**
* @param formatOptions
*/
public void setFormatOptions(FormatOptions formatOptions) {
this.formatOptions = formatOptions;
}
/**
* @return
*/
public FormatOptions getFormatOptions() {
return this.formatOptions;
}
/**
* @param formatOptions
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UpdateDatasetRequest withFormatOptions(FormatOptions formatOptions) {
setFormatOptions(formatOptions);
return this;
}
/**
* @param input
*/
public void setInput(Input input) {
this.input = input;
}
/**
* @return
*/
public Input getInput() {
return this.input;
}
/**
* @param input
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UpdateDatasetRequest withInput(Input input) {
setInput(input);
return this;
}
/**
* <p>
* A set of options that defines how DataBrew interprets an Amazon S3 path of the dataset.
* </p>
*
* @param pathOptions
* A set of options that defines how DataBrew interprets an Amazon S3 path of the dataset.
*/
public void setPathOptions(PathOptions pathOptions) {
this.pathOptions = pathOptions;
}
/**
* <p>
* A set of options that defines how DataBrew interprets an Amazon S3 path of the dataset.
* </p>
*
* @return A set of options that defines how DataBrew interprets an Amazon S3 path of the dataset.
*/
public PathOptions getPathOptions() {
return this.pathOptions;
}
/**
* <p>
* A set of options that defines how DataBrew interprets an Amazon S3 path of the dataset.
* </p>
*
* @param pathOptions
* A set of options that defines how DataBrew interprets an Amazon S3 path of the dataset.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UpdateDatasetRequest withPathOptions(PathOptions pathOptions) {
setPathOptions(pathOptions);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getName() != null)
sb.append("Name: ").append(getName()).append(",");
if (getFormat() != null)
sb.append("Format: ").append(getFormat()).append(",");
if (getFormatOptions() != null)
sb.append("FormatOptions: ").append(getFormatOptions()).append(",");
if (getInput() != null)
sb.append("Input: ").append(getInput()).append(",");
if (getPathOptions() != null)
sb.append("PathOptions: ").append(getPathOptions());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof UpdateDatasetRequest == false)
return false;
UpdateDatasetRequest other = (UpdateDatasetRequest) obj;
if (other.getName() == null ^ this.getName() == null)
return false;
if (other.getName() != null && other.getName().equals(this.getName()) == false)
return false;
if (other.getFormat() == null ^ this.getFormat() == null)
return false;
if (other.getFormat() != null && other.getFormat().equals(this.getFormat()) == false)
return false;
if (other.getFormatOptions() == null ^ this.getFormatOptions() == null)
return false;
if (other.getFormatOptions() != null && other.getFormatOptions().equals(this.getFormatOptions()) == false)
return false;
if (other.getInput() == null ^ this.getInput() == null)
return false;
if (other.getInput() != null && other.getInput().equals(this.getInput()) == false)
return false;
if (other.getPathOptions() == null ^ this.getPathOptions() == null)
return false;
if (other.getPathOptions() != null && other.getPathOptions().equals(this.getPathOptions()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
hashCode = prime * hashCode + ((getFormat() == null) ? 0 : getFormat().hashCode());
hashCode = prime * hashCode + ((getFormatOptions() == null) ? 0 : getFormatOptions().hashCode());
hashCode = prime * hashCode + ((getInput() == null) ? 0 : getInput().hashCode());
hashCode = prime * hashCode + ((getPathOptions() == null) ? 0 : getPathOptions().hashCode());
return hashCode;
}
@Override
public UpdateDatasetRequest clone() {
return (UpdateDatasetRequest) super.clone();
}
}
| |
/*
Copyright 2013, Strategic Gains, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.orangerhymelabs.helenus.persistence;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/**
* Supports the concept of a compound identifier. An Identifier is made up of components, which
* are Object instances. The components are kept in order of which they are added.
*
* @author toddf
* @since Aug 29, 2013
*/
public class Identifier
implements Comparable<Identifier>
{
private static final String DB_NAME_SEPARATOR = "_";
private static final String TO_STRING_SEPARATOR = ", ";
private List<Object> components = new ArrayList<Object>();
/**
* Create an empty identifier.
*/
public Identifier()
{
super();
}
public Identifier(Identifier that)
{
this();
if (that == null || that.isEmpty()) return;
add(that.components.toArray());
}
/**
* Create an identifier with the given components. Duplicate instances
* are not added--only one instance of a component will exist in the identifier.
*
* @param components
*/
public Identifier(Object... components)
{
this();
add(components);
}
/**
* Add the given components, in order, to the identifier. Duplicate instances
* are not added--only one instance of a component will exist in the identifier.
*
* @param components
*/
public Identifier add(Object... components)
{
if (components == null) return this;
for (Object component : components)
{
add(component);
}
return this;
}
/**
* Add a single component to the identifier. The given component is added to
* the end of the identifier. Duplicate instances are not added--only one instance
* of a component will exist in the identifier.
*
* @param component
*/
public Identifier add(Object component)
{
if (component == null) return this;
components.add(component);
return this;
}
/**
* Get an unmodifiable list of the components that make up this identifier.
*
* @return an unmodifiable list of components.
*/
public List<Object> components()
{
return Collections.unmodifiableList(components);
}
/**
* Iterate the components of this identifier. Modifications to the underlying components
* are not possible via this iterator.
*
* @return an iterator over the components of this identifier
*/
public Iterator<Object> iterator()
{
return components().iterator();
}
/**
* Indicates the number of components making up this identifier.
*
* @return the number of components in this identifier.
*/
public int size()
{
return components.size();
}
/**
* Check for equality between identifiers. Returns true if the identifiers
* contain equal components. Otherwise, returns false.
*
* @return true if the identifiers are equivalent.
*/
@Override
public boolean equals(Object that)
{
return (compareTo((Identifier) that) == 0);
}
/**
* Returns a hash code for this identifier.
*
* @return an integer hashcode
*/
@Override
public int hashCode()
{
return 1 + components.hashCode();
}
/**
* Compares this identifer to another, returning -1, 0, or 1 depending
* on whether this identifier is less-than, equal-to, or greater-than
* the other identifier, respectively.
*
* @return -1, 0, 1 to indicate less-than, equal-to, or greater-than, respectively.
*/
@SuppressWarnings({
"unchecked", "rawtypes"
})
@Override
public int compareTo(Identifier that)
{
if (that == null) return 1;
if (this.size() < that.size()) return -1;
if (this.size() > that.size()) return 1;
int i = 0;
int result = 0;
while (result == 0 && i < size())
{
Object cThis = this.components.get(i);
Object cThat = that.components.get(i);
if (areComparable(cThis, cThat))
{
result = ((Comparable) cThis).compareTo(((Comparable) cThat));
}
else
{
result = (cThis.toString().compareTo(cThat.toString()));
}
++i;
}
return result;
}
/**
* Returns a string representation of this identifier.
*
* @return a string representation of the identifier.
*/
@Override
public String toString()
{
if (components.isEmpty()) return "";
return (components.size() == 1 ? primaryKey().toString() : "(" + Identifier.toSeparatedString(this, TO_STRING_SEPARATOR) + ")");
}
/**
* Returns the first component of the identifier. Return null if the identifier is empty.
* Equivalent to components().get(0).
*
* @return the first component or null.
*/
public Object primaryKey()
{
return (isEmpty() ? null : components.get(0));
}
/**
* Return true if the identifier has no components.
*
* @return true if the identifier is empty.
*/
public boolean isEmpty()
{
return components.isEmpty();
}
public String toDbName()
{
return toSeparatedString(this, DB_NAME_SEPARATOR);
}
public static String toSeparatedString(Identifier id, String separator)
{
StringBuilder sb = new StringBuilder();
Iterator<Object> iter = id.iterator();
boolean isFirst = true;
while(iter.hasNext())
{
if (!isFirst)
{
sb.append(separator);
}
else
{
isFirst = false;
}
sb.append(iter.next().toString());
}
return sb.toString();
}
private boolean areComparable(Object o1, Object o2)
{
if ((isComparable(o1) && isComparable(o2)) &&
(o1.getClass().isAssignableFrom(o2.getClass()) ||
o2.getClass().isAssignableFrom(o1.getClass())))
{
return true;
}
return false;
}
/**
* Returns true if the object implements Comparable.
* Otherwise, false.
*
* @param object an instance
* @return true if the instance implements Comparable.
*/
private boolean isComparable(Object object)
{
return (object instanceof Comparable);
}
}
| |
package uk.co.streefland.rhys.finalyearproject.core;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.co.streefland.rhys.finalyearproject.message.content.StoredTextMessage;
import uk.co.streefland.rhys.finalyearproject.message.content.TextMessage;
import uk.co.streefland.rhys.finalyearproject.node.KeyId;
import uk.co.streefland.rhys.finalyearproject.node.Node;
import uk.co.streefland.rhys.finalyearproject.operation.SendMessageOperation;
import java.io.IOException;
import java.io.Serializable;
import java.util.*;
/**
* Stores and manages messages on the local node
*/
public class Messages implements Serializable {
private static final long serialVersionUID = 1L;
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private transient LocalNode localNode;
private final Map<KeyId, Long> receivedMessages;
private final Map<KeyId, TextMessage> forwardMessages;
private final Map<String, ArrayList<StoredTextMessage>> userMessages;
private transient ObjectProperty<StoredTextMessage> lastMessage;
private transient ObjectProperty<StoredTextMessage> lastMessageUpdate;
public Messages(LocalNode localNode) {
this.userMessages = new HashMap<>();
this.receivedMessages = new HashMap<>();
this.forwardMessages = new HashMap<>();
init(localNode);
}
/**
* Used to set the transient objects when a saved state has been read
*/
public void init(LocalNode localNode) {
this.localNode = localNode;
this.lastMessage = new SimpleObjectProperty<>();
this.lastMessageUpdate = new SimpleObjectProperty<>();
}
/**
* Handles the process of sending a message to another user
*
* @param message The message to send
* @param target The target user
* @throws IOException
*/
public void sendMessage(String message, User target) throws IOException {
if (message.isEmpty() || localNode.getUsers().getLocalUser() == null) {
return;
}
/* Current timestamp and messageId for message objects */
long createdTime = new Date().getTime() / 1000;
KeyId messageId = new KeyId();
/* Create the StoredTextMessage and set the lastMessage */
StoredTextMessage stm = new StoredTextMessage(messageId, localNode.getUsers().getLocalUser().getUserName(), target.getUserName(), message, SendMessageOperation.Status.PENDING_DELIVERY, createdTime);
lastMessage.set(stm);
/* Add the storedtextmessage to an existing conversation or create a new one if it doesn't already exist */
if (userMessages.putIfAbsent(target.getUserName(), new ArrayList<>(Collections.singletonList(stm))) != null) {
ArrayList<StoredTextMessage> conversation = userMessages.get(target.getUserName());
conversation.add(stm);
}
long start = System.currentTimeMillis();
/* Execute the SendMessageOperation */
SendMessageOperation operation = new SendMessageOperation(localNode, target, messageId, message, createdTime);
operation.execute();
long end = System.currentTimeMillis();
long time = end - start;
logger.info("OUTGOING SMO TOOK: " + time);
if (operation.getUser() != null) {
localNode.getUsers().addUserToCache(operation.getUser(), false);
/* This if statement prevents the race condition */
if (operation.messageStatus() != SendMessageOperation.Status.PENDING_DELIVERY && stm.getMessageStatus() != SendMessageOperation.Status.DELIVERED) {
stm.setMessageStatus(operation.messageStatus());
lastMessageUpdate.set(stm);
}
} else {
logger.error("User {} doesn't exist", target.getUserName());
}
}
/**
* Updates the status of a sent message to delivered
*
* @param userName The recipient of the message
* @param messageId The id of the message to update
*/
public void setDelivered(String userName, KeyId messageId) {
/* Get the conversation */
ArrayList<StoredTextMessage> conversation = userMessages.get(userName);
/* Reverse for loop should be quicker here because message is more likely to be one of the last in the conversation */
for (int i = conversation.size() - 1; i >= 0; i--) {
if (conversation.get(i).getMessageId().equals(messageId)) {
logger.info("Updating message status to delivered");
conversation.get(i).setMessageStatus(SendMessageOperation.Status.DELIVERED);
logger.info("New message status is: " + conversation.get(i).getMessageStatus());
lastMessageUpdate.set(null);
lastMessageUpdate.set(conversation.get(i));
}
}
}
/**
* Store a received message in the receivedMessages HashMap if it doesn't already exist.
* Print the message if it doesn't already exist
*
* @param message The message to store
*/
public void addReceivedMessage(TextMessage message) {
/* Only do anything if we haven't received this message before */
if (receivedMessages.putIfAbsent(message.getMessageId(), message.getCreatedTime()) != null) {
return;
}
Node origin = message.getOrigin();
User originUser = message.getAuthorUser();
String userName = originUser.getUserName();
String messageString = message.getMessage();
System.out.println("Message received from " + userName + ": " + messageString);
/* Create the StoredTextMessage object */
StoredTextMessage stm = new StoredTextMessage(message.getMessageId(), userName, localNode.getUsers().getLocalUser().getUserName(), messageString, message.getCreatedTime());
lastMessage.set(stm);
/* Add the StoredTextMessage to an existing conversation or create a new one if it doesn't already exist */
if (userMessages.putIfAbsent(userName, new ArrayList<>(Collections.singletonList(stm))) != null) {
ArrayList<StoredTextMessage> conversation = userMessages.get(userName);
conversation.add(stm);
}
if (!origin.equals(message.getSource())) {
logger.info("THIS IS A FORWARDED MESSAGE");
/* Add the origin user and node to cache */
localNode.getUsers().addUserToCache(originUser, false);
} else {
localNode.getUsers().addUserToCache(originUser, true);
}
}
/**
* Inserts a message into the forwardMessages HashMap if it doesn't already exist
*
* @param message The message to store
*/
public void addForwardMessage(TextMessage message) {
forwardMessages.putIfAbsent(message.getMessageId(), message);
}
/**
* Removes any forwardMessages and receivedMessages that are older than two days
*/
public void cleanUp() {
long currentTime = new Date().getTime() / 1000; // current time in seconds
/* Cleanup forward messages */
for (Map.Entry<KeyId, TextMessage> entry : forwardMessages.entrySet()) {
// Remove if current time is greater than created time + two days
if (currentTime >= (entry.getValue().getCreatedTime() + Configuration.FORWARD_MESSAGE_EXPIRY)) {
forwardMessages.remove(entry.getKey());
}
}
/* Cleanup received messages */
for (Map.Entry<KeyId, Long> entry : receivedMessages.entrySet()) {
// Remove if current time is greater than created time + two days
if (currentTime >= (entry.getValue() + Configuration.FORWARD_MESSAGE_EXPIRY)) {
receivedMessages.remove(entry.getKey());
}
}
}
public Map<String, ArrayList<StoredTextMessage>> getUserMessages() {
return userMessages;
}
public Map<KeyId, TextMessage> getForwardMessages() {
return forwardMessages;
}
public ObjectProperty<StoredTextMessage> lastMessageProperty() {
return lastMessage;
}
public ObjectProperty<StoredTextMessage> lastMessageUpdateProperty() {
return lastMessageUpdate;
}
}
| |
/*
* Copyright (c) 2008-2015 Citrix Systems, 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.citrix.netscaler.nitro.resource.config.vpn;
import com.citrix.netscaler.nitro.resource.base.*;
import com.citrix.netscaler.nitro.service.nitro_service;
import com.citrix.netscaler.nitro.service.options;
import com.citrix.netscaler.nitro.util.*;
import com.citrix.netscaler.nitro.exception.nitro_exception;
class vpnvserver_aaapreauthenticationpolicy_binding_response extends base_response
{
public vpnvserver_aaapreauthenticationpolicy_binding[] vpnvserver_aaapreauthenticationpolicy_binding;
}
/**
* Binding class showing the aaapreauthenticationpolicy that can be bound to vpnvserver.
*/
public class vpnvserver_aaapreauthenticationpolicy_binding extends base_resource
{
private String policy;
private Long priority;
private Long acttype;
private String name;
private Boolean secondary;
private Boolean groupextraction;
private String gotopriorityexpression;
private String bindpoint;
private Long __count;
/**
* <pre>
* The priority, if any, of the vpn vserver policy.
* </pre>
*/
public void set_priority(long priority) throws Exception {
this.priority = new Long(priority);
}
/**
* <pre>
* The priority, if any, of the vpn vserver policy.
* </pre>
*/
public void set_priority(Long priority) throws Exception{
this.priority = priority;
}
/**
* <pre>
* The priority, if any, of the vpn vserver policy.
* </pre>
*/
public Long get_priority() throws Exception {
return this.priority;
}
/**
* <pre>
* Expression or other value specifying the next policy to evaluate if the current policy evaluates to TRUE. Specify one of the following values:
* NEXT - Evaluate the policy with the next higher priority number.
* END - End policy evaluation.
* USE_INVOCATION_RESULT - Applicable if this policy invokes another policy label. If the final goto in the invoked policy label has a value of END, the evaluation stops. If the final goto is anything other than END, the current policy label performs a NEXT.
* A default syntax or classic expression that evaluates to a number.
If you specify an expression, the number to which it evaluates determines the next policy to evaluate, as follows:
* If the expression evaluates to a higher numbered priority, the policy with that priority is evaluated next.
* If the expression evaluates to the priority of the current policy, the policy with the next higher numbered priority is evaluated next.
* If the expression evaluates to a number that is larger than the largest numbered priority, policy evaluation ends.
An UNDEF event is triggered if:
* The expression is invalid.
* The expression evaluates to a priority number that is numerically lower than the current policy's priority.
* The expression evaluates to a priority number that is between the current policy's priority number (say, 30) and the highest priority number (say, 100), but does not match any configured priority number (for example, the expression evaluates to the number 85). This example assumes that the priority number increments by 10 for every successive policy, and therefore a priority number of 85 does not exist in the policy label.
* </pre>
*/
public void set_gotopriorityexpression(String gotopriorityexpression) throws Exception{
this.gotopriorityexpression = gotopriorityexpression;
}
/**
* <pre>
* Expression or other value specifying the next policy to evaluate if the current policy evaluates to TRUE. Specify one of the following values:
* NEXT - Evaluate the policy with the next higher priority number.
* END - End policy evaluation.
* USE_INVOCATION_RESULT - Applicable if this policy invokes another policy label. If the final goto in the invoked policy label has a value of END, the evaluation stops. If the final goto is anything other than END, the current policy label performs a NEXT.
* A default syntax or classic expression that evaluates to a number.
If you specify an expression, the number to which it evaluates determines the next policy to evaluate, as follows:
* If the expression evaluates to a higher numbered priority, the policy with that priority is evaluated next.
* If the expression evaluates to the priority of the current policy, the policy with the next higher numbered priority is evaluated next.
* If the expression evaluates to a number that is larger than the largest numbered priority, policy evaluation ends.
An UNDEF event is triggered if:
* The expression is invalid.
* The expression evaluates to a priority number that is numerically lower than the current policy's priority.
* The expression evaluates to a priority number that is between the current policy's priority number (say, 30) and the highest priority number (say, 100), but does not match any configured priority number (for example, the expression evaluates to the number 85). This example assumes that the priority number increments by 10 for every successive policy, and therefore a priority number of 85 does not exist in the policy label.
* </pre>
*/
public String get_gotopriorityexpression() throws Exception {
return this.gotopriorityexpression;
}
/**
* <pre>
* The name of the policy, if any, bound to the vpn vserver.
* </pre>
*/
public void set_policy(String policy) throws Exception{
this.policy = policy;
}
/**
* <pre>
* The name of the policy, if any, bound to the vpn vserver.
* </pre>
*/
public String get_policy() throws Exception {
return this.policy;
}
/**
* <pre>
* Bind the Authentication policy to a tertiary chain which will be used only for group extraction. The user will not authenticate against this server, and this will only be called if primary and/or secondary authentication has succeeded.
* </pre>
*/
public void set_groupextraction(boolean groupextraction) throws Exception {
this.groupextraction = new Boolean(groupextraction);
}
/**
* <pre>
* Bind the Authentication policy to a tertiary chain which will be used only for group extraction. The user will not authenticate against this server, and this will only be called if primary and/or secondary authentication has succeeded.
* </pre>
*/
public void set_groupextraction(Boolean groupextraction) throws Exception{
this.groupextraction = groupextraction;
}
/**
* <pre>
* Bind the Authentication policy to a tertiary chain which will be used only for group extraction. The user will not authenticate against this server, and this will only be called if primary and/or secondary authentication has succeeded.
* </pre>
*/
public Boolean get_groupextraction() throws Exception {
return this.groupextraction;
}
/**
* <pre>
* Name of the virtual server.<br> Minimum length = 1
* </pre>
*/
public void set_name(String name) throws Exception{
this.name = name;
}
/**
* <pre>
* Name of the virtual server.<br> Minimum length = 1
* </pre>
*/
public String get_name() throws Exception {
return this.name;
}
/**
* <pre>
* Bind the authentication policy as the secondary policy to use in a two-factor configuration. A user must then authenticate not only via a primary authentication method but also via a secondary authentication method. User groups are aggregated across both. The user name must be exactly the same for both authentication methods, but they can require different passwords.
* </pre>
*/
public void set_secondary(boolean secondary) throws Exception {
this.secondary = new Boolean(secondary);
}
/**
* <pre>
* Bind the authentication policy as the secondary policy to use in a two-factor configuration. A user must then authenticate not only via a primary authentication method but also via a secondary authentication method. User groups are aggregated across both. The user name must be exactly the same for both authentication methods, but they can require different passwords.
* </pre>
*/
public void set_secondary(Boolean secondary) throws Exception{
this.secondary = secondary;
}
/**
* <pre>
* Bind the authentication policy as the secondary policy to use in a two-factor configuration. A user must then authenticate not only via a primary authentication method but also via a secondary authentication method. User groups are aggregated across both. The user name must be exactly the same for both authentication methods, but they can require different passwords.
* </pre>
*/
public Boolean get_secondary() throws Exception {
return this.secondary;
}
/**
* <pre>
* Bind point to which to bind the policy. Applies only to rewrite and cache policies. If you do not set this parameter, the policy is bound to REQ_DEFAULT or RES_DEFAULT, depending on whether the policy rule is a response-time or a request-time expression.<br> Possible values = REQUEST, RESPONSE, ICA_REQUEST, OTHERTCP_REQUEST
* </pre>
*/
public void set_bindpoint(String bindpoint) throws Exception{
this.bindpoint = bindpoint;
}
/**
* <pre>
* Bind point to which to bind the policy. Applies only to rewrite and cache policies. If you do not set this parameter, the policy is bound to REQ_DEFAULT or RES_DEFAULT, depending on whether the policy rule is a response-time or a request-time expression.<br> Possible values = REQUEST, RESPONSE, ICA_REQUEST, OTHERTCP_REQUEST
* </pre>
*/
public String get_bindpoint() throws Exception {
return this.bindpoint;
}
/**
* <pre>
* .
* </pre>
*/
public Long get_acttype() throws Exception {
return this.acttype;
}
/**
* <pre>
* converts nitro response into object and returns the object array in case of get request.
* </pre>
*/
protected base_resource[] get_nitro_response(nitro_service service, String response) throws Exception{
vpnvserver_aaapreauthenticationpolicy_binding_response result = (vpnvserver_aaapreauthenticationpolicy_binding_response) service.get_payload_formatter().string_to_resource(vpnvserver_aaapreauthenticationpolicy_binding_response.class, response);
if(result.errorcode != 0) {
if (result.errorcode == 444) {
service.clear_session();
}
if(result.severity != null)
{
if (result.severity.equals("ERROR"))
throw new nitro_exception(result.message,result.errorcode);
}
else
{
throw new nitro_exception(result.message,result.errorcode);
}
}
return result.vpnvserver_aaapreauthenticationpolicy_binding;
}
/**
* <pre>
* Returns the value of object identifier argument
* </pre>
*/
protected String get_object_name() {
return this.name;
}
public static base_response add(nitro_service client, vpnvserver_aaapreauthenticationpolicy_binding resource) throws Exception {
vpnvserver_aaapreauthenticationpolicy_binding updateresource = new vpnvserver_aaapreauthenticationpolicy_binding();
updateresource.name = resource.name;
updateresource.policy = resource.policy;
updateresource.priority = resource.priority;
updateresource.secondary = resource.secondary;
updateresource.groupextraction = resource.groupextraction;
updateresource.gotopriorityexpression = resource.gotopriorityexpression;
updateresource.bindpoint = resource.bindpoint;
return updateresource.update_resource(client);
}
public static base_responses add(nitro_service client, vpnvserver_aaapreauthenticationpolicy_binding resources[]) throws Exception {
base_responses result = null;
if (resources != null && resources.length > 0) {
vpnvserver_aaapreauthenticationpolicy_binding updateresources[] = new vpnvserver_aaapreauthenticationpolicy_binding[resources.length];
for (int i=0;i<resources.length;i++){
updateresources[i] = new vpnvserver_aaapreauthenticationpolicy_binding();
updateresources[i].name = resources[i].name;
updateresources[i].policy = resources[i].policy;
updateresources[i].priority = resources[i].priority;
updateresources[i].secondary = resources[i].secondary;
updateresources[i].groupextraction = resources[i].groupextraction;
updateresources[i].gotopriorityexpression = resources[i].gotopriorityexpression;
updateresources[i].bindpoint = resources[i].bindpoint;
}
result = update_bulk_request(client, updateresources);
}
return result;
}
public static base_response delete(nitro_service client, vpnvserver_aaapreauthenticationpolicy_binding resource) throws Exception {
vpnvserver_aaapreauthenticationpolicy_binding deleteresource = new vpnvserver_aaapreauthenticationpolicy_binding();
deleteresource.name = resource.name;
deleteresource.policy = resource.policy;
deleteresource.secondary = resource.secondary;
deleteresource.groupextraction = resource.groupextraction;
deleteresource.bindpoint = resource.bindpoint;
return deleteresource.delete_resource(client);
}
public static base_responses delete(nitro_service client, vpnvserver_aaapreauthenticationpolicy_binding resources[]) throws Exception {
base_responses result = null;
if (resources != null && resources.length > 0) {
vpnvserver_aaapreauthenticationpolicy_binding deleteresources[] = new vpnvserver_aaapreauthenticationpolicy_binding[resources.length];
for (int i=0;i<resources.length;i++){
deleteresources[i] = new vpnvserver_aaapreauthenticationpolicy_binding();
deleteresources[i].name = resources[i].name;
deleteresources[i].policy = resources[i].policy;
deleteresources[i].secondary = resources[i].secondary;
deleteresources[i].groupextraction = resources[i].groupextraction;
deleteresources[i].bindpoint = resources[i].bindpoint;
}
result = delete_bulk_request(client, deleteresources);
}
return result;
}
/**
* Use this API to fetch vpnvserver_aaapreauthenticationpolicy_binding resources of given name .
*/
public static vpnvserver_aaapreauthenticationpolicy_binding[] get(nitro_service service, String name) throws Exception{
vpnvserver_aaapreauthenticationpolicy_binding obj = new vpnvserver_aaapreauthenticationpolicy_binding();
obj.set_name(name);
vpnvserver_aaapreauthenticationpolicy_binding response[] = (vpnvserver_aaapreauthenticationpolicy_binding[]) obj.get_resources(service);
return response;
}
/**
* Use this API to fetch filtered set of vpnvserver_aaapreauthenticationpolicy_binding resources.
* filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
*/
public static vpnvserver_aaapreauthenticationpolicy_binding[] get_filtered(nitro_service service, String name, String filter) throws Exception{
vpnvserver_aaapreauthenticationpolicy_binding obj = new vpnvserver_aaapreauthenticationpolicy_binding();
obj.set_name(name);
options option = new options();
option.set_filter(filter);
vpnvserver_aaapreauthenticationpolicy_binding[] response = (vpnvserver_aaapreauthenticationpolicy_binding[]) obj.getfiltered(service, option);
return response;
}
/**
* Use this API to fetch filtered set of vpnvserver_aaapreauthenticationpolicy_binding resources.
* set the filter parameter values in filtervalue object.
*/
public static vpnvserver_aaapreauthenticationpolicy_binding[] get_filtered(nitro_service service, String name, filtervalue[] filter) throws Exception{
vpnvserver_aaapreauthenticationpolicy_binding obj = new vpnvserver_aaapreauthenticationpolicy_binding();
obj.set_name(name);
options option = new options();
option.set_filter(filter);
vpnvserver_aaapreauthenticationpolicy_binding[] response = (vpnvserver_aaapreauthenticationpolicy_binding[]) obj.getfiltered(service, option);
return response;
}
/**
* Use this API to count vpnvserver_aaapreauthenticationpolicy_binding resources configued on NetScaler.
*/
public static long count(nitro_service service, String name) throws Exception{
vpnvserver_aaapreauthenticationpolicy_binding obj = new vpnvserver_aaapreauthenticationpolicy_binding();
obj.set_name(name);
options option = new options();
option.set_count(true);
vpnvserver_aaapreauthenticationpolicy_binding response[] = (vpnvserver_aaapreauthenticationpolicy_binding[]) obj.get_resources(service,option);
if (response != null) {
return response[0].__count;
}
return 0;
}
/**
* Use this API to count the filtered set of vpnvserver_aaapreauthenticationpolicy_binding resources.
* filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
*/
public static long count_filtered(nitro_service service, String name, String filter) throws Exception{
vpnvserver_aaapreauthenticationpolicy_binding obj = new vpnvserver_aaapreauthenticationpolicy_binding();
obj.set_name(name);
options option = new options();
option.set_count(true);
option.set_filter(filter);
vpnvserver_aaapreauthenticationpolicy_binding[] response = (vpnvserver_aaapreauthenticationpolicy_binding[]) obj.getfiltered(service, option);
if (response != null) {
return response[0].__count;
}
return 0;
}
/**
* Use this API to count the filtered set of vpnvserver_aaapreauthenticationpolicy_binding resources.
* set the filter parameter values in filtervalue object.
*/
public static long count_filtered(nitro_service service, String name, filtervalue[] filter) throws Exception{
vpnvserver_aaapreauthenticationpolicy_binding obj = new vpnvserver_aaapreauthenticationpolicy_binding();
obj.set_name(name);
options option = new options();
option.set_count(true);
option.set_filter(filter);
vpnvserver_aaapreauthenticationpolicy_binding[] response = (vpnvserver_aaapreauthenticationpolicy_binding[]) obj.getfiltered(service, option);
if (response != null) {
return response[0].__count;
}
return 0;
}
public static class bindpointEnum {
public static final String REQUEST = "REQUEST";
public static final String RESPONSE = "RESPONSE";
public static final String ICA_REQUEST = "ICA_REQUEST";
public static final String OTHERTCP_REQUEST = "OTHERTCP_REQUEST";
}
}
| |
/**
* JBoss, Home of Professional Open Source
* Copyright Red Hat, Inc., and individual contributors.
*
* 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.jboss.aerogear.unifiedpush.jpa;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import org.jboss.aerogear.unifiedpush.api.AndroidVariant;
import org.jboss.aerogear.unifiedpush.api.Installation;
import org.jboss.aerogear.unifiedpush.api.PushApplication;
import org.jboss.aerogear.unifiedpush.api.VariantType;
import org.jboss.aerogear.unifiedpush.dao.PushApplicationDao;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import net.jakubholy.dbunitexpress.EmbeddedDbTesterRule;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = { JPAConfig.class })
@Transactional
public class PushApplicationDaoTest {
@Inject
private EntityManager entityManager;
@Inject
private PushApplicationDao pushApplicationDao;
@Rule
public EmbeddedDbTesterRule testDb = new EmbeddedDbTesterRule("PushApplications.xml");
@Test
public void findAllForDeveloper() throws Exception {
assertThat(pushApplicationDao.findAllForDeveloper("Admin", 0, 10).getResultList()).hasSize(2);
assertThat(pushApplicationDao.findAllForDeveloper("Dave The Drummer", 0, 10).getResultList()).hasSize(1);
assertThat(pushApplicationDao.findAllForDeveloper("Dave The Drummer", 0, 10).getResultList()).extracting("name").containsOnly("Push App 3");
assertThat(pushApplicationDao.findAllForDeveloper("Admin The Drummer", 0, 10).getResultList()).isEmpty();
assertThat(pushApplicationDao.getNumberOfPushApplicationsForDeveloper("Dave The Drummer")).isEqualTo(1);
assertThat(pushApplicationDao.getNumberOfPushApplicationsForDeveloper("Admin")).isEqualTo(2);
// check all:
assertThat(pushApplicationDao.getNumberOfPushApplicationsForDeveloper()).isEqualTo(3);
assertThat(pushApplicationDao.findAll(0, 10).getAggregate().getCount()).isEqualTo(3);
// check exact:
assertThat(pushApplicationDao.findAllByPushApplicationID("123").getName()).isEqualTo("Push App 2");
}
@Test
public void findAllIDsForDeveloper() {
assertThat(pushApplicationDao.findAllPushApplicationIDsForDeveloper("Admin")).hasSize(2);
assertThat(pushApplicationDao.findAllPushApplicationIDsForDeveloper("Dave The Drummer")).hasSize(1);
assertThat(pushApplicationDao.findAllPushApplicationIDsForDeveloper("Admin The Drummer")).isEmpty();
// check all:
assertThat(pushApplicationDao.getNumberOfPushApplicationsForDeveloper()).isEqualTo(3);
assertThat(pushApplicationDao.findAll(0, 10).getAggregate().getCount()).isEqualTo(3);
}
@Test
public void findByPushApplicationIDForDeveloper() {
final String pushApplicationID1 = "888";
assertThat(pushApplicationDao.findByPushApplicationIDForDeveloper(pushApplicationID1, "Admin")).isNotNull();
assertThat(pushApplicationDao.findByPushApplicationIDForDeveloper(pushApplicationID1, "Admin").getName()).isEqualTo("Push App 1");
assertThat(pushApplicationDao.findByPushApplicationIDForDeveloper("1234", "Admin")).isNull();
assertThat(pushApplicationDao.findByPushApplicationIDForDeveloper(pushApplicationID1, "FooBar")).isNull();
}
@Test
public void findByPushApplicationID() {
final String pushApplicationID1 = "888";
assertThat(pushApplicationDao.findByPushApplicationID(pushApplicationID1)).isNotNull();
assertThat(pushApplicationDao.findByPushApplicationID(pushApplicationID1).getName()).isEqualTo("Push App 1");
assertThat(pushApplicationDao.findByPushApplicationID("13245632")).isNull();
}
@Test
public void updatePushApplication() {
final String pushApplicationID1 = "888";
final PushApplication pushApplication1 = pushApplicationDao.findByPushApplicationID(pushApplicationID1);
assertThat(pushApplication1).isNotNull();
assertThat(pushApplication1.getName()).isEqualTo("Push App 1");
pushApplication1.setName("Cool Push App 1");
pushApplicationDao.update(pushApplication1);
assertThat(pushApplicationDao.findByPushApplicationID(pushApplicationID1)).isNotNull();
assertThat(pushApplicationDao.findByPushApplicationID(pushApplicationID1).getName()).isEqualTo("Cool Push App 1");
}
@Test
public void updateAndDeletePushApplication() {
final String pushApplicationID1 = "888";
assertThat(pushApplicationDao.findByPushApplicationID(pushApplicationID1)).isNotNull();
assertThat(pushApplicationDao.findByPushApplicationID(pushApplicationID1).getName()).isEqualTo("Push App 1");
final PushApplication pushApplication1 = pushApplicationDao.findByPushApplicationID(pushApplicationID1);
pushApplication1.setName("Cool Push App 1");
pushApplicationDao.update(pushApplication1);
assertThat(pushApplicationDao.findByPushApplicationID(pushApplicationID1)).isNotNull();
assertThat(pushApplicationDao.findByPushApplicationID(pushApplicationID1).getName()).isEqualTo("Cool Push App 1");
pushApplicationDao.delete(pushApplication1);
assertThat(pushApplicationDao.findByPushApplicationID(pushApplicationID1)).isNull();
}
@Test
public void pushApplicationIDUnmodifiedAfterUpdate() {
final String pushApplicationID1 = "888";
assertThat(pushApplicationDao.findByPushApplicationID(pushApplicationID1)).isNotNull();
assertThat(pushApplicationDao.findByPushApplicationID(pushApplicationID1).getName()).isEqualTo("Push App 1");
final PushApplication pushApplication1 = pushApplicationDao.findByPushApplicationID(pushApplicationID1);
pushApplication1.setName("Cool Push App 1");
pushApplicationDao.update(pushApplication1);
assertThat(pushApplicationDao.findByPushApplicationID(pushApplicationID1)).isNotNull();
assertThat(pushApplicationDao.findByPushApplicationID(pushApplicationID1).getPushApplicationID()).isEqualTo(pushApplicationID1);
}
@Test
public void primaryKeyUnmodifiedAfterUpdate() {
final String id = "1";
PushApplication pa = pushApplicationDao.find(id);
assertThat(pa.getId()).isEqualTo(id);
final PushApplication pushApplication1 = pushApplicationDao.findByPushApplicationID(pa.getPushApplicationID());
pushApplication1.setName("Cool Push App 1");
pushApplicationDao.update(pushApplication1);
entityManager.flush();
entityManager.clear();
pa = pushApplicationDao.find(id);
assertThat(pa.getName()).isEqualTo("Cool Push App 1");
}
@Test
public void deletePushApplicationIncludingVariantAndInstallations() {
final String id = "888";
final PushApplication pa = pushApplicationDao.findByPushApplicationID(id);
pushApplicationDao.delete(pa);
// flush to be sure that it's in the database
entityManager.flush();
// clear the cache otherwise finding the entity will not perform a select but get the entity from cache
entityManager.clear();
// Installation should be gone:
assertThat(entityManager.find(Installation.class, "1")).isNull();
// Variant should be gone:
assertThat(entityManager.find(AndroidVariant.class, "1")).isNull();
// PushApp should be gone:
assertThat(pushApplicationDao.find(id)).isNull();
}
@Test
public void shouldCountInstallations() {
final Map<String, Long> result = pushApplicationDao.countInstallationsByType("888");
assertThat(result).isNotEmpty();
assertThat(result.get("1")).isEqualTo(2L);
assertThat(result.get("3")).isEqualTo(1L);
assertThat(result.get(VariantType.ANDROID.getTypeName())).isEqualTo(2L);
}
@Test
public void shouldFindPushApplicationNameAndIDBasedOnVariantID() {
//when
final List<PushApplication> applications = pushApplicationDao.findByVariantIds(Arrays.asList("1"));
//then
assertThat(applications).isNotEmpty();
assertThat(applications.size()).isEqualTo(1);
final PushApplication application = applications.iterator().next();
assertThat(application.getName()).isEqualTo("Push App 1");
assertThat(application.getVariants()).isNotEmpty();
assertThat(application.getVariants().size()).isEqualTo(1);
assertThat(application.getVariants().iterator().next().getId()).isEqualTo("1");
}
@Test(expected = PersistenceException.class)
public void failDuplicatedApplicationName() {
//when
PushApplication application = pushApplicationDao.findByPushApplicationName("Push App 1");
//then
assertThat(application).isNotNull();
assertThat(application.getName()).isEqualTo("Push App 1");
PushApplication application2 = new PushApplication();
application2.setId("100");
application2.setName(application.getName());
pushApplicationDao.create(application2);
pushApplicationDao.flushAndClear();
}
}
| |
/*
* Copyright (c) 2010-2017, KNOPFLERFISH project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* - Neither the name of the KNOPFLERFISH project nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT 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 org.knopflerfish.bundle.component;
import java.util.Collection;
import java.util.Collections;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.service.component.ComponentConstants;
/**
* This class needs to be a Dictionary and a Map.
* TBD, check that this class is immutable
*/
class PropertyDictionary extends Dictionary<String, Object>
implements Map<String, Object>, Comparable<Map<String, Object>>
{
final private Hashtable<String,Object> props;
/**
*
*/
PropertyDictionary(Component comp,
Map<String,Object> cm,
Dictionary<String,Object> instance,
boolean service) {
props = new Hashtable<String,Object>();
final ComponentDescription cd = comp.compDesc;
addDict(cd.getProperties(), service);
if (cm != null) {
addDict(cm, service);
}
if (instance != null) {
addDict(instance, service);
}
props.put(ComponentConstants.COMPONENT_ID, comp.id);
props.put(ComponentConstants.COMPONENT_NAME, cd.getName());
}
/**
*
*/
PropertyDictionary(ServiceReference<?> sr) {
props = new Hashtable<String,Object>();
for (String key : sr.getPropertyKeys()) {
props.put(key, sr.getProperty(key));
}
}
/**
*
*/
@Override
public Enumeration<Object> elements() {
return props.elements();
}
/**
*
*/
@Override
public boolean equals(Object o) {
return props.equals(o);
}
/**
*
*/
@Override
public Object get(Object key) {
return props.get(key);
}
/**
*
*/
@Override
public int hashCode() {
return props.hashCode();
}
/**
*
*/
@Override
public boolean isEmpty() {
return props.isEmpty();
}
/**
*
*/
@Override
public Enumeration<String> keys() {
return props.keys();
}
/**
*
*/
@Override
public Object put(String key, Object value) {
throw new UnsupportedOperationException();
}
/**
*
*/
@Override
public Object remove(Object key) {
throw new UnsupportedOperationException();
}
/**
*
*/
@Override
public int size() {
return props.size();
}
/**
*
*/
@Override
public void clear() {
throw new UnsupportedOperationException();
}
/**
*
*/
@Override
public boolean containsKey(Object key) {
return props.containsKey(key);
}
/**
*
*/
@Override
public boolean containsValue(Object value) {
return props.containsValue(value);
}
/**
*
*/
@Override
public Set<Map.Entry<String, Object>> entrySet() {
return Collections.unmodifiableSet(props.entrySet());
}
/**
*
*/
@Override
public Set<String> keySet() {
return Collections.unmodifiableSet(props.keySet());
}
/**
*
*/
@Override
public void putAll(Map<? extends String, ?> m) {
throw new UnsupportedOperationException();
}
/**
*
*/
@Override
public Collection<Object> values() {
return Collections.unmodifiableCollection(props.values());
}
/**
*
*/
@Override
public int compareTo(Map<String, Object> that) {
final Object ro1 = this.get(Constants.SERVICE_RANKING);
final Object ro2 = that.get(Constants.SERVICE_RANKING);
final int r1 = (ro1 instanceof Integer) ? ((Integer)ro1).intValue() : 0;
final int r2 = (ro2 instanceof Integer) ? ((Integer)ro2).intValue() : 0;
if (r1 != r2) {
// use ranking if ranking differs
return r1 < r2 ? -1 : 1;
} else {
final Long id1 = (Long)this.get(Constants.SERVICE_ID);
Object id2 = that.get(Constants.SERVICE_ID);
if (!(id2 instanceof Long)) {
id2 = new Long(0);
}
// otherwise compare using IDs,
// is less than if it has a higher ID.
return -id1.compareTo((Long)id2);
}
}
/**
*
*/
Map<String,Object> getMap() {
return new HashMap<String, Object>(props);
}
//
// Private methods
//
/**
* Add all properties in the given properties object to the props dictionary.
*
* @param m The properties object to insert the contents of.
* @param service If the component is a service skip non-public properties.
* I.e., those with a key starting with '.'.
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
private void addDict(Map m, boolean service) {
for (final Iterator<Map.Entry> i = m.entrySet().iterator(); i.hasNext(); ) {
final Map.Entry<String, Object> e = i.next();
addDict(e.getKey(), e.getValue(), service);
}
}
/**
* Add all properties in the given dictionary to the props dictionary.
*
* @param properties The dictionary to insert the contents of.
* @param service If the component is a service skip non-public properties.
* I.e., those with a key starting with '.'.
*/
private void addDict(Dictionary<String,Object> d, boolean service) {
for (final Enumeration<String> e = d.keys(); e.hasMoreElements(); ) {
final String key = e.nextElement();
addDict(key, d.get(key), service);
}
}
/**
* Add a property in the given dictionary to the props dictionary.
*
* @param key The key of the property to insert.
* @param value The value of the property to insert.
* @param service If the component is a service skip non-public properties.
* I.e., those with a key starting with '.'.
*/
private void addDict(String key, Object value, boolean service) {
if (!service || !key.startsWith(".")) {
props.put(key, value);
}
}
}
| |
/**
* 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.jinn.coca.benchmark.thrift.util.mem;
import com.sun.jna.Pointer;
import sun.misc.Unsafe;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
/**
* An off-heap region of memory that must be manually free'd when no longer needed.
*/
class Memory
{
private static final Unsafe unsafe;
static
{
try
{
Field field = Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
unsafe = (Unsafe) field.get(null);
}
catch (Exception e)
{
throw new AssertionError(e);
}
}
protected long peer, size; // size could be changed by 'reallocate'
protected Memory(long size)
{
this(unsafe.allocateMemory(size), size);
}
protected Memory(long peer, long size)
{
this.peer = peer;
this.size = size;
}
public static Memory allocate(long bytes)
{
if (bytes < 0)
throw new IllegalArgumentException();
return new Memory(bytes);
}
public static Memory wrap(long peer, int limit)
{
return new Memory(peer, limit);
}
public void setByte(long offset, byte b)
{
checkPosition(offset);
setByteUnsafe(offset, b);
}
void setByteUnsafe(long offset, byte b)
{
unsafe.putByte(peer + offset, b);
}
public void setMemory(long offset, long bytes, byte b)
{
// check if the last element will fit into the memory
checkPosition(offset + bytes - 1);
unsafe.setMemory(peer + offset, bytes, b);
}
void copyMemory(long offset, long dstAddr, long bytes)
{
if (bytes > size - offset)
throw new IllegalArgumentException();
unsafe.copyMemory(peer + offset, dstAddr, bytes);
}
public void setLong(long offset, long l)
{
checkPosition(offset);
unsafe.putLong(peer + offset, l);
}
/**
* Transfers count bytes from buffer to Memory
*
* @param memoryOffset start offset in the memory
* @param buffer the data buffer
* @param bufferOffset start offset of the buffer
* @param count number of bytes to transfer
*/
public void setBytes(long memoryOffset, byte[] buffer, int bufferOffset, int count)
{
if (buffer == null)
throw new NullPointerException();
else if (bufferOffset < 0
|| count < 0
|| bufferOffset + count > buffer.length)
throw new IndexOutOfBoundsException();
else if (count == 0)
return;
checkPosition(memoryOffset);
long end = memoryOffset + count;
checkPosition(end - 1);
while (memoryOffset < end)
{
unsafe.putByte(peer + memoryOffset, buffer[bufferOffset]);
memoryOffset++;
bufferOffset++;
}
}
/**
* Transfers count bytes from buffer to Memory
*
* @param memoryOffset start offset in the memory
* @param buffer the data buffer
*/
public void setBytes(long memoryOffset, ByteBuffer buffer)
{
if (buffer == null)
throw new NullPointerException();
else if (buffer.remaining() == 0)
return;
int bufferOffset = buffer.position();
checkPosition(memoryOffset);
long end = memoryOffset + buffer.remaining();
checkPosition(end - 1);
while (memoryOffset < end)
{
unsafe.putByte(peer + memoryOffset, buffer.get(bufferOffset));
memoryOffset++;
bufferOffset++;
}
}
public byte getByte(long offset)
{
checkPosition(offset);
return getByteUnsafe(offset);
}
byte getByteUnsafe(long offset)
{
return unsafe.getByte(peer + offset);
}
public long getLong(long offset)
{
checkPosition(offset);
return unsafe.getLong(peer + offset);
}
/**
* Transfers count bytes from Memory starting at memoryOffset to buffer starting at bufferOffset
*
* @param memoryOffset start offset in the memory
* @param buffer the data buffer
* @param bufferOffset start offset of the buffer
* @param count number of bytes to transfer
*/
public void getBytes(long memoryOffset, byte[] buffer, int bufferOffset, int count)
{
if (buffer == null)
throw new NullPointerException();
else if (bufferOffset < 0 || count < 0 || count > buffer.length - bufferOffset)
throw new IndexOutOfBoundsException();
else if (count == 0)
return;
checkPosition(memoryOffset);
long end = memoryOffset + count;
checkPosition(end - 1);
while (memoryOffset < end)
{
buffer[bufferOffset++] = unsafe.getByte(peer + memoryOffset);
memoryOffset++;
}
}
private void checkPosition(long offset)
{
assert peer != 0 : "Memory was freed";
assert offset >= 0 && offset < size : "Illegal offset: " + offset + ", size: " + size;
}
public long getPeer()
{
return peer;
}
public Memory reallocate(int newSize)
{
peer = unsafe.reallocateMemory(peer, newSize);
size = newSize;
return this;
}
public void free()
{
assert peer != 0;
unsafe.freeMemory(peer);
peer = 0;
}
public long size()
{
return size;
}
@Override
public boolean equals(Object o)
{
if (this == o)
return true;
if (!(o instanceof Memory))
return false;
Memory b = (Memory) o;
if (peer == b.peer && size == b.size)
return true;
return false;
}
public String toString()
{
return new String(toBytes());
}
public String toString(String enc) throws UnsupportedEncodingException
{
return new String(toBytes(), enc);
}
public byte[] toBytes()
{
return toBytes((int) size);
}
public byte[] toBytes(int size)
{
assert size <= (int) this.size;
byte[] buf = new byte[size];
for (int i = 0; i < size; i++)
buf[i] = getByte(i);
return buf;
}
public ByteBuffer toByteBuffer()
{
ByteBuffer buffer = new Pointer(peer).getByteBuffer(0, size);
if (buffer != null)
return buffer;
buffer = ByteBuffer.allocate((int) size);
for (int i = 0; i < size; i++)
buffer.put(getByteUnsafe(i));
buffer.flip();
return buffer;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.cache;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteException;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.internal.cluster.ClusterTopologyCheckedException;
import org.apache.ignite.internal.managers.communication.GridMessageListener;
import org.apache.ignite.internal.managers.deployment.GridDeploymentInfo;
import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtLockRequest;
import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtLockResponse;
import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxPrepareRequest;
import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxPrepareResponse;
import org.apache.ignite.internal.processors.cache.distributed.dht.GridPartitionedGetFuture;
import org.apache.ignite.internal.processors.cache.distributed.dht.atomic.GridDhtAtomicUpdateRequest;
import org.apache.ignite.internal.processors.cache.distributed.dht.atomic.GridDhtAtomicUpdateResponse;
import org.apache.ignite.internal.processors.cache.distributed.dht.atomic.GridNearAtomicUpdateRequest;
import org.apache.ignite.internal.processors.cache.distributed.dht.atomic.GridNearAtomicUpdateResponse;
import org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtForceKeysRequest;
import org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtForceKeysResponse;
import org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionSupplyMessage;
import org.apache.ignite.internal.processors.cache.distributed.near.GridNearGetFuture;
import org.apache.ignite.internal.processors.cache.distributed.near.GridNearGetRequest;
import org.apache.ignite.internal.processors.cache.distributed.near.GridNearGetResponse;
import org.apache.ignite.internal.processors.cache.distributed.near.GridNearLockRequest;
import org.apache.ignite.internal.processors.cache.distributed.near.GridNearLockResponse;
import org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxPrepareRequest;
import org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxPrepareResponse;
import org.apache.ignite.internal.util.F0;
import org.apache.ignite.internal.util.GridLeanSet;
import org.apache.ignite.internal.util.GridSpinReadWriteLock;
import org.apache.ignite.internal.util.future.GridFinishedFuture;
import org.apache.ignite.internal.util.lang.GridPlainRunnable;
import org.apache.ignite.internal.util.typedef.CI1;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.P1;
import org.apache.ignite.internal.util.typedef.X;
import org.apache.ignite.internal.util.typedef.internal.CU;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgniteBiInClosure;
import org.apache.ignite.lang.IgnitePredicate;
import org.jetbrains.annotations.Nullable;
import org.jsr166.ConcurrentHashMap8;
import static org.apache.ignite.internal.GridTopic.TOPIC_CACHE;
/**
* Cache communication manager.
*/
public class GridCacheIoManager extends GridCacheSharedManagerAdapter {
/** Message ID generator. */
private static final AtomicLong idGen = new AtomicLong();
/** Delay in milliseconds between retries. */
private long retryDelay;
/** Number of retries using to send messages. */
private int retryCnt;
/** Indexed class handlers. */
private Map<Integer, IgniteBiInClosure[]> idxClsHandlers = new HashMap<>();
/** Handler registry. */
private ConcurrentMap<ListenerKey, IgniteBiInClosure<UUID, GridCacheMessage>>
clsHandlers = new ConcurrentHashMap8<>();
/** Ordered handler registry. */
private ConcurrentMap<Object, IgniteBiInClosure<UUID, ? extends GridCacheMessage>> orderedHandlers =
new ConcurrentHashMap8<>();
/** Stopping flag. */
private boolean stopping;
/** Error flag. */
private final AtomicBoolean startErr = new AtomicBoolean();
/** Mutex. */
private final GridSpinReadWriteLock rw = new GridSpinReadWriteLock();
/** Deployment enabled. */
private boolean depEnabled;
/** Message listener. */
private GridMessageListener lsnr = new GridMessageListener() {
@Override public void onMessage(final UUID nodeId, Object msg) {
if (log.isDebugEnabled())
log.debug("Received unordered cache communication message [nodeId=" + nodeId +
", locId=" + cctx.localNodeId() + ", msg=" + msg + ']');
final GridCacheMessage cacheMsg = (GridCacheMessage)msg;
IgniteInternalFuture<?> fut = null;
if (cacheMsg.partitionExchangeMessage()) {
long locTopVer = cctx.discovery().topologyVersion();
long rmtTopVer = cacheMsg.topologyVersion().topologyVersion();
if (locTopVer < rmtTopVer) {
if (log.isDebugEnabled())
log.debug("Received message has higher topology version [msg=" + msg +
", locTopVer=" + locTopVer + ", rmtTopVer=" + rmtTopVer + ']');
fut = cctx.discovery().topologyFuture(rmtTopVer);
}
}
else {
AffinityTopologyVersion locAffVer = cctx.exchange().readyAffinityVersion();
AffinityTopologyVersion rmtAffVer = cacheMsg.topologyVersion();
if (locAffVer.compareTo(rmtAffVer) < 0) {
if (log.isDebugEnabled())
log.debug("Received message has higher affinity topology version [msg=" + msg +
", locTopVer=" + locAffVer + ", rmtTopVer=" + rmtAffVer + ']');
fut = cctx.exchange().affinityReadyFuture(rmtAffVer);
}
}
if (fut != null && !fut.isDone()) {
fut.listen(new CI1<IgniteInternalFuture<?>>() {
@Override public void apply(IgniteInternalFuture<?> t) {
cctx.kernalContext().closure().runLocalSafe(new Runnable() {
@Override public void run() {
handleMessage(nodeId, cacheMsg);
}
});
}
});
return;
}
handleMessage(nodeId, cacheMsg);
}
};
/**
* @param nodeId Sender node ID.
* @param cacheMsg Message.
*/
@SuppressWarnings("unchecked")
private void handleMessage(UUID nodeId, GridCacheMessage cacheMsg) {
int msgIdx = cacheMsg.lookupIndex();
IgniteBiInClosure<UUID, GridCacheMessage> c = null;
if (msgIdx >= 0) {
IgniteBiInClosure[] cacheClsHandlers = idxClsHandlers.get(cacheMsg.cacheId());
if (cacheClsHandlers != null)
c = cacheClsHandlers[msgIdx];
}
if (c == null)
c = clsHandlers.get(new ListenerKey(cacheMsg.cacheId(), cacheMsg.getClass()));
if (c == null) {
U.warn(log, "Received message without registered handler (will ignore) [msg=" + cacheMsg +
", nodeId=" + nodeId + ']');
return;
}
onMessage0(nodeId, cacheMsg, c);
}
/** {@inheritDoc} */
@Override public void start0() throws IgniteCheckedException {
retryDelay = cctx.gridConfig().getNetworkSendRetryDelay();
retryCnt = cctx.gridConfig().getNetworkSendRetryCount();
depEnabled = cctx.gridDeploy().enabled();
cctx.gridIO().addMessageListener(TOPIC_CACHE, lsnr);
}
/** {@inheritDoc} */
@SuppressWarnings("BusyWait")
@Override protected void onKernalStop0(boolean cancel) {
cctx.gridIO().removeMessageListener(TOPIC_CACHE);
for (Object ordTopic : orderedHandlers.keySet())
cctx.gridIO().removeMessageListener(ordTopic);
boolean interrupted = false;
// Busy wait is intentional.
while (true) {
try {
if (rw.tryWriteLock(200, TimeUnit.MILLISECONDS))
break;
else
Thread.sleep(200);
}
catch (InterruptedException ignore) {
// Preserve interrupt status & ignore.
// Note that interrupted flag is cleared.
interrupted = true;
}
}
if (interrupted)
Thread.currentThread().interrupt();
try {
stopping = true;
}
finally {
rw.writeUnlock();
}
}
/**
* @param nodeId Node ID.
* @param cacheMsg Cache message.
* @param c Handler closure.
*/
@SuppressWarnings({"unchecked", "ConstantConditions", "ThrowableResultOfMethodCallIgnored"})
private void onMessage0(final UUID nodeId, final GridCacheMessage cacheMsg,
final IgniteBiInClosure<UUID, GridCacheMessage> c) {
rw.readLock();
try {
if (stopping) {
if (log.isDebugEnabled())
log.debug("Received cache communication message while stopping (will ignore) [nodeId=" +
nodeId + ", msg=" + cacheMsg + ']');
return;
}
if (depEnabled)
cctx.deploy().ignoreOwnership(true);
unmarshall(nodeId, cacheMsg);
if (cacheMsg.classError() != null)
processFailedMessage(nodeId, cacheMsg);
else {
if (cacheMsg.allowForStartup())
processMessage(nodeId, cacheMsg, c);
else {
IgniteInternalFuture<?> startFut = startFuture(cacheMsg);
if (startFut.isDone())
processMessage(nodeId, cacheMsg, c);
else {
if (log.isDebugEnabled())
log.debug("Waiting for start future to complete for message [nodeId=" + nodeId +
", locId=" + cctx.localNodeId() + ", msg=" + cacheMsg + ']');
// Don't hold this thread waiting for preloading to complete.
startFut.listen(new CI1<IgniteInternalFuture<?>>() {
@Override public void apply(final IgniteInternalFuture<?> f) {
cctx.kernalContext().closure().runLocalSafe(
new GridPlainRunnable() {
@Override public void run() {
rw.readLock();
try {
if (stopping) {
if (log.isDebugEnabled())
log.debug("Received cache communication message while stopping " +
"(will ignore) [nodeId=" + nodeId + ", msg=" + cacheMsg + ']');
return;
}
f.get();
if (log.isDebugEnabled())
log.debug("Start future completed for message [nodeId=" + nodeId +
", locId=" + cctx.localNodeId() + ", msg=" + cacheMsg + ']');
processMessage(nodeId, cacheMsg, c);
}
catch (IgniteCheckedException e) {
// Log once.
if (startErr.compareAndSet(false, true))
U.error(log, "Failed to complete preload start future " +
"(will ignore message) " +
"[fut=" + f + ", nodeId=" + nodeId + ", msg=" + cacheMsg + ']', e);
}
finally {
rw.readUnlock();
}
}
}
);
}
});
}
}
}
}
catch (Throwable e) {
U.error(log, "Failed to process message [senderId=" + nodeId + ", messageType=" + cacheMsg.getClass() + ']', e);
if (e instanceof Error)
throw (Error)e;
}
finally {
if (depEnabled)
cctx.deploy().ignoreOwnership(false);
rw.readUnlock();
}
}
/**
* Sends response on failed message.
* @param nodeId node id.
* @param res response.
* @param cctx shared context.
* @param plc grid io policy.
*/
private void sendResponseOnFailedMessage(UUID nodeId, GridCacheMessage res, GridCacheSharedContext cctx,
byte plc) {
try {
cctx.io().send(nodeId, res, plc);
}
catch (IgniteCheckedException e) {
U.error(log, "Failed to send response to node (is node still alive?) [nodeId=" + nodeId +
",res=" + res + ']', e);
}
}
/**
* Processes failed messages.
* @param nodeId niode id.
* @param msg message.
* @throws IgniteCheckedException If failed.
*/
private void processFailedMessage(UUID nodeId, GridCacheMessage msg) throws IgniteCheckedException {
GridCacheContext ctx = cctx.cacheContext(msg.cacheId());
switch (msg.directType()) {
case 14: {
GridCacheEvictionRequest req = (GridCacheEvictionRequest)msg;
GridCacheEvictionResponse res = new GridCacheEvictionResponse(
ctx.cacheId(),
req.futureId(),
req.classError() != null
);
sendResponseOnFailedMessage(nodeId, res, cctx, ctx.ioPolicy());
}
break;
case 30: {
GridDhtLockRequest req = (GridDhtLockRequest)msg;
GridDhtLockResponse res = new GridDhtLockResponse(
ctx.cacheId(),
req.version(),
req.futureId(),
req.miniId(),
0);
sendResponseOnFailedMessage(nodeId, res, cctx, ctx.ioPolicy());
}
break;
case 34: {
GridDhtTxPrepareRequest req = (GridDhtTxPrepareRequest)msg;
GridDhtTxPrepareResponse res = new GridDhtTxPrepareResponse(
req.version(),
req.futureId(),
req.miniId());
res.error(req.classError());
sendResponseOnFailedMessage(nodeId, res, cctx, req.policy());
}
break;
case 38: {
GridDhtAtomicUpdateRequest req = (GridDhtAtomicUpdateRequest)msg;
GridDhtAtomicUpdateResponse res = new GridDhtAtomicUpdateResponse(
ctx.cacheId(),
req.futureVersion());
res.onError(req.classError());
sendResponseOnFailedMessage(nodeId, res, cctx, ctx.ioPolicy());
}
break;
case 40: {
GridNearAtomicUpdateRequest req = (GridNearAtomicUpdateRequest)msg;
GridNearAtomicUpdateResponse res = new GridNearAtomicUpdateResponse(
ctx.cacheId(),
nodeId,
req.futureVersion());
res.error(req.classError());
sendResponseOnFailedMessage(nodeId, res, cctx, ctx.ioPolicy());
}
break;
case 42: {
GridDhtForceKeysRequest req = (GridDhtForceKeysRequest)msg;
GridDhtForceKeysResponse res = new GridDhtForceKeysResponse(
ctx.cacheId(),
req.futureId(),
req.miniId()
);
res.error(req.classError());
sendResponseOnFailedMessage(nodeId, res, cctx, ctx.ioPolicy());
}
break;
case 45: {
GridDhtPartitionSupplyMessage req = (GridDhtPartitionSupplyMessage)msg;
U.error(log, "Supply message cannot be unmarshalled.", req.classError());
}
break;
case 49: {
GridNearGetRequest req = (GridNearGetRequest)msg;
GridNearGetResponse res = new GridNearGetResponse(
ctx.cacheId(),
req.futureId(),
req.miniId(),
req.version());
res.error(req.classError());
sendResponseOnFailedMessage(nodeId, res, cctx, ctx.ioPolicy());
}
break;
case 50: {
GridNearGetResponse res = (GridNearGetResponse)msg;
GridCacheFuture fut = ctx.mvcc().future(res.version(), res.futureId());
if (fut == null) {
if (log.isDebugEnabled())
log.debug("Failed to find future for get response [sender=" + nodeId + ", res=" + res + ']');
return;
}
res.error(res.classError());
if (fut instanceof GridNearGetFuture)
((GridNearGetFuture)fut).onResult(nodeId, res);
else
((GridPartitionedGetFuture)fut).onResult(nodeId, res);
}
break;
case 51: {
GridNearLockRequest req = (GridNearLockRequest)msg;
GridNearLockResponse res = new GridNearLockResponse(
ctx.cacheId(),
req.version(),
req.futureId(),
req.miniId(),
false,
0,
req.classError(),
null);
sendResponseOnFailedMessage(nodeId, res, cctx, ctx.ioPolicy());
}
break;
case 55: {
GridNearTxPrepareRequest req = (GridNearTxPrepareRequest)msg;
GridNearTxPrepareResponse res = new GridNearTxPrepareResponse(
req.version(),
req.futureId(),
req.miniId(),
req.version(),
req.version(),
null,
null,
null);
res.error(req.classError());
sendResponseOnFailedMessage(nodeId, res, cctx, req.policy());
}
break;
default:
throw new IgniteCheckedException("Failed to send response to node. Unsupported direct type [message="
+ msg + "]");
}
}
/**
* @param cacheMsg Cache message to get start future.
* @return Preloader start future.
*/
@SuppressWarnings("unchecked")
private IgniteInternalFuture<Object> startFuture(GridCacheMessage cacheMsg) {
int cacheId = cacheMsg.cacheId();
if (cacheId != 0)
return cctx.cacheContext(cacheId).preloader().startFuture();
else {
if (F.eq(cacheMsg.topologyVersion(), AffinityTopologyVersion.NONE))
return new GridFinishedFuture<>();
return cctx.preloadersStartFuture(cacheMsg.topologyVersion());
}
}
/**
* @param nodeId Node ID.
* @param msg Message.
* @param c Closure.
*/
private void processMessage(UUID nodeId, GridCacheMessage msg,
IgniteBiInClosure<UUID, GridCacheMessage> c) {
try {
// We will not end up with storing a bunch of new UUIDs
// in each cache entry, since node ID is stored in NIO session
// on handshake.
c.apply(nodeId, msg);
if (log.isDebugEnabled())
log.debug("Finished processing cache communication message [nodeId=" + nodeId + ", msg=" + msg + ']');
}
catch (Throwable e) {
U.error(log, "Failed processing message [senderId=" + nodeId + ", msg=" + msg + ']', e);
if (e instanceof Error)
throw e;
}
finally {
// Reset thread local context.
cctx.tm().resetContext();
cctx.mvcc().contextReset();
// Unwind eviction notifications.
CU.unwindEvicts(cctx);
}
}
/**
* Pre-processes message prior to send.
*
* @param msg Message to send.
* @param destNodeId Destination node ID.
* @throws IgniteCheckedException If failed.
*/
private void onSend(GridCacheMessage msg, @Nullable UUID destNodeId) throws IgniteCheckedException {
if (msg.messageId() < 0)
// Generate and set message ID.
msg.messageId(idGen.incrementAndGet());
if (destNodeId == null || !cctx.localNodeId().equals(destNodeId)) {
msg.prepareMarshal(cctx);
if (depEnabled && msg instanceof GridCacheDeployable)
cctx.deploy().prepare((GridCacheDeployable)msg);
}
}
/**
* Sends communication message.
*
* @param node Node to send the message to.
* @param msg Message to send.
* @param plc IO policy.
* @throws IgniteCheckedException If sending failed.
* @throws ClusterTopologyCheckedException If receiver left.
*/
@SuppressWarnings("unchecked")
public void send(ClusterNode node, GridCacheMessage msg, byte plc) throws IgniteCheckedException {
assert !node.isLocal();
onSend(msg, node.id());
if (log.isDebugEnabled())
log.debug("Sending cache message [msg=" + msg + ", node=" + U.toShortString(node) + ']');
int cnt = 0;
while (cnt <= retryCnt) {
try {
cnt++;
cctx.gridIO().send(node, TOPIC_CACHE, msg, plc);
return;
}
catch (IgniteCheckedException e) {
if (!cctx.discovery().alive(node.id()) || !cctx.discovery().pingNode(node.id()))
throw new ClusterTopologyCheckedException("Node left grid while sending message to: " + node.id(), e);
if (cnt == retryCnt || cctx.kernalContext().isStopping())
throw e;
else if (log.isDebugEnabled())
log.debug("Failed to send message to node (will retry): " + node.id());
}
U.sleep(retryDelay);
}
if (log.isDebugEnabled())
log.debug("Sent cache message [msg=" + msg + ", node=" + U.toShortString(node) + ']');
}
/**
* Sends message and automatically accounts for lefts nodes.
*
* @param nodes Nodes to send to.
* @param msg Message to send.
* @param plc IO policy.
* @param fallback Callback for failed nodes.
* @return {@code True} if nodes are empty or message was sent, {@code false} if
* all nodes have left topology while sending this message.
* @throws IgniteCheckedException If send failed.
*/
@SuppressWarnings({"BusyWait", "unchecked"})
public boolean safeSend(Collection<? extends ClusterNode> nodes, GridCacheMessage msg, byte plc,
@Nullable IgnitePredicate<ClusterNode> fallback) throws IgniteCheckedException {
assert nodes != null;
assert msg != null;
if (nodes.isEmpty()) {
if (log.isDebugEnabled())
log.debug("Message will not be sent as collection of nodes is empty: " + msg);
return true;
}
onSend(msg, null);
if (log.isDebugEnabled())
log.debug("Sending cache message [msg=" + msg + ", nodes=" + U.toShortString(nodes) + ']');
final Collection<UUID> leftIds = new GridLeanSet<>();
int cnt = 0;
while (cnt < retryCnt) {
try {
Collection<? extends ClusterNode> nodesView = F.view(nodes, new P1<ClusterNode>() {
@Override public boolean apply(ClusterNode e) {
return !leftIds.contains(e.id());
}
});
cctx.gridIO().send(nodesView, TOPIC_CACHE, msg, plc);
boolean added = false;
// Even if there is no exception, we still check here, as node could have
// ignored the message during stopping.
for (ClusterNode n : nodes) {
if (!leftIds.contains(n.id()) && !cctx.discovery().alive(n.id())) {
leftIds.add(n.id());
if (fallback != null && !fallback.apply(n))
// If fallback signalled to stop.
return false;
added = true;
}
}
if (added) {
if (!F.exist(F.nodeIds(nodes), F0.not(F.contains(leftIds)))) {
if (log.isDebugEnabled())
log.debug("Message will not be sent because all nodes left topology [msg=" + msg +
", nodes=" + U.toShortString(nodes) + ']');
return false;
}
}
break;
}
catch (IgniteCheckedException e) {
boolean added = false;
for (ClusterNode n : nodes) {
if (!leftIds.contains(n.id()) &&
(!cctx.discovery().alive(n.id()) || !cctx.discovery().pingNode(n.id()))) {
leftIds.add(n.id());
if (fallback != null && !fallback.apply(n))
// If fallback signalled to stop.
return false;
added = true;
}
}
if (!added) {
cnt++;
if (cnt == retryCnt)
throw e;
U.sleep(retryDelay);
}
if (!F.exist(F.nodeIds(nodes), F0.not(F.contains(leftIds)))) {
if (log.isDebugEnabled())
log.debug("Message will not be sent because all nodes left topology [msg=" + msg + ", nodes=" +
U.toShortString(nodes) + ']');
return false;
}
if (log.isDebugEnabled())
log.debug("Message send will be retried [msg=" + msg + ", nodes=" + U.toShortString(nodes) +
", leftIds=" + leftIds + ']');
}
}
if (log.isDebugEnabled())
log.debug("Sent cache message [msg=" + msg + ", nodes=" + U.toShortString(nodes) + ']');
return true;
}
/**
* Sends communication message.
*
* @param nodeId ID of node to send the message to.
* @param msg Message to send.
* @param plc IO policy.
* @throws IgniteCheckedException If sending failed.
*/
public void send(UUID nodeId, GridCacheMessage msg, byte plc) throws IgniteCheckedException {
ClusterNode n = cctx.discovery().node(nodeId);
if (n == null)
throw new ClusterTopologyCheckedException("Failed to send message because node left grid [nodeId=" + nodeId +
", msg=" + msg + ']');
send(n, msg, plc);
}
/**
* @param node Destination node.
* @param topic Topic to send the message to.
* @param msg Message to send.
* @param plc IO policy.
* @param timeout Timeout to keep a message on receiving queue.
* @throws IgniteCheckedException Thrown in case of any errors.
*/
public void sendOrderedMessage(ClusterNode node, Object topic, GridCacheMessage msg, byte plc,
long timeout) throws IgniteCheckedException {
onSend(msg, node.id());
int cnt = 0;
while (cnt <= retryCnt) {
try {
cnt++;
cctx.gridIO().sendOrderedMessage(node, topic, msg, plc, timeout, false);
if (log.isDebugEnabled())
log.debug("Sent ordered cache message [topic=" + topic + ", msg=" + msg +
", nodeId=" + node.id() + ']');
return;
}
catch (IgniteCheckedException e) {
if (cctx.discovery().node(node.id()) == null)
throw new ClusterTopologyCheckedException("Node left grid while sending ordered message to: " + node.id(), e);
if (cnt == retryCnt)
throw e;
else if (log.isDebugEnabled())
log.debug("Failed to send message to node (will retry): " + node.id());
}
U.sleep(retryDelay);
}
}
/**
* @return ID that auto-grows based on local counter and counters received
* from other nodes.
*/
public long nextIoId() {
return idGen.incrementAndGet();
}
/**
* Sends message without retries and node ping in case of error.
*
* @param node Node to send message to.
* @param msg Message.
* @param plc IO policy.
* @throws IgniteCheckedException If send failed.
*/
public void sendNoRetry(ClusterNode node,
GridCacheMessage msg,
byte plc)
throws IgniteCheckedException
{
assert node != null;
assert msg != null;
onSend(msg, null);
try {
cctx.gridIO().send(node, TOPIC_CACHE, msg, plc);
if (log.isDebugEnabled())
log.debug("Sent cache message [msg=" + msg + ", node=" + U.toShortString(node) + ']');
}
catch (IgniteCheckedException e) {
if (!cctx.discovery().alive(node.id()))
throw new ClusterTopologyCheckedException("Node left grid while sending message to: " + node.id(), e);
else
throw e;
}
}
/**
* Adds message handler.
*
* @param cacheId Cache ID.
* @param type Type of message.
* @param c Handler.
*/
@SuppressWarnings({"unchecked"})
public void addHandler(
int cacheId,
Class<? extends GridCacheMessage> type,
IgniteBiInClosure<UUID, ? extends GridCacheMessage> c) {
int msgIdx = messageIndex(type);
if (msgIdx != -1) {
IgniteBiInClosure[] cacheClsHandlers = idxClsHandlers.get(cacheId);
if (cacheClsHandlers == null) {
cacheClsHandlers = new IgniteBiInClosure[GridCacheMessage.MAX_CACHE_MSG_LOOKUP_INDEX];
idxClsHandlers.put(cacheId, cacheClsHandlers);
}
if (cacheClsHandlers[msgIdx] != null)
throw new IgniteException("Duplicate cache message ID found [cacheId=" + cacheId +
", type=" + type + ']');
cacheClsHandlers[msgIdx] = c;
return;
}
else {
ListenerKey key = new ListenerKey(cacheId, type);
if (clsHandlers.putIfAbsent(key,
(IgniteBiInClosure<UUID, GridCacheMessage>)c) != null)
assert false : "Handler for class already registered [cacheId=" + cacheId + ", cls=" + type +
", old=" + clsHandlers.get(key) + ", new=" + c + ']';
}
if (log != null && log.isDebugEnabled())
log.debug("Registered cache communication handler [cacheId=" + cacheId + ", type=" + type +
", msgIdx=" + msgIdx + ", handler=" + c + ']');
}
/**
* @param cacheId Cache ID to remove handlers for.
*/
public void removeHandlers(int cacheId) {
assert cacheId != 0;
idxClsHandlers.remove(cacheId);
for (Iterator<ListenerKey> iter = clsHandlers.keySet().iterator(); iter.hasNext(); ) {
ListenerKey key = iter.next();
if (key.cacheId == cacheId)
iter.remove();
}
}
/**
* @param cacheId Cache ID to remove handlers for.
* @param type Message type.
*/
public void removeHandler(int cacheId, Class<? extends GridCacheMessage> type) {
clsHandlers.remove(new ListenerKey(cacheId, type));
}
/**
* @param msgCls Message class to check.
* @return Message index.
*/
private int messageIndex(Class<?> msgCls) {
try {
Integer msgIdx = U.field(msgCls, GridCacheMessage.CACHE_MSG_INDEX_FIELD_NAME);
if (msgIdx == null || msgIdx < 0)
return -1;
return msgIdx;
}
catch (IgniteCheckedException ignored) {
return -1;
}
}
/**
* Adds ordered message handler.
*
* @param topic Topic.
* @param c Handler.
*/
@SuppressWarnings({"unchecked"})
public void addOrderedHandler(Object topic, IgniteBiInClosure<UUID, ? extends GridCacheMessage> c) {
if (orderedHandlers.putIfAbsent(topic, c) == null) {
cctx.gridIO().addMessageListener(topic, new OrderedMessageListener(
(IgniteBiInClosure<UUID, GridCacheMessage>)c));
if (log != null && log.isDebugEnabled())
log.debug("Registered ordered cache communication handler [topic=" + topic + ", handler=" + c + ']');
}
else if (log != null)
U.warn(log, "Failed to register ordered cache communication handler because it is already " +
"registered for this topic [topic=" + topic + ", handler=" + c + ']');
}
/**
* Removed ordered message handler.
*
* @param topic Topic.
*/
public void removeOrderedHandler(Object topic) {
if (orderedHandlers.remove(topic) != null) {
cctx.gridIO().removeMessageListener(topic);
if (log != null && log.isDebugEnabled())
log.debug("Unregistered ordered cache communication handler for topic:" + topic);
}
else if (log != null)
U.warn(log, "Failed to unregister ordered cache communication handler because it was not found " +
"for topic: " + topic);
}
/**
* @param nodeId Sender node ID.
* @param cacheMsg Message.
* @throws IgniteCheckedException If failed.
*/
@SuppressWarnings({"ErrorNotRethrown", "unchecked"})
private void unmarshall(UUID nodeId, GridCacheMessage cacheMsg) throws IgniteCheckedException {
if (cctx.localNodeId().equals(nodeId))
return;
GridDeploymentInfo bean = cacheMsg.deployInfo();
if (bean != null) {
assert depEnabled : "Received deployment info while peer class loading is disabled [nodeId=" + nodeId +
", msg=" + cacheMsg + ']';
cctx.deploy().p2pContext(nodeId, bean.classLoaderId(), bean.userVersion(),
bean.deployMode(), bean.participants(), bean.localDeploymentOwner());
if (log.isDebugEnabled())
log.debug("Set P2P context [senderId=" + nodeId + ", msg=" + cacheMsg + ']');
}
try {
cacheMsg.finishUnmarshal(cctx, cctx.deploy().globalLoader());
}
catch (IgniteCheckedException e) {
cacheMsg.onClassError(e);
}
catch (Error e) {
if (cacheMsg.ignoreClassErrors() && X.hasCause(e, NoClassDefFoundError.class,
UnsupportedClassVersionError.class))
cacheMsg.onClassError(new IgniteCheckedException("Failed to load class during unmarshalling: " + e, e));
else
throw e;
}
}
/** {@inheritDoc} */
@Override public void printMemoryStats() {
X.println(">>> ");
X.println(">>> Cache IO manager memory stats [grid=" + cctx.gridName() + ']');
X.println(">>> clsHandlersSize: " + clsHandlers.size());
X.println(">>> orderedHandlersSize: " + orderedHandlers.size());
}
/**
* Ordered message listener.
*/
private class OrderedMessageListener implements GridMessageListener {
/** */
private final IgniteBiInClosure<UUID, GridCacheMessage> c;
/**
* @param c Handler closure.
*/
OrderedMessageListener(IgniteBiInClosure<UUID, GridCacheMessage> c) {
this.c = c;
}
/** {@inheritDoc} */
@SuppressWarnings({"CatchGenericClass", "unchecked"})
@Override public void onMessage(final UUID nodeId, Object msg) {
if (log.isDebugEnabled())
log.debug("Received cache ordered message [nodeId=" + nodeId + ", msg=" + msg + ']');
final GridCacheMessage cacheMsg = (GridCacheMessage)msg;
onMessage0(nodeId, cacheMsg, c);
}
}
/**
*
*/
private static class ListenerKey {
/** Cache ID. */
private int cacheId;
/** Message class. */
private Class<? extends GridCacheMessage> msgCls;
/**
* @param cacheId Cache ID.
* @param msgCls Message class.
*/
private ListenerKey(int cacheId, Class<? extends GridCacheMessage> msgCls) {
this.cacheId = cacheId;
this.msgCls = msgCls;
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ListenerKey))
return false;
ListenerKey that = (ListenerKey)o;
return cacheId == that.cacheId && msgCls.equals(that.msgCls);
}
/** {@inheritDoc} */
@Override public int hashCode() {
int res = cacheId;
res = 31 * res + msgCls.hashCode();
return res;
}
}
}
| |
package com.hubspot.baragon.data;
import com.codahale.metrics.annotation.Timed;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Optional;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.hubspot.baragon.config.ZooKeeperConfiguration;
import com.hubspot.baragon.models.BaragonRequest;
import com.hubspot.baragon.models.InternalRequestStates;
import com.hubspot.baragon.models.QueuedRequestId;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.transaction.CuratorTransactionResult;
import org.apache.curator.utils.ZKPaths;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException.NodeExistsException;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
public class BaragonRequestDatastore extends AbstractDataStore {
private static final Logger LOG = LoggerFactory.getLogger(
BaragonRequestDatastore.class
);
public static final String REQUESTS_FORMAT = "/request";
public static final String REQUEST_FORMAT = REQUESTS_FORMAT + "/%s";
public static final String REQUEST_STATE_FORMAT = REQUEST_FORMAT + "/status";
public static final String REQUEST_MESSAGE_FORMAT = REQUEST_FORMAT + "/message";
public static final String REQUEST_QUEUE_FORMAT = "/queue";
public static final String REQUEST_ENQUEUE_FORMAT = REQUEST_QUEUE_FORMAT + "/%s|%s|";
public static final String REQUEST_QUEUE_ITEM_FORMAT = REQUEST_QUEUE_FORMAT + "/%s";
@Inject
public BaragonRequestDatastore(
CuratorFramework curatorFramework,
ObjectMapper objectMapper,
ZooKeeperConfiguration zooKeeperConfiguration
) {
super(curatorFramework, objectMapper, zooKeeperConfiguration);
}
//
// REQUEST DATA
//
@Timed
public Optional<BaragonRequest> getRequest(String requestId) {
return readFromZk(String.format(REQUEST_FORMAT, requestId), BaragonRequest.class);
}
@Timed
public Optional<BaragonRequest> deleteRequest(String requestId) {
final Optional<BaragonRequest> maybeRequest = getRequest(requestId);
if (maybeRequest.isPresent()) {
deleteNode(String.format(REQUEST_FORMAT, requestId), true);
}
return maybeRequest;
}
@Timed
public BaragonRequest updateRequest(BaragonRequest request) throws Exception {
final Optional<BaragonRequest> maybeRequest = getRequest(
request.getLoadBalancerRequestId()
);
if (!maybeRequest.isPresent()) {
throw new IllegalStateException("No such request exists!");
}
final String requestPath = String.format(
REQUEST_FORMAT,
request.getLoadBalancerRequestId()
);
writeToZk(requestPath, request);
return maybeRequest.get();
}
@Timed
public List<String> getAllRequestIds() {
return getChildren(REQUESTS_FORMAT);
}
@Timed
public Optional<Long> getRequestUpdatedAt(String requestId) {
return getUpdatedAt(String.format(String.format(REQUEST_STATE_FORMAT, requestId)));
}
//
// REQUEST STATE
//
public boolean activeRequestExists(String requestId) {
return nodeExists(String.format(REQUEST_FORMAT, requestId));
}
@Timed
public Optional<InternalRequestStates> getRequestState(String requestId) {
return readFromZk(
String.format(REQUEST_STATE_FORMAT, requestId),
InternalRequestStates.class
);
}
@Timed
public void setRequestState(String requestId, InternalRequestStates state) {
writeToZk(String.format(REQUEST_STATE_FORMAT, requestId), state);
}
// REQUEST MESSAGE
@Timed
public Optional<String> getRequestMessage(String requestId) {
return readFromZk(String.format(REQUEST_MESSAGE_FORMAT, requestId), String.class);
}
@Timed
public void setRequestMessage(String requestId, String message) {
writeToZk(String.format(REQUEST_MESSAGE_FORMAT, requestId), message);
}
//
// REQUEST QUEUING
//
@Timed
public QueuedRequestId enqueueRequest(
BaragonRequest request,
InternalRequestStates state
)
throws NodeExistsException {
final long start = System.currentTimeMillis();
final String queuedRequestPath = String.format(
REQUEST_ENQUEUE_FORMAT,
request.getLoadBalancerService().getServiceId(),
request.getLoadBalancerRequestId()
);
final String requestPath = String.format(
REQUEST_FORMAT,
request.getLoadBalancerRequestId()
);
final String requestStatePath = String.format(
REQUEST_STATE_FORMAT,
request.getLoadBalancerRequestId()
);
try {
if (!nodeExists(REQUESTS_FORMAT)) {
createNode(REQUESTS_FORMAT);
}
if (!nodeExists(REQUEST_QUEUE_FORMAT)) {
createNode(REQUEST_QUEUE_FORMAT);
}
byte[] requestBytes = objectMapper.writeValueAsBytes(request);
byte[] stateBytes = objectMapper.writeValueAsBytes(state);
Collection<CuratorTransactionResult> results = curatorFramework
.inTransaction()
.create()
.forPath(requestPath, requestBytes)
.and()
.create()
.forPath(requestStatePath, stateBytes)
.and()
.create()
.withMode(CreateMode.PERSISTENT_SEQUENTIAL)
.forPath(queuedRequestPath)
.and()
.commit();
log(
OperationType.WRITE,
Optional.of(3),
Optional.of(requestBytes.length + stateBytes.length),
start,
String.format(
"Transaction Paths [%s + %s + %s]",
requestPath,
requestStatePath,
queuedRequestPath
)
);
return QueuedRequestId.fromString(
ZKPaths.getNodeFromPath(
Iterables
.find(
results,
CuratorTransactionResult.ofTypeAndPath(
org.apache.curator.framework.api.transaction.OperationType.CREATE,
queuedRequestPath
)
)
.getResultPath()
)
);
} catch (NodeExistsException nee) {
throw nee;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Timed
public List<QueuedRequestId> getQueuedRequestIds() {
final List<String> nodes = getChildren(REQUEST_QUEUE_FORMAT);
Collections.sort(nodes, SEQUENCE_NODE_COMPARATOR_LOW_TO_HIGH);
final List<QueuedRequestId> queuedRequestIds = Lists.newArrayListWithCapacity(
nodes.size()
);
for (String node : nodes) {
queuedRequestIds.add(QueuedRequestId.fromString(node));
}
return queuedRequestIds;
}
public long getOldestQueuedRequestAge() {
long now = System.currentTimeMillis();
long oldest = now;
for (String child : getChildren(REQUEST_QUEUE_FORMAT)) {
try {
Stat stat = curatorFramework
.checkExists()
.forPath(ZKPaths.makePath(REQUEST_QUEUE_FORMAT, child));
if (stat != null && stat.getMtime() < oldest) {
oldest = stat.getMtime();
}
} catch (Exception e) {
LOG.warn("Could not check exists for queued request id {}", child);
}
}
return now - oldest;
}
@Timed
public int getQueuedRequestCount() {
return getChildren(REQUEST_QUEUE_FORMAT).size();
}
@Timed
public void removeQueuedRequest(QueuedRequestId queuedRequestId) {
deleteNode(String.format(REQUEST_QUEUE_ITEM_FORMAT, queuedRequestId.buildZkPath()));
}
}
| |
/*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets 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 io.druid.query.lookup;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.inject.Binder;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.name.Names;
import io.druid.guice.GuiceInjectors;
import io.druid.initialization.Initialization;
import io.druid.java.util.common.DateTimes;
import io.druid.java.util.common.ISE;
import io.druid.java.util.common.StringUtils;
import io.druid.java.util.common.io.Closer;
import io.druid.java.util.common.logger.Logger;
import io.druid.server.lookup.namespace.NamespaceExtractionModule;
import kafka.admin.AdminUtils;
import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;
import kafka.server.KafkaConfig;
import kafka.server.KafkaServer;
import kafka.utils.Time;
import kafka.utils.ZKStringSerializer$;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.exception.ZkException;
import org.apache.curator.test.TestingServer;
import org.apache.zookeeper.CreateMode;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.Closeable;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ThreadLocalRandom;
/**
*
*/
public class TestKafkaExtractionCluster
{
private static final Logger log = new Logger(TestKafkaExtractionCluster.class);
private static final String topicName = "testTopic";
private static final Map<String, String> kafkaProperties = new HashMap<>();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
private final Closer closer = Closer.create();
private KafkaServer kafkaServer;
private KafkaConfig kafkaConfig;
private TestingServer zkTestServer;
private ZkClient zkClient;
private Injector injector;
private ObjectMapper mapper;
private KafkaLookupExtractorFactory factory;
@Before
public void setUp() throws Exception
{
zkTestServer = new TestingServer(-1, temporaryFolder.newFolder(), true);
zkTestServer.start();
closer.register(new Closeable()
{
@Override
public void close() throws IOException
{
zkTestServer.stop();
}
});
zkClient = new ZkClient(
zkTestServer.getConnectString(),
10000,
10000,
ZKStringSerializer$.MODULE$
);
closer.register(new Closeable()
{
@Override
public void close() throws IOException
{
zkClient.close();
}
});
if (!zkClient.exists("/kafka")) {
zkClient.create("/kafka", null, CreateMode.PERSISTENT);
}
log.info("---------------------------Started ZK---------------------------");
final String zkKafkaPath = "/kafka";
final Properties serverProperties = new Properties();
serverProperties.putAll(kafkaProperties);
serverProperties.put("broker.id", "0");
serverProperties.put("log.dir", temporaryFolder.newFolder().getAbsolutePath());
serverProperties.put("log.cleaner.enable", "true");
serverProperties.put("host.name", "127.0.0.1");
serverProperties.put("zookeeper.connect", zkTestServer.getConnectString() + zkKafkaPath);
serverProperties.put("zookeeper.session.timeout.ms", "10000");
serverProperties.put("zookeeper.sync.time.ms", "200");
serverProperties.put("port", String.valueOf(ThreadLocalRandom.current().nextInt(9999) + 10000));
kafkaConfig = new KafkaConfig(serverProperties);
final long time = DateTimes.of("2015-01-01").getMillis();
kafkaServer = new KafkaServer(
kafkaConfig,
new Time()
{
@Override
public long milliseconds()
{
return time;
}
@Override
public long nanoseconds()
{
return milliseconds() * 1_000_000;
}
@Override
public void sleep(long ms)
{
try {
Thread.sleep(ms);
}
catch (InterruptedException e) {
throw Throwables.propagate(e);
}
}
}
);
kafkaServer.startup();
closer.register(new Closeable()
{
@Override
public void close() throws IOException
{
kafkaServer.shutdown();
kafkaServer.awaitShutdown();
}
});
int sleepCount = 0;
while (!kafkaServer.kafkaController().isActive()) {
Thread.sleep(100);
if (++sleepCount > 10) {
throw new InterruptedException("Controller took to long to awaken");
}
}
log.info("---------------------------Started Kafka Server---------------------------");
final ZkClient zkClient = new ZkClient(
zkTestServer.getConnectString() + zkKafkaPath, 10000, 10000,
ZKStringSerializer$.MODULE$
);
try (final AutoCloseable autoCloseable = new AutoCloseable()
{
@Override
public void close() throws Exception
{
if (zkClient.exists(zkKafkaPath)) {
try {
zkClient.deleteRecursive(zkKafkaPath);
}
catch (ZkException ex) {
log.warn(ex, "error deleting %s zk node", zkKafkaPath);
}
}
zkClient.close();
}
}) {
final Properties topicProperties = new Properties();
topicProperties.put("cleanup.policy", "compact");
if (!AdminUtils.topicExists(zkClient, topicName)) {
AdminUtils.createTopic(zkClient, topicName, 1, 1, topicProperties);
}
log.info("---------------------------Created topic---------------------------");
Assert.assertTrue(AdminUtils.topicExists(zkClient, topicName));
}
final Properties kafkaProducerProperties = makeProducerProperties();
final Producer<byte[], byte[]> producer = new Producer<>(new ProducerConfig(kafkaProducerProperties));
try (final AutoCloseable autoCloseable = new AutoCloseable()
{
@Override
public void close() throws Exception
{
producer.close();
}
}) {
producer.send(
new KeyedMessage<>(
topicName,
StringUtils.toUtf8("abcdefg"),
StringUtils.toUtf8("abcdefg")
)
);
}
System.setProperty("druid.extensions.searchCurrentClassloader", "false");
injector = Initialization.makeInjectorWithModules(
GuiceInjectors.makeStartupInjector(),
ImmutableList.of(
new Module()
{
@Override
public void configure(Binder binder)
{
binder.bindConstant().annotatedWith(Names.named("serviceName")).to("test");
binder.bindConstant().annotatedWith(Names.named("servicePort")).to(0);
binder.bindConstant().annotatedWith(Names.named("tlsServicePort")).to(-1);
}
},
// These injections fail under IntelliJ but are required for maven
new NamespaceExtractionModule(),
new KafkaExtractionNamespaceModule()
)
);
mapper = injector.getInstance(ObjectMapper.class);
log.info("--------------------------- placed default item via producer ---------------------------");
final Map<String, String> consumerProperties = new HashMap<>(kafkaProperties);
consumerProperties.put("zookeeper.connect", zkTestServer.getConnectString() + zkKafkaPath);
consumerProperties.put("zookeeper.session.timeout.ms", "10000");
consumerProperties.put("zookeeper.sync.time.ms", "200");
final KafkaLookupExtractorFactory kafkaLookupExtractorFactory = new KafkaLookupExtractorFactory(
null,
topicName,
consumerProperties
);
factory = (KafkaLookupExtractorFactory) mapper.readValue(
mapper.writeValueAsString(kafkaLookupExtractorFactory),
LookupExtractorFactory.class
);
Assert.assertEquals(kafkaLookupExtractorFactory.getKafkaTopic(), factory.getKafkaTopic());
Assert.assertEquals(kafkaLookupExtractorFactory.getKafkaProperties(), factory.getKafkaProperties());
factory.start();
closer.register(new Closeable()
{
@Override
public void close() throws IOException
{
factory.close();
}
});
log.info("--------------------------- started rename manager ---------------------------");
}
@After
public void tearDown() throws Exception
{
closer.close();
}
private Properties makeProducerProperties()
{
final Properties kafkaProducerProperties = new Properties();
kafkaProducerProperties.putAll(kafkaProperties);
kafkaProducerProperties.put(
"metadata.broker.list",
StringUtils.format("127.0.0.1:%d", kafkaServer.socketServer().port())
);
kafkaProperties.put("request.required.acks", "1");
return kafkaProducerProperties;
}
private void checkServer()
{
if (!kafkaServer.apis().controller().isActive()) {
throw new ISE("server is not active!");
}
}
@Test(timeout = 60_000L)
public void testSimpleRename() throws InterruptedException
{
final Properties kafkaProducerProperties = makeProducerProperties();
final Producer<byte[], byte[]> producer = new Producer<>(new ProducerConfig(kafkaProducerProperties));
closer.register(new Closeable()
{
@Override
public void close() throws IOException
{
producer.close();
}
});
checkServer();
assertUpdated(null, "foo");
assertReverseUpdated(ImmutableList.<String>of(), "foo");
long events = factory.getCompletedEventCount();
log.info("------------------------- Sending foo bar -------------------------------");
producer.send(new KeyedMessage<>(topicName, StringUtils.toUtf8("foo"), StringUtils.toUtf8("bar")));
long start = System.currentTimeMillis();
while (events == factory.getCompletedEventCount()) {
Thread.sleep(100);
if (System.currentTimeMillis() > start + 60_000) {
throw new ISE("Took too long to update event");
}
}
log.info("------------------------- Checking foo bar -------------------------------");
assertUpdated("bar", "foo");
assertReverseUpdated(Collections.singletonList("foo"), "bar");
assertUpdated(null, "baz");
checkServer();
events = factory.getCompletedEventCount();
log.info("------------------------- Sending baz bat -------------------------------");
producer.send(new KeyedMessage<>(topicName, StringUtils.toUtf8("baz"), StringUtils.toUtf8("bat")));
while (events == factory.getCompletedEventCount()) {
Thread.sleep(10);
if (System.currentTimeMillis() > start + 60_000) {
throw new ISE("Took too long to update event");
}
}
log.info("------------------------- Checking baz bat -------------------------------");
Assert.assertEquals("bat", factory.get().apply("baz"));
Assert.assertEquals(Collections.singletonList("baz"), factory.get().unapply("bat"));
}
private void assertUpdated(
String expected,
String key
)
throws InterruptedException
{
final LookupExtractor extractor = factory.get();
if (expected == null) {
while (extractor.apply(key) != null) {
Thread.sleep(100);
}
} else {
while (!expected.equals(extractor.apply(key))) {
Thread.sleep(100);
}
}
Assert.assertEquals("update check", expected, extractor.apply(key));
}
private void assertReverseUpdated(
List<String> expected,
String key
)
throws InterruptedException
{
final LookupExtractor extractor = factory.get();
while (!expected.equals(extractor.unapply(key))) {
Thread.sleep(100);
}
Assert.assertEquals("update check", expected, extractor.unapply(key));
}
}
| |
package de.flexiprovider.pqc.hbc.ots;
import java.util.BitSet;
import de.flexiprovider.api.MessageDigest;
import de.flexiprovider.common.math.IntegerFunctions;
import de.flexiprovider.common.util.ByteUtils;
import de.flexiprovider.pqc.hbc.PRNG;
/**
* Implementation of Winternitz OTS
*/
public class WinternitzOTS implements OTS {
// the Winternitz parameter
private int w;
// the hash function used by the OTS
private MessageDigest md;
// the PRNG used for key pair generation
private PRNG rng;
// t, t1, t2 from the paper and the lengths of the digest
private int t, t1, t2, mdSize;
// the signature key X, the verification key Y
private byte[][] X, Y;
private final int wPowOfTow; // 2^w
/**
* @param w
* the Winternitz parameter
*/
public WinternitzOTS(int w) {
this.w = w;
this.wPowOfTow = 1 << w;
if (w < 1) {
System.err.println("w should >= 1");
}
}
/**
* Initialize the OTS.
*
* @param md
* the hash function for the OTS
* @param rng
* the name of the PRNG used for key pair generation
*/
public void init(MessageDigest md, PRNG rng) {
this.md = md;
this.rng = rng;
mdSize = md.getDigestLength();
double n = mdSize * 8.0;
t1 = (int) Math.ceil(n / w);
t2 = (int) Math.ceil((IntegerFunctions.floorLog(t1) + w + 1.0) / w);
t = t1 + t2;
}
/**
* Generate an OTS key pair using the given seed and the message digest and
* PRNG specified via {@link #init(MessageDigest, PRNG)}.
*
* @param seed
* the seed for the PRGN
*/
public void generateKeyPair(byte[] seed) {
generateSignatureKey(seed);
generateVerificationKey();
}
/**
* Generate an OTS signature key the given seed and the message digest and
* PRNG specified via {@link #init(MessageDigest, PRNG)}.
*
* @param seed
* the seed for the PRGN
*/
public void generateSignatureKey(byte[] seed) {
X = new byte[t][mdSize];
for (int i = 0; i < t; i++) {
X[i] = rng.nextSeed(seed);
}
}
/**
* Generate an OTS verification key from the previously generated signature
* key given the message digest specified via
* {@link #init(MessageDigest, PRNG)}.
*
*/
public void generateVerificationKey() {
Y = new byte[t][mdSize];
int repeat = wPowOfTow - 1;
for (int i = 0; i < t; i++) {
Y[i] = md.digest(X[i]);
for (int j = 0; j < repeat - 1; j++) {
Y[i] = md.digest(Y[i]);
}
}
}
/**
* @return the verification key generated via
* {@link #generateKeyPair(byte[])}
*/
public byte[] getVerificationKey() {
byte[] vkey = new byte[t * mdSize];
for (int i = 0; i < t; i++) {
System.arraycopy(Y[i], 0, vkey, i * mdSize, mdSize);
}
return vkey;
}
public int getVerificationKeyLength() {
return t * mdSize;
}
public int getSignatureLength() {
return t * mdSize;
}
/**
* Generate a one-time signature of the given message using the private key
* generated via {@link #generateKeyPair(byte[])}.
*
* @param mBytes
* the message
* @return the one-time signature of the message
*/
public byte[] sign(byte[] mBytes) {
int[] b = generateB(mBytes);
// generate signature
byte[] sig = new byte[t * mdSize];
for (int i = 0; i < t; i++) {
for (int j = 0; j < b[i]; j++) {
X[i] = md.digest(X[i]);
}
System.arraycopy(X[i], 0, sig, i * mdSize, mdSize);
}
return sig;
}
/**
* Verify a one-time signature of the given message using the verification
* key generated via {@link #generateKeyPair(byte[])}.
*
* @param mBytes
* the message
* @param sBytes
* the signature
* @param pBytes
* the verification key
* @return true if signature is valid and false otherwise
*/
public boolean verify(byte[] mBytes, byte[] sBytes, byte[] pBytes) {
byte[] vKey = computeVerificationKey(mBytes, sBytes);
return ByteUtils.equals(md.digest(vKey), md.digest(pBytes));
}
/**
* Compute the verification OTS key from the one-time signature of a
* message. This is *NOT* a complete OTS signature verification, but it
* suffices for usage with CMSS.
*
* @param mBytes
* the message
* @param sBytes
* the one-time signature
* @return the verification OTS key
*/
public byte[] computeVerificationKey(byte[] mBytes, byte[] sBytes) {
int[] b = generateB(mBytes);
int a = wPowOfTow - 1;
byte[] verify = new byte[t * mdSize], sig = new byte[mdSize];
for (int i = 0; i < t; i++) {
b[i] = a - b[i];
System.arraycopy(sBytes, i * mdSize, sig, 0, mdSize);
// apply f(sig) for 2^w-1-b[i] times
for (int j = 0; j < b[i]; j++) {
sig = md.digest(sig);
}
System.arraycopy(sig, 0, verify, i * mdSize, mdSize);
}
return verify;
}
public boolean canComputeVerificationKeyFromSignature() {
return true;
}
/**
* split a binary string into 'num' blocks with length 'bitLength' and
* interpret each block as an integer.
*
* @param sb
* the binary string
* @param num
* number of blocks
* @param step
* the length of each block
* @return an array of integers
*/
private int[] parseBinaryString(BitSet s, int bitLength) {
int block = bitLength % w, num = bitLength / w;
int[] b = new int[block == 0 ? num : num + 1];
int i = 0;
if (block != 0) {
for (int j = 0; j < block; j++) {
if (s.get(block - 1 - j)) {
b[0] += (1 << j);
}
}
i++;
}
int offset = block;
for (; offset < bitLength; offset += w, i++) { // parse b[i]
for (int j = 0; j < w; j++) {
if (s.get(offset + j)) {
b[i] += (1 << (w - 1 - j));
}
}
}
return b;
}
/**
* generate the array b[] (see paper) from the message
*
* @param mBytes
* the message byte array
* @return the array b[]
*/
private int[] generateB(byte[] mBytes) {
int[] b = new int[t];
// binary representation of message digest
byte[] d = md.digest(mBytes);
BitSet bits = fromByteArray(d);
int[] p = parseBinaryString(bits, d.length * 8);
System.arraycopy(p, 0, b, 0, t1);
int c = t1 << w;
for (int i = 0; i < t1; i++) {
c = c - b[i];
}
int length = t2 * w;
bits = fromInteger(c, length); // binary representation of c
p = parseBinaryString(bits, length);
System.arraycopy(p, 0, b, t1, t2);
return b;
}
/**
* Returns a bitSet containing the values in bytes. The bytes are big-endian
*/
private static BitSet fromByteArray(byte[] bytes) {
int bytesLength = bytes.length;
BitSet bits = new BitSet(bytesLength * 8);
int byteOffset, i, j, b;
for (i = 0; i < bytesLength; i++) {
byteOffset = i << 3;
b = 255 & bytes[i];
for (j = 7; b != 0; j--) {
if ((b & 1) != 0) {
bits.set(byteOffset + j);
}
b = b >>> 1;
}
}
return bits;
}
/** Generate Bit String from Integer */
private static BitSet fromInteger(int n, int length) {
BitSet bits = new BitSet();
for (int i = length - 1; n != 0; i--) {
if ((n & 1) != 0) {
bits.set(i);
}
n = n >>> 1;
}
return bits;
}
}
| |
/*
* 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.drill.exec.store.dfs;
import org.apache.drill.common.exceptions.DrillRuntimeException;
import org.apache.drill.exec.util.DrillFileSystemUtil;
import org.apache.drill.shaded.guava.com.google.common.base.Preconditions;
import org.apache.drill.shaded.guava.com.google.common.base.Stopwatch;
import org.apache.drill.shaded.guava.com.google.common.collect.Lists;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
* Jackson serializable description of a file selection.
*/
public class FileSelection {
private static final Logger logger = LoggerFactory.getLogger(FileSelection.class);
private static final String WILD_CARD = "*";
private List<FileStatus> statuses;
public List<Path> files;
/**
* root path for the selections
*/
public final Path selectionRoot;
/**
* root path for the metadata cache file (if any)
*/
public final Path cacheFileRoot;
/**
* metadata context useful for metadata operations (if any)
*/
private MetadataContext metaContext = null;
/**
* Indicates whether this selectionRoot is an empty directory
*/
private boolean emptyDirectory;
private enum StatusType {
NOT_CHECKED, // initial state
NO_DIRS, // no directories in this selection
HAS_DIRS, // directories were found in the selection
EXPANDED_FULLY, // whether selection fully expanded to files
EXPANDED_PARTIAL // whether selection partially expanded to only directories (not files)
}
private StatusType dirStatus;
// whether this selection previously had a wildcard, false by default
private boolean hadWildcard;
// whether all partitions were previously pruned for this selection, false by default
private boolean wasAllPartitionsPruned;
/**
* Creates a {@link FileSelection selection} out of given file statuses/files and selection root.
*
* @param statuses list of file statuses
* @param files list of files
* @param selectionRoot root path for selections
*/
public FileSelection(List<FileStatus> statuses, List<Path> files, Path selectionRoot) {
this(statuses, files, selectionRoot, null, false, StatusType.NOT_CHECKED);
}
public FileSelection(List<FileStatus> statuses, List<Path> files, Path selectionRoot, Path cacheFileRoot,
boolean wasAllPartitionsPruned) {
this(statuses, files, selectionRoot, cacheFileRoot, wasAllPartitionsPruned, StatusType.NOT_CHECKED);
}
public FileSelection(List<FileStatus> statuses, List<Path> files, Path selectionRoot, Path cacheFileRoot,
boolean wasAllPartitionsPruned, StatusType dirStatus) {
this.statuses = statuses;
this.files = files;
this.selectionRoot = selectionRoot;
this.dirStatus = dirStatus;
this.cacheFileRoot = cacheFileRoot;
this.wasAllPartitionsPruned = wasAllPartitionsPruned;
}
/**
* Copy constructor for convenience.
*/
protected FileSelection(FileSelection selection) {
Preconditions.checkNotNull(selection, "File selection cannot be null");
this.statuses = selection.statuses;
this.files = selection.files;
this.selectionRoot = selection.selectionRoot;
this.dirStatus = selection.dirStatus;
this.cacheFileRoot = selection.cacheFileRoot;
this.metaContext = selection.metaContext;
this.hadWildcard = selection.hadWildcard;
this.wasAllPartitionsPruned = selection.wasAllPartitionsPruned;
this.emptyDirectory = selection.emptyDirectory;
}
public Path getSelectionRoot() {
return selectionRoot;
}
public List<FileStatus> getStatuses(DrillFileSystem fs) throws IOException {
Stopwatch timer = logger.isDebugEnabled() ? Stopwatch.createStarted() : null;
if (statuses == null) {
List<FileStatus> newStatuses = new ArrayList<>();
for (Path pathStr : Objects.requireNonNull(files, "Files can not be null if statuses are null")) {
newStatuses.add(fs.getFileStatus(pathStr));
}
statuses = newStatuses;
}
if (timer != null) {
logger.debug("FileSelection.getStatuses() took {} ms, numFiles: {}",
timer.elapsed(TimeUnit.MILLISECONDS), statuses == null ? 0 : statuses.size());
timer.stop();
}
return statuses;
}
public List<Path> getFiles() {
if (files == null) {
files = Objects.requireNonNull(statuses, "Statuses can not be null if files are null").stream()
.map(FileStatus::getPath)
.collect(Collectors.toList());
}
return files;
}
public boolean containsDirectories(DrillFileSystem fs) throws IOException {
if (dirStatus == StatusType.NOT_CHECKED) {
dirStatus = StatusType.NO_DIRS;
for (FileStatus status : getStatuses(fs)) {
if (status.isDirectory()) {
dirStatus = StatusType.HAS_DIRS;
break;
}
}
}
return dirStatus == StatusType.HAS_DIRS;
}
public FileSelection minusDirectories(DrillFileSystem fs) throws IOException {
if (isExpandedFully()) {
return this;
}
Stopwatch timer = logger.isDebugEnabled() ? Stopwatch.createStarted() : null;
List<FileStatus> statuses = getStatuses(fs);
List<FileStatus> nonDirectories = Lists.newArrayList();
for (FileStatus status : statuses) {
nonDirectories.addAll(DrillFileSystemUtil.listFiles(fs, status.getPath(), true));
}
FileSelection fileSel = create(nonDirectories, null, selectionRoot);
if (timer != null) {
logger.debug("FileSelection.minusDirectories() took {} ms, numFiles: {}", timer.elapsed(TimeUnit.MILLISECONDS), statuses.size());
timer.stop();
}
// fileSel will be null if we query an empty folder
if (fileSel != null) {
fileSel.setExpandedFully();
}
return fileSel;
}
public FileStatus getFirstPath(DrillFileSystem fs) throws IOException {
return getStatuses(fs).get(0);
}
public void setExpandedFully() {
this.dirStatus = StatusType.EXPANDED_FULLY;
}
public boolean isExpandedFully() {
return dirStatus == StatusType.EXPANDED_FULLY;
}
public void setExpandedPartial() {
this.dirStatus = StatusType.EXPANDED_PARTIAL;
}
public boolean isExpandedPartial() {
return dirStatus == StatusType.EXPANDED_PARTIAL;
}
public StatusType getDirStatus() {
return dirStatus;
}
public boolean wasAllPartitionsPruned() {
return this.wasAllPartitionsPruned;
}
/**
* Returns longest common path for the given list of files.
*
* @param files list of files.
* @return longest common path
*/
private static Path commonPathForFiles(List<Path> files) {
if (files == null || files.isEmpty()) {
return new Path("/");
}
int total = files.size();
String[][] folders = new String[total][];
int shortest = Integer.MAX_VALUE;
for (int i = 0; i < total; i++) {
folders[i] = files.get(i).toUri().getPath().split(Path.SEPARATOR);
shortest = Math.min(shortest, folders[i].length);
}
int latest;
out:
for (latest = 0; latest < shortest; latest++) {
String current = folders[0][latest];
for (int i = 1; i < folders.length; i++) {
if (!current.equals(folders[i][latest])) {
break out;
}
}
}
URI uri = files.get(0).toUri();
String pathString = buildPath(folders[0], latest);
return new Path(uri.getScheme(), uri.getAuthority(), pathString);
}
private static String buildPath(String[] path, int folderIndex) {
StringBuilder builder = new StringBuilder();
for (int i=0; i<folderIndex; i++) {
builder.append(path[i]).append(Path.SEPARATOR);
}
builder.deleteCharAt(builder.length()-1);
return builder.toString();
}
public static FileSelection create(DrillFileSystem fs, String parent, String path,
boolean allowAccessOutsideWorkspace) throws IOException {
Stopwatch timer = logger.isDebugEnabled() ? Stopwatch.createStarted() : null;
boolean hasWildcard = path.contains(WILD_CARD);
Path combined = new Path(parent, removeLeadingSlash(path));
if (!allowAccessOutsideWorkspace) {
checkBackPaths(new Path(parent).toUri().getPath(), combined.toUri().getPath(), path);
}
FileStatus[] statuses = fs.globStatus(combined); // note: this would expand wildcards
if (statuses == null) {
return null;
}
FileSelection fileSel = create(Arrays.asList(statuses), null, combined);
if (timer != null) {
logger.debug("FileSelection.create() took {} ms ", timer.elapsed(TimeUnit.MILLISECONDS));
timer.stop();
}
if (fileSel == null) {
return null;
}
fileSel.setHadWildcard(hasWildcard);
return fileSel;
}
/**
* Creates a {@link FileSelection selection} with the given file statuses/files and selection root.
*
* @param statuses list of file statuses
* @param files list of files
* @param root root path for selections
* @param cacheFileRoot root path for metadata cache (null for no metadata cache)
* @return null if creation of {@link FileSelection} fails with an {@link IllegalArgumentException}
* otherwise a new selection.
*
* @see FileSelection#FileSelection(List, List, Path)
*/
public static FileSelection create(List<FileStatus> statuses, List<Path> files, Path root,
Path cacheFileRoot, boolean wasAllPartitionsPruned) {
boolean bothNonEmptySelection = (statuses != null && statuses.size() > 0) && (files != null && files.size() > 0);
boolean bothEmptySelection = (statuses == null || statuses.size() == 0) && (files == null || files.size() == 0);
if (bothNonEmptySelection || bothEmptySelection) {
return null;
}
Path selectionRoot;
if (statuses == null || statuses.isEmpty()) {
selectionRoot = commonPathForFiles(files);
} else {
Objects.requireNonNull(root, "Selection root is null");
Path rootPath = handleWildCard(root);
URI uri = statuses.get(0).getPath().toUri();
selectionRoot = new Path(uri.getScheme(), uri.getAuthority(), rootPath.toUri().getPath());
}
return new FileSelection(statuses, files, selectionRoot, cacheFileRoot, wasAllPartitionsPruned);
}
public static FileSelection create(List<FileStatus> statuses, List<Path> files, Path root) {
return FileSelection.create(statuses, files, root, null, false);
}
public static FileSelection createFromDirectories(List<Path> dirPaths, FileSelection selection,
Path cacheFileRoot) {
Stopwatch timer = logger.isDebugEnabled() ? Stopwatch.createStarted() : null;
Path root = selection.getSelectionRoot();
Objects.requireNonNull(root, "Selection root is null");
if (dirPaths == null || dirPaths.isEmpty()) {
throw new DrillRuntimeException("List of directories is null or empty");
}
// for wildcard the directory list should have already been expanded
List<Path> dirs = selection.hadWildcard() ? selection.getFileStatuses().stream()
.map(FileStatus::getPath)
.collect(Collectors.toList()) : new ArrayList<>(dirPaths);
Path rootPath = handleWildCard(root);
URI uri = selection.getFileStatuses().get(0).getPath().toUri();
Path path = new Path(uri.getScheme(), uri.getAuthority(), rootPath.toUri().getPath());
FileSelection fileSel = new FileSelection(null, dirs, path, cacheFileRoot, false);
fileSel.setHadWildcard(selection.hadWildcard());
if (timer != null) {
logger.debug("FileSelection.createFromDirectories() took {} ms ", timer.elapsed(TimeUnit.MILLISECONDS));
timer.stop();
}
return fileSel;
}
private static Path handleWildCard(Path root) {
String stringRoot = root.toUri().getPath();
if (stringRoot.contains(WILD_CARD)) {
int idx = stringRoot.indexOf(WILD_CARD); // first wild card in the path
idx = stringRoot.lastIndexOf('/', idx); // file separator right before the first wild card
String newRoot = stringRoot.substring(0, idx);
return DrillFileSystemUtil.createPathSafe(newRoot);
} else {
return new Path(stringRoot);
}
}
public static String removeLeadingSlash(String path) {
if (!path.isEmpty() && path.charAt(0) == '/') {
String newPath = path.substring(1);
return removeLeadingSlash(newPath);
} else {
return path;
}
}
/**
* Check if the path is a valid sub path under the parent after removing backpaths. Throw an exception if
* it is not. We pass subpath in as a parameter only for the error message
*
* @param parent The parent path (the workspace directory).
* @param combinedPath The workspace directory and (relative) subpath path combined.
* @param subpath For error message only, the subpath
*/
public static void checkBackPaths(String parent, String combinedPath, String subpath) {
Preconditions.checkArgument(!parent.isEmpty(), "Invalid root (" + parent + ") in file selection path.");
Preconditions.checkArgument(!combinedPath.isEmpty(), "Empty path (" + combinedPath + "( in file selection path.");
if (!combinedPath.startsWith(parent)) {
throw new IllegalArgumentException(
String.format("Invalid path [%s] takes you outside the workspace.", subpath));
}
}
public List<FileStatus> getFileStatuses() {
return statuses;
}
public boolean supportsDirPruning() {
if (isExpandedFully() || isExpandedPartial()) {
if (!wasAllPartitionsPruned) {
return true;
}
}
return false;
}
public void setHadWildcard(boolean wc) {
this.hadWildcard = wc;
}
public boolean hadWildcard() {
return this.hadWildcard;
}
public Path getCacheFileRoot() {
return cacheFileRoot;
}
public void setMetaContext(MetadataContext context) {
metaContext = context;
}
public MetadataContext getMetaContext() {
return metaContext;
}
/**
* @return true if this {@link FileSelection#selectionRoot} points to an empty directory, false otherwise
*/
public boolean isEmptyDirectory() {
return emptyDirectory;
}
/**
* Setting {@link FileSelection#emptyDirectory} as true allows to identify this {@link FileSelection#selectionRoot}
* as an empty directory
*/
public void setEmptyDirectoryStatus() {
this.emptyDirectory = true;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("root=").append(selectionRoot);
sb.append("files=[");
sb.append(getFiles().stream()
.map(Path::toString)
.collect(Collectors.joining(", ")));
sb.append("]");
return sb.toString();
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.cache.query.functional;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.apache.geode.cache.AttributesFactory;
import org.apache.geode.cache.AttributesMutator;
import org.apache.geode.cache.CacheWriterException;
import org.apache.geode.cache.DataPolicy;
import org.apache.geode.cache.DiskStore;
import org.apache.geode.cache.DiskStoreFactory;
import org.apache.geode.cache.EntryEvent;
import org.apache.geode.cache.EvictionAction;
import org.apache.geode.cache.EvictionAttributes;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionDestroyedException;
import org.apache.geode.cache.Scope;
import org.apache.geode.cache.query.CacheUtils;
import org.apache.geode.cache.query.IndexType;
import org.apache.geode.cache.query.QueryService;
import org.apache.geode.cache.query.data.Portfolio;
import org.apache.geode.cache.util.CacheWriterAdapter;
import org.apache.geode.test.dunit.ThreadUtils;
import org.apache.geode.test.junit.categories.OQLIndexTest;
@Category({OQLIndexTest.class})
public class IndexCreationDeadLockJUnitTest {
private static final String indexName = "queryTest";
private boolean testFailed = false;
private String cause = "";
private boolean exceptionInCreatingIndex = false;
private Region region;
@Before
public void setUp() throws Exception {
CacheUtils.startCache();
this.testFailed = false;
this.cause = "";
exceptionInCreatingIndex = false;
AttributesFactory factory = new AttributesFactory();
factory.setScope(Scope.DISTRIBUTED_ACK);
factory.setValueConstraint(Portfolio.class);
factory.setIndexMaintenanceSynchronous(true);
region = CacheUtils.createRegion("portfolios", factory.create(), true);
}
@After
public void tearDown() throws Exception {
try {
this.region.localDestroyRegion();
} catch (RegionDestroyedException rde) {
// Ignore
}
CacheUtils.closeCache();
}
/**
* Tests Index creation and maintenance deadlock scenario for in memory region
*/
@Test
public void testIndexCreationDeadLock() throws Exception {
simulateDeadlockScenario();
assertFalse(this.cause, this.testFailed);
assertFalse("Index creation failed", this.exceptionInCreatingIndex);
}
/**
* Tests Index creation and maintenance deadlock scenario for Persistent only disk region
*/
@Test
public void testIndexCreationDeadLockForDiskOnlyRegion() {
this.region.destroyRegion();
AttributesFactory factory = new AttributesFactory();
factory.setScope(Scope.DISTRIBUTED_ACK);
factory.setValueConstraint(Portfolio.class);
factory.setDataPolicy(DataPolicy.PERSISTENT_REPLICATE);
factory.setIndexMaintenanceSynchronous(true);
File dir = new File("test");
dir.mkdir();
DiskStoreFactory dsf = region.getCache().createDiskStoreFactory();
DiskStore ds1 = dsf.setDiskDirs(new File[] {dir}).create("ds1");
factory.setDiskStoreName("ds1");
dir.deleteOnExit();
region = CacheUtils.createRegion("portfolios", factory.create(), true);
simulateDeadlockScenario();
assertFalse(this.cause, this.testFailed);
assertFalse("Index creation failed", this.exceptionInCreatingIndex);
}
/**
* Tests Index creation and maintenance deadlock scenario for a region with stats enabled
*/
@Test
public void testIndexCreationDeadLockForStatsEnabledRegion() {
this.region.destroyRegion();
AttributesFactory factory = new AttributesFactory();
factory.setScope(Scope.DISTRIBUTED_ACK);
factory.setValueConstraint(Portfolio.class);
factory.setStatisticsEnabled(true);
factory.setIndexMaintenanceSynchronous(true);
region = CacheUtils.createRegion("portfolios", factory.create(), true);
simulateDeadlockScenario();
assertFalse(this.cause, this.testFailed);
assertFalse("Index creation failed", this.exceptionInCreatingIndex);
}
/**
* Tests inability to create index on a region which overflows to disk *
*/
@Test
public void testIndexCreationDeadLockForOverflowToDiskRegion() {
this.region.destroyRegion();
AttributesFactory factory = new AttributesFactory();
factory.setScope(Scope.DISTRIBUTED_ACK);
factory.setValueConstraint(Portfolio.class);
factory.setEvictionAttributes(
EvictionAttributes.createLRUEntryAttributes(1, EvictionAction.OVERFLOW_TO_DISK));
factory.setIndexMaintenanceSynchronous(true);
File dir = new File("test");
dir.mkdir();
DiskStoreFactory dsf = region.getCache().createDiskStoreFactory();
DiskStore ds1 = dsf.setDiskDirs(new File[] {dir}).create("ds1");
factory.setDiskStoreName("ds1");
dir.deleteOnExit();
region = CacheUtils.createRegion("portfolios", factory.create(), true);
simulateDeadlockScenario();
assertFalse(this.cause, this.testFailed);
assertTrue("Index creation succeeded . For diskRegion this shoudl not have happened",
this.exceptionInCreatingIndex);
}
private void simulateDeadlockScenario() {
Thread th = new IndexCreationDeadLockJUnitTest.PutThread("put thread");
th.start();
ThreadUtils.join(th, 60 * 1000);
}
/**
* following thread will perform the operations of data population and index creation.
*/
private class HelperThread extends Thread {
public HelperThread(String thName) {
super(thName);
System.out
.println("--------------------- Thread started ------------------------- " + thName);
}
@Override
public void run() {
try {
System.out.println("--------------------- Creating Indices -------------------------");
QueryService qs;
qs = CacheUtils.getQueryService();
qs.createIndex("status", IndexType.FUNCTIONAL, "pf.status",
"/portfolios pf, pf.positions.values posit");
qs.createIndex("secId", IndexType.FUNCTIONAL, "posit.secId",
"/portfolios pf, pf.positions.values posit");
System.out.println("--------------------- Index Creation Done-------------------------");
} catch (Exception e) {
exceptionInCreatingIndex = true;
}
}
}
/**
* thread to put the entries in region
*/
private class PutThread extends Thread {
public PutThread(String thName) {
super(thName);
System.out
.println("--------------------- Thread started ------------------------- " + thName);
}
@Override
public void run() {
try {
System.out.println("--------------------- Populating Data -------------------------");
for (int i = 0; i < 10; i++) {
region.put(String.valueOf(i), new Portfolio(i));
Portfolio value = (Portfolio) region.get(String.valueOf(i));
CacheUtils.log("value for key " + i + " is: " + value);
CacheUtils.log("region.size(): - " + region.size());
}
System.out.println("--------------------- Data Populatio done -------------------------");
System.out.println(
"---------------------Destroying & repopulating the data -------------------------");
AttributesMutator mutator =
IndexCreationDeadLockJUnitTest.this.region.getAttributesMutator();
mutator.setCacheWriter(new BeforeUpdateCallBack());
CacheUtils.log("region.size(): - " + region.size());
for (int i = 0; i < 10; i++) {
region.destroy(String.valueOf(i));
region.put(String.valueOf(i), new Portfolio(i + 20));
}
} catch (Exception e) {
e.printStackTrace();
IndexCreationDeadLockJUnitTest.this.testFailed = true;
IndexCreationDeadLockJUnitTest.this.cause = "Test failed because of exception=" + e;
}
}
}
/**
* make the update to wait for a while before updatation to simulate the deadlock condiction
*/
private class BeforeUpdateCallBack extends CacheWriterAdapter {
int cnt = 0;
@Override
public void beforeCreate(EntryEvent event) throws CacheWriterException {
cnt++;
if (cnt == 10) {
System.out.println(
"--------------------- starting IndexCreation Thread-------------------------");
Thread indxCreationThread = new HelperThread("index creator thread");
indxCreationThread.start();
try {
ThreadUtils.join(indxCreationThread, 30 * 1000);
} catch (Exception e) {
e.printStackTrace();
IndexCreationDeadLockJUnitTest.this.testFailed = true;
IndexCreationDeadLockJUnitTest.this.cause = "Test failed because of exception=" + e;
fail(e.toString());
}
}
}
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.ql.udf.generic;
import java.util.ArrayDeque;
import java.util.Deque;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.apache.hadoop.hive.ql.parse.WindowingSpec.BoundarySpec;
import org.apache.hadoop.hive.ql.plan.ptf.BoundaryDef;
import org.apache.hadoop.hive.ql.plan.ptf.WindowFrameDef;
import org.apache.hadoop.hive.ql.udf.UDFType;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFEvaluator.AggregationBuffer;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFEvaluator.AggregationType;
import org.apache.hadoop.hive.ql.util.JavaDataModel;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils.ObjectInspectorCopyOption;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils;
@Description(name = "max", value = "_FUNC_(expr) - Returns the maximum value of expr")
public class GenericUDAFMax extends AbstractGenericUDAFResolver {
static final Logger LOG = LoggerFactory.getLogger(GenericUDAFMax.class.getName());
@Override
public GenericUDAFEvaluator getEvaluator(TypeInfo[] parameters)
throws SemanticException {
if (parameters.length != 1) {
throw new UDFArgumentTypeException(parameters.length - 1,
"Exactly one argument is expected.");
}
ObjectInspector oi = TypeInfoUtils.getStandardJavaObjectInspectorFromTypeInfo(parameters[0]);
if (!ObjectInspectorUtils.compareSupported(oi)) {
throw new UDFArgumentTypeException(parameters.length - 1,
"Cannot support comparison of map<> type or complex type containing map<>.");
}
return new GenericUDAFMaxEvaluator();
}
@UDFType(distinctLike=true)
public static class GenericUDAFMaxEvaluator extends GenericUDAFEvaluator {
private transient ObjectInspector inputOI;
private transient ObjectInspector outputOI;
@Override
public ObjectInspector init(Mode m, ObjectInspector[] parameters)
throws HiveException {
assert (parameters.length == 1);
super.init(m, parameters);
inputOI = parameters[0];
// Copy to Java object because that saves object creation time.
// Note that on average the number of copies is log(N) so that's not
// very important.
outputOI = ObjectInspectorUtils.getStandardObjectInspector(inputOI,
ObjectInspectorCopyOption.JAVA);
return outputOI;
}
/** class for storing the current max value */
@AggregationType(estimable = true)
static class MaxAgg extends AbstractAggregationBuffer {
Object o;
@Override
public int estimate() {
return JavaDataModel.PRIMITIVES2;
}
}
@Override
public AggregationBuffer getNewAggregationBuffer() throws HiveException {
MaxAgg result = new MaxAgg();
return result;
}
@Override
public void reset(AggregationBuffer agg) throws HiveException {
MaxAgg myagg = (MaxAgg) agg;
myagg.o = null;
}
boolean warned = false;
@Override
public void iterate(AggregationBuffer agg, Object[] parameters)
throws HiveException {
assert (parameters.length == 1);
merge(agg, parameters[0]);
}
@Override
public Object terminatePartial(AggregationBuffer agg) throws HiveException {
return terminate(agg);
}
@Override
public void merge(AggregationBuffer agg, Object partial)
throws HiveException {
if (partial != null) {
MaxAgg myagg = (MaxAgg) agg;
int r = ObjectInspectorUtils.compare(myagg.o, outputOI, partial, inputOI);
if (myagg.o == null || r < 0) {
myagg.o = ObjectInspectorUtils.copyToStandardObject(partial, inputOI,
ObjectInspectorCopyOption.JAVA);
}
}
}
@Override
public Object terminate(AggregationBuffer agg) throws HiveException {
MaxAgg myagg = (MaxAgg) agg;
return myagg.o;
}
@Override
public GenericUDAFEvaluator getWindowingEvaluator(WindowFrameDef wFrmDef) {
return new MaxStreamingFixedWindow(this, wFrmDef);
}
}
/*
* Based on the Paper by Daniel Lemire: Streaming Max-Min filter using no more
* than 3 comparisons per elem.
*
* 1. His algorithm works on fixed size windows up to the current row. For row
* 'i' and window 'w' it computes the min/max for window (i-w, i). 2. The core
* idea is to keep a queue of (max, idx) tuples. A tuple in the queue
* represents the max value in the range (prev tuple.idx, idx). Using the
* queue data structure and following 2 operations it is easy to see that
* maxes can be computed: - on receiving the ith row; drain the queue from the
* back of any entries whose value is less than the ith entry; add the ith
* value as a tuple in the queue (i-val, i) - on the ith step, check if the
* element at the front of the queue has reached its max range of influence;
* i.e. frontTuple.idx + w > i. If yes we can remove it from the queue. - on
* the ith step o/p the front of the queue as the max for the ith entry.
*
* Here we modify the algorithm: 1. to handle window's that are of the form
* (i-p, i+f), where p is numPreceding,f = numFollowing - we start outputing
* rows only after receiving f rows. - the formula for 'influence range' of an
* idx accounts for the following rows. 2. optimize for the case when
* numPreceding is Unbounded. In this case only 1 max needs to be tarcked at
* any given time.
*/
static class MaxStreamingFixedWindow extends
GenericUDAFStreamingEvaluator<Object> {
class State extends GenericUDAFStreamingEvaluator<Object>.StreamingState {
private final Deque<Object[]> maxChain;
public State(AggregationBuffer buf) {
super(buf);
maxChain = new ArrayDeque<Object[]>(wFrameDef.isStartUnbounded() ? 1 : wFrameDef.getWindowSize());
}
@Override
public int estimate() {
if (!(wrappedBuf instanceof AbstractAggregationBuffer)) {
return -1;
}
int underlying = ((AbstractAggregationBuffer) wrappedBuf).estimate();
if (underlying == -1) {
return -1;
}
if (wFrameDef.isStartUnbounded()) {
return -1;
}
/*
* sz Estimate = sz needed by underlying AggBuffer + sz for results + sz
* for maxChain + 3 * JavaDataModel.PRIMITIVES1 sz of results = sz of
* underlying * wdwSz sz of maxChain = sz of underlying * wdwSz
*/
int wdwSz = wFrameDef.getWindowSize();
return underlying + (underlying * wdwSz) + (underlying * wdwSz)
+ (3 * JavaDataModel.PRIMITIVES1);
}
@Override
protected void reset() {
maxChain.clear();
super.reset();
}
}
public MaxStreamingFixedWindow(GenericUDAFEvaluator wrappedEval,
WindowFrameDef wFrmDef) {
super(wrappedEval, wFrmDef);
}
@Override
public AggregationBuffer getNewAggregationBuffer() throws HiveException {
AggregationBuffer underlying = wrappedEval.getNewAggregationBuffer();
return new State(underlying);
}
protected ObjectInspector inputOI() {
return ((GenericUDAFMaxEvaluator) wrappedEval).inputOI;
}
protected ObjectInspector outputOI() {
return ((GenericUDAFMaxEvaluator) wrappedEval).outputOI;
}
@Override
public void iterate(AggregationBuffer agg, Object[] parameters)
throws HiveException {
State s = (State) agg;
Object o = parameters[0];
while (!s.maxChain.isEmpty()) {
if (!removeLast(o, s.maxChain.getLast()[0])) {
break;
} else {
s.maxChain.removeLast();
}
}
// We need to insert 'null' before processing first row for the case: X preceding and y preceding
if (s.numRows == 0) {
for (int i = wFrameDef.getEnd().getRelativeOffset(); i < 0; i++) {
s.results.add(null);
}
}
/*
* add row to chain. except in case of UNB preceding: - only 1 max needs
* to be tracked. - current max will never become out of range. It can
* only be replaced by a larger max.
*/
if (!wFrameDef.isStartUnbounded() || s.maxChain.isEmpty()) {
o = o == null ? null : ObjectInspectorUtils.copyToStandardObject(o,
inputOI(), ObjectInspectorCopyOption.JAVA);
s.maxChain.addLast(new Object[] { o, s.numRows });
}
if (s.hasResultReady()) {
s.results.add(s.maxChain.getFirst()[0]);
}
s.numRows++;
int fIdx = (Integer) s.maxChain.getFirst()[1];
if (!wFrameDef.isStartUnbounded()
&& s.numRows >= fIdx + wFrameDef.getWindowSize()) {
s.maxChain.removeFirst();
}
}
protected boolean removeLast(Object in, Object last) {
return isGreater(in, last);
}
private boolean isGreater(Object in, Object last) {
if (in == null) {
return false;
}
if (last == null) {
return true;
}
return ObjectInspectorUtils.compare(in, inputOI(), last, outputOI()) > 0;
}
@Override
public Object terminate(AggregationBuffer agg) throws HiveException {
State s = (State) agg;
Object[] r = s.maxChain.isEmpty() ? null : s.maxChain.getFirst();
// After all the rows are processed, continue to generate results for the rows that results haven't generated.
// For the case: X following and Y following, process first Y-X results and then insert X nulls.
// For the case X preceding and Y following, process Y results.
for (int i = Math.max(0, wFrameDef.getStart().getRelativeOffset()); i < wFrameDef.getEnd().getRelativeOffset(); i++) {
if (s.hasResultReady()) {
s.results.add(r == null ? null : r[0]);
}
s.numRows++;
if (r != null) {
int fIdx = (Integer) r[1];
if (!wFrameDef.isStartUnbounded()
&& s.numRows >= fIdx + wFrameDef.getWindowSize()
&& !s.maxChain.isEmpty()) {
s.maxChain.removeFirst();
r = !s.maxChain.isEmpty() ? s.maxChain.getFirst() : null;
}
}
}
for (int i = 0; i < wFrameDef.getStart().getRelativeOffset(); i++) {
if (s.hasResultReady()) {
s.results.add(null);
}
s.numRows++;
}
return null;
}
@Override
public int getRowsRemainingAfterTerminate() throws HiveException {
throw new UnsupportedOperationException();
}
}
}
| |
/*
* Created on Jan 9, 2006
*/
package com.foc.join;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import com.foc.Globals;
import com.foc.IFocEnvironment;
import com.foc.desc.FocDesc;
import com.foc.desc.field.FField;
import com.foc.desc.field.FMultipleChoiceStringField;
import com.foc.desc.field.FObjectField;
import com.foc.list.FocListGroupBy;
import com.foc.util.Utils;
/**
* @author 01Barmaja
*/
public class FocRequestDesc {
private FocDesc focDesc = null;
private TableAlias rootTableAlias = null;
private LinkedHashMap<String, TableAlias> aliasMap = null;
private ArrayList<FocRequestField> fieldList = null;
@Deprecated
public FocRequestDesc(FocDesc mainDesc){
aliasMap = new LinkedHashMap<String, TableAlias>();
fieldList = new ArrayList<FocRequestField>();
}
public FocRequestDesc(){
aliasMap = new LinkedHashMap<String, TableAlias>();
fieldList = new ArrayList<FocRequestField>();
}
public void dispose(){
focDesc = null;
if(aliasMap != null){
Iterator iter = aliasMap.values().iterator();
while(iter.hasNext()){
TableAlias tableAlias = (TableAlias) iter.next();
if(tableAlias != null){
tableAlias.dispose();
}
}
aliasMap.clear();
aliasMap = null;
}
if(fieldList != null){
for(int i=0; i<fieldList.size(); i++){
FocRequestField reqFld = (FocRequestField) fieldList.get(i);
if(reqFld != null){
reqFld.dispose();
}
}
fieldList.clear();
fieldList = null;
}
rootTableAlias = null;
}
public TableAlias getRootTableAlias(){
return rootTableAlias;
}
public void addTableAlias(TableAlias tableAlias){
aliasMap.put(tableAlias.getAlias(), tableAlias);
if(tableAlias.getJoinCount() == 0){
rootTableAlias = tableAlias ;
}
}
public TableAlias getTableAlias(String tableAlias){
return aliasMap != null ? aliasMap.get(tableAlias) : null;
}
public void addField(FocRequestField reqField){
if(reqField.getId() != FField.FLD_SYNC_IS_NEW_OBJECT){
fieldList.add(reqField);
}
}
public boolean containsField(int fldId){
boolean contains = false;
Iterator iter = fieldList.iterator();
while(iter != null && iter.hasNext() && !contains){
FocRequestField reqField = (FocRequestField) iter.next();
if(reqField != null && fldId == reqField.getId()){
contains = true;
}
}
return contains;
}
public Iterator newFieldIterator(){
return fieldList.iterator();
}
public Iterator newAliasIterator(){
return aliasMap.values().iterator();
}
public Collection<TableAlias> newAliasArray(){
ArrayList<TableAlias> array = new ArrayList<TableAlias>();
Iterator iter = newAliasIterator();
while(iter != null && iter.hasNext()){
TableAlias alias = (TableAlias) iter.next();
if(alias != null){
array.add(alias);
}
}
Collections.sort(array, new Comparator<TableAlias>() {
@Override
public int compare(TableAlias ta1, TableAlias ta2) {
return ta1.getOrder() - ta2.getOrder();
}
});
return array;
}
public void fillFocDesc(FocDesc focDesc){
if(focDesc != null){
this.focDesc = focDesc;
Iterator iter = fieldList.iterator();
while(iter != null && iter.hasNext()){
FocRequestField reqField = (FocRequestField) iter.next();
if(reqField != null){
if(focDesc.getFieldByID(reqField.getId()) == null){
FField field = reqField.getField();
FField newField = null;
try {
if(field == null){
Globals.showNotification("Field Not Found", "Could not find field:"+reqField.getId(), IFocEnvironment.TYPE_ERROR_MESSAGE);
}else{
newField = (FField) field.cloneWithoutListeners();
newField.setJoinOriginalField(field);
newField.setName(reqField.getTableAlias().getAlias()+"."+field.getName());
if(newField instanceof FObjectField){
FObjectField newObjField = (FObjectField) newField;
newObjField.setKeyPrefix(reqField.getTableAlias().getAlias()+"."+newObjField.getKeyPrefix());
if(!Utils.isStringEmpty(newObjField.getForcedDBName())){
newObjField.setForcedDBName(reqField.getTableAlias().getAlias()+"."+newObjField.getForcedDBName());
}
}
newField.setId(reqField.getId());
if(newField instanceof FMultipleChoiceStringField){
FMultipleChoiceStringField mcsFld = (FMultipleChoiceStringField) newField;
mcsFld.setChoicesSelection_FieldID(field.getID());
}
String groupByFormula = reqField.getGroupByFormula();
if (!Utils.isStringEmpty(groupByFormula)) {
FocListGroupBy groupBy = focDesc.getGroupBy();
if (groupBy != null) {
newField = groupBy.addField_FormulaSingleText(focDesc, newField, groupByFormula, reqField.getGroupByFormula_AdditionalField());
} else {
Globals.logString("Missing Group By expression.");
}
}
}
} catch (CloneNotSupportedException e) {
Globals.logException(e);
}
focDesc.addField(newField);
if(field.getIndexOfPropertyInDummyArray() > 0){
focDesc.addDummyProperty(newField.getID());
}
}
}
}
}
}
public void fillRequestDescWithJoinFields(){
fillRequestDescWithJoinFields(200);
}
public void fillRequestDescWithJoinFields(int firstFieldID){
FocRequestField reqFld = new FocRequestField(firstFieldID++, getRootTableAlias(), FField.REF_FIELD_ID);
addField(reqFld);
Iterator iter = aliasMap.values().iterator();
while(iter != null && iter.hasNext()){
TableAlias tableAlias = (TableAlias) iter.next();
if(tableAlias != null){
for(int i=0; i<tableAlias.getJoinCount(); i++){
Join join = tableAlias.getJoin(i);
if(join != null){
firstFieldID = join.fillRequestDescWithJoinFields(this, firstFieldID);
}
}
}
}
}
public FocDesc getFocDesc() {
return focDesc;
}
public String getLinkCondition(){
StringBuffer str = new StringBuffer();
boolean firstCondition = true;
Iterator iter = newAliasIterator();
while(iter != null && iter.hasNext()){
TableAlias alias =(TableAlias) iter.next();
if(alias != null){
for(int i=0; i<alias.getJoinCount(); i++){
Join join = alias.getJoin(i);
if(join != null){
String joinCondition = join.getLinkCondition();
if(joinCondition != null && joinCondition.length() > 0){
if(!firstCondition){
str.append(" AND ");
}
str.append("(");
str.append(joinCondition);
str.append(")");
firstCondition = false;
}
}
}
}
}
return str.toString();
}
}
| |
/**
* Copyright 2005-2015 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.krms.api.repository.term;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.apache.commons.lang.StringUtils;
import org.jdom.IllegalAddException;
import org.kuali.rice.core.api.CoreConstants;
import org.kuali.rice.core.api.mo.AbstractDataTransferObject;
import org.kuali.rice.core.api.mo.ModelBuilder;
import org.kuali.rice.krms.api.KrmsConstants;
import org.kuali.rice.krms.api.repository.BuilderUtils;
/**
* Immutable DTO for Terms. Construction must be done via the {@link Builder} inner class.
*
* @author Kuali Rice Team (rice.collab@kuali.org)
*
*/
@XmlRootElement(name = TermDefinition.Constants.ROOT_ELEMENT_NAME)
@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = TermDefinition.Constants.TYPE_NAME, propOrder = {
TermDefinition.Elements.ID,
TermDefinition.Elements.SPECIFICATION,
TermDefinition.Elements.DESCRIPTION,
TermDefinition.Elements.PARAMETERS,
CoreConstants.CommonElements.VERSION_NUMBER,
CoreConstants.CommonElements.FUTURE_ELEMENTS
})
public final class TermDefinition extends AbstractDataTransferObject implements TermDefinitionContract {
private static final long serialVersionUID = 1L;
@XmlElement(name = Elements.ID, required=false)
private final String id;
@XmlElement(name = Elements.SPECIFICATION, required=true)
private final TermSpecificationDefinition specification;
@XmlElement(name = Elements.DESCRIPTION, required=false)
private final String description;
@XmlElementWrapper(name = Elements.PARAMETERS, required=false)
@XmlElement(name = "parameter", required=false)
private final List<TermParameterDefinition> parameters;
@XmlElement(name = CoreConstants.CommonElements.VERSION_NUMBER, required = false)
private final Long versionNumber;
@SuppressWarnings("unused")
@XmlAnyElement
private final Collection<org.w3c.dom.Element> _futureElements = null;
/**
* This constructor is for JAXB only. Do not invoke directly.
*/
private TermDefinition() {
id = null;
specification = null;
description = null;
parameters = null;
versionNumber = null;
}
private TermDefinition(Builder builder) {
id = builder.getId();
specification = builder.getSpecification().build();
description = builder.getDescription();
parameters = BuilderUtils.convertFromBuilderList(builder.getParameters());
versionNumber = builder.getVersionNumber();
}
/**
* {@link ModelBuilder} for {@link TermDefinition}s.
*
* @author Kuali Rice Team (rice.collab@kuali.org)
*
*/
public static class Builder implements TermDefinitionContract, ModelBuilder, Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String description;
private TermSpecificationDefinition.Builder specification;
private List<TermParameterDefinition.Builder> parameters;
private Long versionNumber;
private Builder(String id, TermSpecificationDefinition.Builder termSpecificationDefinition,
List<TermParameterDefinition.Builder> termParameters) {
setId(id);
setSpecification(termSpecificationDefinition);
setParameters(termParameters);
}
/**
* static factory for creating a {@link Builder}.
*
* @param id may be null.
* @param termSpecification must not be null.
* @param termParameters may be null.
*/
public static Builder create(String id, TermSpecificationDefinition.Builder termSpecification,
List<TermParameterDefinition.Builder> termParameters) {
return new Builder(id, termSpecification, termParameters);
}
/**
* static factory for creating a {@link Builder} from a {@link TermDefinitionContract}.
*
* @param term must be non-null.
*/
public static Builder create(TermDefinitionContract term) {
if (term == null) throw new IllegalAddException("term may not be null");
// Convert TermParameterDefinitionContract to TermParameterDefinition:
List<TermParameterDefinition.Builder> outParams =
BuilderUtils.transform(term.getParameters(), TermParameterDefinition.Builder.toBuilder);
Builder builder = create(term.getId(),
// doing my TermSpecificationDefinitionContract conversion inline:
TermSpecificationDefinition.Builder.create(term.getSpecification()),
// this is made immutable in the setter
outParams
);
builder.setDescription(term.getDescription());
builder.setVersionNumber(term.getVersionNumber());
return builder;
}
public void setDescription(String description) {
this.description = description;
}
// Builder setters:
/**
* @param id the id to set. Should be null to build {@link TermDefinition}s for creation operations.
* @throws IllegalArgumentException if the id is non-null and only contains whitespace
*/
public void setId(String id) {
if (id != null && StringUtils.isBlank(id)) {
throw new IllegalArgumentException("id must contain non-whitespace chars");
}
this.id = id;
}
/**
* @param termSpecification the termSpecification to set
* @throws IllegalArgumentException if termSpecification is null
*/
public void setSpecification(TermSpecificationDefinition.Builder termSpecification) {
if (termSpecification == null) {
throw new IllegalArgumentException("termSpecification must not be null");
}
this.specification = termSpecification;
}
/**
* @param parameters the termParameters to set. May be null, or empty.
*/
public void setParameters(List<TermParameterDefinition.Builder> parameters) {
this.parameters = parameters;
}
/**
* @param versionNumber the versionNumber to set. May be null.
*/
public void setVersionNumber(Long versionNumber){
this.versionNumber = versionNumber;
}
// Builder getters:
/**
* @return the id
*/
@Override
public String getId() {
return id;
}
/**
* @return the termSpecification
*/
@Override
public TermSpecificationDefinition.Builder getSpecification() {
return specification;
}
@Override
public String getDescription() {
return description;
}
/**
* @return the termParameters
*/
@Override
public List<TermParameterDefinition.Builder> getParameters() {
return parameters;
}
/**
* @return the version number
*/
@Override
public Long getVersionNumber() {
return this.versionNumber;
}
/**
* Builds the {@link TermDefinition}, or dies trying.
*
* @see org.kuali.rice.core.api.mo.ModelBuilder#build()
* @throws IllegalStateException if builder validation fails
*/
@Override
public TermDefinition build() {
return new TermDefinition(this);
}
}
/**
* @return the termId. May be null if this {@link TermDefinition} hasn't been persisted.
*/
@Override
public String getId() {
return this.id;
}
/**
* @return the specification. Will never be null.
*/
@Override
public TermSpecificationDefinition getSpecification() {
return this.specification;
}
@Override
public String getDescription() {
return description;
}
/**
* @return the parameters. May be empty, but will never be null.
*/
@Override
public List<TermParameterDefinition> getParameters() {
return this.parameters;
}
/**
* @see org.kuali.rice.core.api.mo.common.Versioned#getVersionNumber()
*/
@Override
public Long getVersionNumber() {
return versionNumber;
}
static class Constants {
public static final String ROOT_ELEMENT_NAME = "termDefinition";
public static final String TYPE_NAME = "termDefinitionType";
}
static class Elements {
public static final String ID = "id";
public static final String SPECIFICATION = "specification";
public static final String PARAMETERS = "parameters";
public static final String DESCRIPTION = "description";
}
public static class Cache {
public static final String NAME = KrmsConstants.Namespaces.KRMS_NAMESPACE_2_0 + "/" + TermDefinition.Constants.TYPE_NAME;
}
}
| |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.debugger.actions;
import com.intellij.debugger.DebuggerBundle;
import com.intellij.debugger.DebuggerManagerEx;
import com.intellij.debugger.engine.DebugProcessImpl;
import com.intellij.debugger.engine.events.DebuggerCommandImpl;
import com.intellij.debugger.impl.DebuggerContextImpl;
import com.intellij.debugger.impl.DebuggerSession;
import com.intellij.debugger.impl.DebuggerUtilsEx;
import com.intellij.debugger.jdi.VirtualMachineProxyImpl;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.project.Project;
import com.intellij.unscramble.ThreadDumpParser;
import com.intellij.unscramble.ThreadState;
import com.intellij.util.SmartList;
import com.intellij.xdebugger.XDebugSession;
import com.sun.jdi.*;
import gnu.trove.TIntObjectHashMap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ThreadDumpAction extends AnAction implements AnAction.TransparentUpdate {
public void actionPerformed(AnActionEvent e) {
final Project project = e.getProject();
if (project == null) {
return;
}
DebuggerContextImpl context = (DebuggerManagerEx.getInstanceEx(project)).getContext();
final DebuggerSession session = context.getDebuggerSession();
if(session != null && session.isAttached()) {
final DebugProcessImpl process = context.getDebugProcess();
process.getManagerThread().invoke(new DebuggerCommandImpl() {
protected void action() {
final VirtualMachineProxyImpl vm = process.getVirtualMachineProxy();
vm.suspend();
try {
final List<ThreadState> threads = buildThreadStates(vm);
ApplicationManager.getApplication().invokeLater(() -> {
XDebugSession xSession = session.getXDebugSession();
if (xSession != null) {
DebuggerUtilsEx.addThreadDump(project, threads, xSession.getUI(), session);
}
}, ModalityState.NON_MODAL);
}
finally {
vm.resume();
}
}
});
}
}
public static List<ThreadState> buildThreadStates(VirtualMachineProxyImpl vmProxy) {
final List<ThreadReference> threads = vmProxy.getVirtualMachine().allThreads();
final List<ThreadState> result = new ArrayList<>();
final Map<String, ThreadState> nameToThreadMap = new HashMap<>();
final Map<String, String> waitingMap = new HashMap<>(); // key 'waits_for' value
for (ThreadReference threadReference : threads) {
final StringBuilder buffer = new StringBuilder();
boolean hasEmptyStack = true;
final int threadStatus = threadReference.status();
if (threadStatus == ThreadReference.THREAD_STATUS_ZOMBIE) {
continue;
}
final String threadName = threadName(threadReference);
final ThreadState threadState = new ThreadState(threadName, threadStatusToState(threadStatus));
nameToThreadMap.put(threadName, threadState);
result.add(threadState);
threadState.setJavaThreadState(threadStatusToJavaThreadState(threadStatus));
buffer.append("\"").append(threadName).append("\"");
ReferenceType referenceType = threadReference.referenceType();
if (referenceType != null) {
//noinspection HardCodedStringLiteral
Field daemon = referenceType.fieldByName("daemon");
if (daemon != null) {
Value value = threadReference.getValue(daemon);
if (value instanceof BooleanValue && ((BooleanValue)value).booleanValue()) {
buffer.append(" ").append(DebuggerBundle.message("threads.export.attribute.label.daemon"));
threadState.setDaemon(true);
}
}
//noinspection HardCodedStringLiteral
Field priority = referenceType.fieldByName("priority");
if (priority != null) {
Value value = threadReference.getValue(priority);
if (value instanceof IntegerValue) {
buffer.append(" ").append(DebuggerBundle.message("threads.export.attribute.label.priority", ((IntegerValue)value).intValue()));
}
}
Field tid = referenceType.fieldByName("tid");
if (tid != null) {
Value value = threadReference.getValue(tid);
if (value instanceof LongValue) {
buffer.append(" ").append(DebuggerBundle.message("threads.export.attribute.label.tid", Long.toHexString(((LongValue)value).longValue())));
buffer.append(" nid=NA");
}
}
}
//ThreadGroupReference groupReference = threadReference.threadGroup();
//if (groupReference != null) {
// buffer.append(", ").append(DebuggerBundle.message("threads.export.attribute.label.group", groupReference.name()));
//}
final String state = threadState.getState();
if (state != null) {
buffer.append(" ").append(state);
}
buffer.append("\n java.lang.Thread.State: ").append(threadState.getJavaThreadState());
try {
if (vmProxy.canGetOwnedMonitorInfo() && vmProxy.canGetMonitorInfo()) {
List<ObjectReference> list = threadReference.ownedMonitors();
for (ObjectReference reference : list) {
if (!vmProxy.canGetMonitorFrameInfo()) { // java 5 and earlier
buffer.append("\n\t ").append(renderLockedObject(reference));
}
final List<ThreadReference> waiting = reference.waitingThreads();
for (ThreadReference thread : waiting) {
final String waitingThreadName = threadName(thread);
waitingMap.put(waitingThreadName, threadName);
buffer.append("\n\t ").append(DebuggerBundle.message("threads.export.attribute.label.blocks.thread", waitingThreadName));
}
}
}
ObjectReference waitedMonitor = vmProxy.canGetCurrentContendedMonitor() ? threadReference.currentContendedMonitor() : null;
if (waitedMonitor != null) {
if (vmProxy.canGetMonitorInfo()) {
ThreadReference waitedMonitorOwner = waitedMonitor.owningThread();
if (waitedMonitorOwner != null) {
final String monitorOwningThreadName = threadName(waitedMonitorOwner);
waitingMap.put(threadName, monitorOwningThreadName);
buffer.append("\n\t ")
.append(DebuggerBundle.message("threads.export.attribute.label.waiting.for.thread", monitorOwningThreadName, renderObject(waitedMonitor)));
}
}
}
final List<StackFrame> frames = threadReference.frames();
hasEmptyStack = frames.size() == 0;
final TIntObjectHashMap<List<ObjectReference>> lockedAt = new TIntObjectHashMap<>();
if (vmProxy.canGetMonitorFrameInfo()) {
for (MonitorInfo info : threadReference.ownedMonitorsAndFrames()) {
final int stackDepth = info.stackDepth();
List<ObjectReference> monitors;
if ((monitors = lockedAt.get(stackDepth)) == null) {
lockedAt.put(stackDepth, monitors = new SmartList<>());
}
monitors.add(info.monitor());
}
}
for (int i = 0, framesSize = frames.size(); i < framesSize; i++) {
final StackFrame stackFrame = frames.get(i);
try {
final Location location = stackFrame.location();
buffer.append("\n\t ").append(renderLocation(location));
final List<ObjectReference> monitors = lockedAt.get(i);
if (monitors != null) {
for (ObjectReference monitor : monitors) {
buffer.append("\n\t - ").append(renderLockedObject(monitor));
}
}
}
catch (InvalidStackFrameException e) {
buffer.append("\n\t Invalid stack frame: ").append(e.getMessage());
}
}
}
catch (IncompatibleThreadStateException e) {
buffer.append("\n\t ").append(DebuggerBundle.message("threads.export.attribute.error.incompatible.state"));
}
threadState.setStackTrace(buffer.toString(), hasEmptyStack);
ThreadDumpParser.inferThreadStateDetail(threadState);
}
for (String waiting : waitingMap.keySet()) {
final ThreadState waitingThread = nameToThreadMap.get(waiting);
final ThreadState awaitedThread = nameToThreadMap.get(waitingMap.get(waiting));
if (waitingThread != null && awaitedThread != null) { //zombie
awaitedThread.addWaitingThread(waitingThread);
}
}
// detect simple deadlocks
for (ThreadState thread : result) {
for (ThreadState awaitingThread : thread.getAwaitingThreads()) {
if (awaitingThread.isAwaitedBy(thread)) {
thread.addDeadlockedThread(awaitingThread);
awaitingThread.addDeadlockedThread(thread);
}
}
}
ThreadDumpParser.sortThreads(result);
return result;
}
private static String renderLockedObject(ObjectReference monitor) {
return DebuggerBundle.message("threads.export.attribute.label.locked", renderObject(monitor));
}
public static String renderObject(ObjectReference monitor) {
String monitorTypeName;
try {
monitorTypeName = monitor.referenceType().name();
}
catch (Throwable e) {
monitorTypeName = "Error getting object type: '" + e.getMessage() + "'";
}
return DebuggerBundle.message("threads.export.attribute.label.object-id", Long.toHexString(monitor.uniqueID()), monitorTypeName);
}
private static String threadStatusToJavaThreadState(int status) {
switch (status) {
case ThreadReference.THREAD_STATUS_MONITOR:
return Thread.State.BLOCKED.name();
case ThreadReference.THREAD_STATUS_NOT_STARTED:
return Thread.State.NEW.name();
case ThreadReference.THREAD_STATUS_RUNNING:
return Thread.State.RUNNABLE.name();
case ThreadReference.THREAD_STATUS_SLEEPING:
return Thread.State.TIMED_WAITING.name();
case ThreadReference.THREAD_STATUS_WAIT:
return Thread.State.WAITING.name();
case ThreadReference.THREAD_STATUS_ZOMBIE:
return Thread.State.TERMINATED.name();
case ThreadReference.THREAD_STATUS_UNKNOWN:
return "unknown";
default:
return "undefined";
}
}
private static String threadStatusToState(int status) {
switch (status) {
case ThreadReference.THREAD_STATUS_MONITOR:
return "waiting for monitor entry";
case ThreadReference.THREAD_STATUS_NOT_STARTED:
return "not started";
case ThreadReference.THREAD_STATUS_RUNNING:
return "runnable";
case ThreadReference.THREAD_STATUS_SLEEPING:
return "sleeping";
case ThreadReference.THREAD_STATUS_WAIT:
return "waiting";
case ThreadReference.THREAD_STATUS_ZOMBIE:
return "zombie";
case ThreadReference.THREAD_STATUS_UNKNOWN:
return "unknown";
default:
return "undefined";
}
}
public static String renderLocation(final Location location) {
return DebuggerBundle.message("export.threads.stackframe.format",
DebuggerUtilsEx.getLocationMethodQName(location),
DebuggerUtilsEx.getSourceName(location, e -> "Unknown Source"),
DebuggerUtilsEx.getLineNumber(location, false));
}
private static String threadName(ThreadReference threadReference) {
return threadReference.name() + "@" + threadReference.uniqueID();
}
public void update(AnActionEvent e){
Presentation presentation = e.getPresentation();
Project project = e.getProject();
if (project == null) {
presentation.setEnabled(false);
return;
}
DebuggerSession debuggerSession = (DebuggerManagerEx.getInstanceEx(project)).getContext().getDebuggerSession();
presentation.setEnabled(debuggerSession != null && debuggerSession.isAttached());
}
}
| |
/*
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/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.kra.committee.rules;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.kuali.coeus.common.committee.impl.bo.CommitteeMembershipRole;
import org.kuali.coeus.common.committee.impl.rule.event.AddCommitteeMembershipEvent;
import org.kuali.coeus.common.committee.impl.rule.event.AddCommitteeMembershipRoleEvent;
import org.kuali.kra.committee.bo.CommitteeMembership;
import org.kuali.kra.committee.document.CommitteeDocument;
import org.kuali.kra.infrastructure.Constants;
import org.kuali.kra.infrastructure.KeyConstants;
import java.sql.Date;
import static org.junit.Assert.*;
/**
* Test the Committee Membership Add Rules
*/
public class CommitteeMembershipAddRuleTest extends CommitteeRuleTestBase {
private org.kuali.coeus.common.committee.impl.rules.CommitteeMembershipRule rule;
@Before
public void setup() throws Exception {
super.setUp();
rule = new org.kuali.coeus.common.committee.impl.rules.CommitteeMembershipRule();
}
@After
public void tearDown() throws Exception {
rule = null;
super.tearDown();
}
/**
* Test adding a committee membership without a person id or rolodex id.
* This is not allowed
*/
@Test
public void testAddCommitteeMembershipWithNoId() throws Exception {
CommitteeMembership newCommitteeMembership = new CommitteeMembership();
assertFalse(rule.processAddCommitteeMembershipBusinessRules(getAddCommitteeMembershipEvent(newCommitteeMembership)));
assertError("committeeHelper.newCommitteeMembership.personName", KeyConstants.ERROR_COMMITTEE_MEMBERSHIP_PERSON_NOT_SPECIFIED);
}
/**
* Test adding a committee membership with a person id.
*/
@Test
public void testAddCommitteeMembershipWithPersonId() throws Exception {
CommitteeMembership newCommitteeMembership = new CommitteeMembership();
newCommitteeMembership.setPersonId("jtester");
//newCommitteeMembership.setRolodexId(123);
newCommitteeMembership.setPersonName("jtester");
boolean result =rule.processAddCommitteeMembershipBusinessRules(getAddCommitteeMembershipEvent(newCommitteeMembership));
assertTrue(result);
}
/**
* Test adding a committee membership with a person id.
*/
@Test
public void testAddCommitteeMembershipWithRolodexId() throws Exception {
CommitteeMembership newCommitteeMembership = new CommitteeMembership();
//newCommitteeMembership.setPersonId("jtester");
newCommitteeMembership.setRolodexId(123);
newCommitteeMembership.setPersonName("jtester");
boolean result =rule.processAddCommitteeMembershipBusinessRules(getAddCommitteeMembershipEvent(newCommitteeMembership));
assertTrue(result);
}
@Test
public void testAddCommitteeMembershipWithPersonName() throws Exception {
CommitteeMembership newCommitteeMembership = new CommitteeMembership();
newCommitteeMembership.setPersonId("jtester");
newCommitteeMembership.setRolodexId(123);
assertFalse(rule.processAddCommitteeMembershipBusinessRules(getAddCommitteeMembershipEvent(newCommitteeMembership)));
assertError("committeeHelper.newCommitteeMembership.personName", KeyConstants.ERROR_COMMITTEE_MEMBERHSIP_PERSON_NO_NAME);
}
/**
* Test adding a role without a missing role type.
*/
@Test
public void testAddCommitteeMembershipRoleWithoutRole() throws Exception {
CommitteeMembershipRole newCommitteeMembershipRole = new CommitteeMembershipRole();
newCommitteeMembershipRole.setStartDate(Date.valueOf("2009-01-01"));
newCommitteeMembershipRole.setEndDate(Date.valueOf("2009-01-31"));
assertFalse(rule.processAddCommitteeMembershipRoleBusinessRules(getAddCommitteeMembershipRoleEvent(new CommitteeMembership(),
newCommitteeMembershipRole)));
assertError("committeeHelper.newCommitteeMembershipRoles[0].membershipRoleCode",
KeyConstants.ERROR_COMMITTEE_MEMBERSHIP_ROLE_NOT_SPECIFIED);
}
/**
* Test adding a role without a start date.
*/
@Test
public void testAddCommitteeMembershipRoleWithoutStartDate() throws Exception {
CommitteeMembershipRole newCommitteeMembershipRole = new CommitteeMembershipRole();
newCommitteeMembershipRole.setMembershipRoleCode("1");
newCommitteeMembershipRole.setEndDate(Date.valueOf("2009-01-31"));
assertFalse(rule.processAddCommitteeMembershipRoleBusinessRules(getAddCommitteeMembershipRoleEvent(new CommitteeMembership(),
newCommitteeMembershipRole)));
assertError("committeeHelper.newCommitteeMembershipRoles[0].startDate",
KeyConstants.ERROR_COMMITTEE_MEMBERSHIP_ROLE_START_DATE_NOT_SPECIFIED);
}
/**
* Test adding a role without a end date.
*/
@Test
public void testAddCommitteeMembershipRoleWithoutEndDate() throws Exception {
CommitteeMembershipRole newCommitteeMembershipRole = new CommitteeMembershipRole();
newCommitteeMembershipRole.setMembershipRoleCode("1");
newCommitteeMembershipRole.setStartDate(Date.valueOf("2009-01-01"));
assertFalse(rule.processAddCommitteeMembershipRoleBusinessRules(getAddCommitteeMembershipRoleEvent(new CommitteeMembership(),
newCommitteeMembershipRole)));
assertError("committeeHelper.newCommitteeMembershipRoles[0].endDate",
KeyConstants.ERROR_COMMITTEE_MEMBERSHIP_ROLE_END_DATE_NOT_SPECIFIED);
}
/**
* Test adding a role where the end date is before the start date.
*/
@Test
public void testAddCommitteeMembershipRoleWithEndDateBeforeStartDate() throws Exception {
CommitteeMembershipRole newCommitteeMembershipRole = new CommitteeMembershipRole();
newCommitteeMembershipRole.setMembershipRoleCode("1");
newCommitteeMembershipRole.setStartDate(Date.valueOf("2009-01-31"));
newCommitteeMembershipRole.setEndDate(Date.valueOf("2009-01-01"));
assertFalse(rule.processAddCommitteeMembershipRoleBusinessRules(getAddCommitteeMembershipRoleEvent(new CommitteeMembership(),
newCommitteeMembershipRole)));
assertError("committeeHelper.newCommitteeMembershipRoles[0].endDate",
KeyConstants.ERROR_COMMITTEE_MEMBERSHIP_ROLE_END_DATE_BEFORE_ROLE_START_DATE);
}
/**
* Test adding a role where the start date is outside of the term of the committee membership.
*/
@Test
public void testAddCommitteeMembershipRoleWithStartDateOutsideTerm() throws Exception {
CommitteeMembership committeeMembership = new CommitteeMembership();
committeeMembership.setTermStartDate(Date.valueOf("2009-01-10"));
committeeMembership.setTermEndDate(Date.valueOf("2009-01-20"));
CommitteeMembershipRole newCommitteeMembershipRole = new CommitteeMembershipRole();
newCommitteeMembershipRole.setMembershipRoleCode("1");
newCommitteeMembershipRole.setStartDate(Date.valueOf("2009-01-01"));
newCommitteeMembershipRole.setEndDate(Date.valueOf("2009-01-17"));
assertFalse(rule.processAddCommitteeMembershipRoleBusinessRules(getAddCommitteeMembershipRoleEvent(committeeMembership,
newCommitteeMembershipRole)));
assertError("committeeHelper.newCommitteeMembershipRoles[0].startDate",
KeyConstants.ERROR_COMMITTEE_MEMBERSHIP_ROLE_START_DATE_OUTSIDE_TERM);
}
/**
* Test adding a role where the start date is outside of the term of the committee membership.
*/
@Test
public void testAddCommitteeMembershipRoleWithEndDateOutsideTerm() throws Exception {
CommitteeMembership committeeMembership = new CommitteeMembership();
committeeMembership.setTermStartDate(Date.valueOf("2009-01-10"));
committeeMembership.setTermEndDate(Date.valueOf("2009-01-20"));
CommitteeMembershipRole newCommitteeMembershipRole = new CommitteeMembershipRole();
newCommitteeMembershipRole.setMembershipRoleCode("1");
newCommitteeMembershipRole.setStartDate(Date.valueOf("2009-01-15"));
newCommitteeMembershipRole.setEndDate(Date.valueOf("2009-01-31"));
assertFalse(rule.processAddCommitteeMembershipRoleBusinessRules(getAddCommitteeMembershipRoleEvent(committeeMembership,
newCommitteeMembershipRole)));
assertError("committeeHelper.newCommitteeMembershipRoles[0].endDate",
KeyConstants.ERROR_COMMITTEE_MEMBERSHIP_ROLE_END_DATE_OUTSIDE_TERM);
}
/**
* Test adding a role where the role's start/end date overlaps with another role's start/end date
* that has the same role type.
*/
@Test
public void testAddCommitteeMembershipRoleWhichOverlapsAnotherRole() throws Exception {
CommitteeMembership committeeMembership = new CommitteeMembership();
CommitteeMembershipRole newCommitteeMembershipRole = new CommitteeMembershipRole();
newCommitteeMembershipRole.setMembershipRoleCode("1");
newCommitteeMembershipRole.setStartDate(Date.valueOf("2009-01-01"));
newCommitteeMembershipRole.setEndDate(Date.valueOf("2009-01-15"));
committeeMembership.getMembershipRoles().add(newCommitteeMembershipRole);
newCommitteeMembershipRole.setStartDate(Date.valueOf("2009-01-10"));
newCommitteeMembershipRole.setEndDate(Date.valueOf("2009-01-31"));
assertFalse(rule.processAddCommitteeMembershipRoleBusinessRules(getAddCommitteeMembershipRoleEvent(committeeMembership,
newCommitteeMembershipRole)));
assertError("committeeHelper.newCommitteeMembershipRoles[0].membershipRoleCode",
KeyConstants.ERROR_COMMITTEE_MEMBERSHIP_ROLE_DUPLICATE);
}
/**
* Test adding a role to a committee having two existing roles. One of the same role type but without
* Overlapping dates. The other of a different role type but with overlapping dates.
*/
@Test
public void testAddCommitteeMembershipRoleWithNoErrors() throws Exception {
CommitteeMembership committeeMembership = new CommitteeMembership();
committeeMembership.setTermStartDate(Date.valueOf("2009-01-01"));
committeeMembership.setTermEndDate(Date.valueOf("2009-01-31"));
CommitteeMembershipRole committeeMembershipRole = new CommitteeMembershipRole();
committeeMembershipRole.setMembershipRoleCode("1");
committeeMembershipRole.setStartDate(Date.valueOf("2009-01-05"));
committeeMembershipRole.setEndDate(Date.valueOf("2009-01-14"));
committeeMembership.getMembershipRoles().add(committeeMembershipRole);
committeeMembershipRole = new CommitteeMembershipRole();
committeeMembershipRole.setMembershipRoleCode("2");
committeeMembershipRole.setStartDate(Date.valueOf("2009-01-19"));
committeeMembershipRole.setEndDate(Date.valueOf("2009-01-28"));
committeeMembership.getMembershipRoles().add(committeeMembershipRole);
committeeMembershipRole = new CommitteeMembershipRole();
committeeMembershipRole.setMembershipRoleCode("1");
committeeMembershipRole.setStartDate(Date.valueOf("2009-01-20"));
committeeMembershipRole.setEndDate(Date.valueOf("2009-01-31"));
assertTrue(rule.processAddCommitteeMembershipRoleBusinessRules(getAddCommitteeMembershipRoleEvent(committeeMembership,
committeeMembershipRole)));
}
/**
* this method creates an <code>AddCommitteeMembershipEvent</code>
*
* @param newCommitteeMembership
* @return event
* @throws Exception
*/
private AddCommitteeMembershipEvent getAddCommitteeMembershipEvent(CommitteeMembership newCommitteeMembership) throws Exception {
CommitteeDocument document = getNewCommitteeDocument();
AddCommitteeMembershipEvent event = new AddCommitteeMembershipEvent(Constants.EMPTY_STRING, document, newCommitteeMembership);
return event;
}
/**
* this method creates an <code>AddCommitteeMembershipRoleEvent</code>
*
* @param newCommitteeMembershipRole
* @return event
* @throws Exception
*/
private AddCommitteeMembershipRoleEvent getAddCommitteeMembershipRoleEvent(CommitteeMembership committeeMembership,
CommitteeMembershipRole newCommitteeMembershipRole) throws Exception {
CommitteeDocument document = getNewCommitteeDocument();
document.getCommittee().getCommitteeMemberships().add(committeeMembership);
AddCommitteeMembershipRoleEvent event = new AddCommitteeMembershipRoleEvent(Constants.EMPTY_STRING, document,
newCommitteeMembershipRole, 0);
return event;
}
}
| |
/*
* 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.axis2.transport.http;
import org.apache.axiom.om.OMAttribute;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMOutputFormat;
import org.apache.axis2.AxisFault;
import org.apache.axis2.Constants;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.context.OperationContext;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.description.TransportOutDescription;
import org.apache.axis2.i18n.Messages;
import org.apache.axis2.transport.MessageFormatter;
import org.apache.axis2.transport.TransportUtils;
import org.apache.axis2.transport.http.util.HTTPProxyConfigurationUtil;
import org.apache.axis2.util.JavaUtils;
import org.apache.axis2.util.MessageProcessorSelector;
import org.apache.axis2.wsdl.WSDLConstants;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HeaderElement;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.HttpVersion;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NTCredentials;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthPolicy;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpHeaders;
import org.apache.http.protocol.HTTP;
import javax.xml.namespace.QName;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.zip.GZIPInputStream;
public abstract class AbstractHTTPSender {
protected static final String ANONYMOUS = "anonymous";
protected static final String PROXY_HOST_NAME = "proxy_host";
protected static final String PROXY_PORT = "proxy_port";
protected boolean chunked = false;
protected String httpVersion = HTTPConstants.HEADER_PROTOCOL_11;
private static final Log log = LogFactory.getLog(AbstractHTTPSender.class);
protected static final String PROTOCOL_HTTP = "http";
protected static final String PROTOCOL_HTTPS = "https";
/**
* proxydiscription
*/
protected TransportOutDescription proxyOutSetting = null;
protected OMOutputFormat format = new OMOutputFormat();
/**
* isAllowedRetry will be using to check where the
* retry should be allowed or not.
*/
protected boolean isAllowedRetry = false;
public void setChunked(boolean chunked) {
this.chunked = chunked;
}
public void setHttpVersion(String version) throws AxisFault {
if (version != null) {
if (HTTPConstants.HEADER_PROTOCOL_11.equals(version)) {
this.httpVersion = HTTPConstants.HEADER_PROTOCOL_11;
} else if (HTTPConstants.HEADER_PROTOCOL_10.equals(version)) {
this.httpVersion = HTTPConstants.HEADER_PROTOCOL_10;
// chunked is not possible with HTTP/1.0
this.chunked = false;
} else {
throw new AxisFault(
"Parameter " + HTTPConstants.PROTOCOL_VERSION
+ " Can have values only HTTP/1.0 or HTTP/1.1");
}
}
}
/**
* Collect the HTTP header information and set them in the message context
*
* @param method HttpMethodBase from which to get information
* @param msgContext the MessageContext in which to place the information... OR NOT!
* @throws AxisFault if problems occur
*/
protected void obtainHTTPHeaderInformation(HttpMethodBase method,
MessageContext msgContext) throws AxisFault {
// Set RESPONSE properties onto the REQUEST message context. They will need to be copied off the request context onto
// the response context elsewhere, for example in the OutInOperationClient.
Map transportHeaders = new CommonsTransportHeaders(method.getResponseHeaders());
msgContext.setProperty(MessageContext.TRANSPORT_HEADERS, transportHeaders);
msgContext.setProperty(HTTPConstants.MC_HTTP_STATUS_CODE, new Integer(method.getStatusCode()));
Header header = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE);
if (header != null) {
HeaderElement[] headers = header.getElements();
MessageContext inMessageContext = msgContext.getOperationContext().getMessageContext(
WSDLConstants.MESSAGE_LABEL_IN_VALUE);
Object contentType = header.getValue();
Object charSetEnc = null;
for (int i = 0; i < headers.length; i++) {
NameValuePair charsetEnc = headers[i].getParameterByName(
HTTPConstants.CHAR_SET_ENCODING);
if (charsetEnc != null) {
charSetEnc = charsetEnc.getValue();
}
}
if (inMessageContext != null) {
inMessageContext
.setProperty(Constants.Configuration.CONTENT_TYPE, contentType);
inMessageContext
.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc);
} else {
// Transport details will be stored in a HashMap so that anybody interested can
// retrieve them
HashMap transportInfoMap = new HashMap();
transportInfoMap.put(Constants.Configuration.CONTENT_TYPE, contentType);
transportInfoMap.put(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc);
//the HashMap is stored in the outgoing message.
msgContext.setProperty(Constants.Configuration.TRANSPORT_INFO_MAP,
transportInfoMap);
}
}
String sessionCookie = null;
// Process old style headers first
Header[] cookieHeaders = method.getResponseHeaders(HTTPConstants.HEADER_SET_COOKIE);
String customCoookiId = (String) msgContext.getProperty(Constants.CUSTOM_COOKIE_ID);
// process all the cookieHeaders, when load balancer is fronted it may require some cookies to function.
sessionCookie = processCookieHeaders(cookieHeaders);
// Overwrite old style cookies with new style ones if present
cookieHeaders = method.getResponseHeaders(HTTPConstants.HEADER_SET_COOKIE2);
for (int i = 0; i < cookieHeaders.length; i++) {
HeaderElement[] elements = cookieHeaders[i].getElements();
for (int e = 0; e < elements.length; e++) {
HeaderElement element = elements[e];
if (Constants.SESSION_COOKIE.equalsIgnoreCase(element.getName()) ||
Constants.SESSION_COOKIE_JSESSIONID.equalsIgnoreCase(element.getName())) {
sessionCookie = processCookieHeader(element);
}
if(customCoookiId!=null&&customCoookiId.equalsIgnoreCase(element.getName())){
sessionCookie = processCookieHeader(element);
}
}
}
if (sessionCookie != null && !sessionCookie.isEmpty()) {
msgContext.getServiceContext().setProperty(HTTPConstants.COOKIE_STRING, sessionCookie);
}
}
private String processCookieHeader(HeaderElement element) {
String cookie = element.getName() + "=" + element.getValue();
NameValuePair[] parameters = element.getParameters();
for (int j = 0; parameters != null && j < parameters.length; j++) {
NameValuePair parameter = parameters[j];
cookie = cookie + "; " + parameter.getName() + "=" + parameter.getValue();
}
return cookie;
}
private String processCookieHeaders(Header[] headers) {
String cookie = "";
for (Header header : headers) {
if (!cookie.equals("")) {
cookie = cookie + ";";
}
cookie += header.getValue();
}
return cookie;
}
protected void processResponse(HttpMethodBase httpMethod,
MessageContext msgContext)
throws IOException {
obtainHTTPHeaderInformation(httpMethod, msgContext);
InputStream in = httpMethod.getResponseBodyAsStream();
if (in == null) {
if (hasResponseBodyForHTTPStatusCode(httpMethod.getStatusCode())) {
throw new AxisFault(Messages.getMessage("canNotBeNull", "InputStream"));
} else {
in = new ByteArrayInputStream("".getBytes());
}
}
Header contentEncoding =
httpMethod.getResponseHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
if (contentEncoding != null) {
if (contentEncoding.getValue().
equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP)) {
in = new GZIPInputStream(in);
// If the content-encoding is identity we can basically ignore it.
} else if (!"identity".equalsIgnoreCase(contentEncoding.getValue())) {
throw new AxisFault("HTTP :" + "unsupported content-encoding of '"
+ contentEncoding.getValue() + "' found");
}
}
if (httpMethod.getStatusCode() == HttpStatus.SC_ACCEPTED) {
Header contentLength = httpMethod.getResponseHeader(HTTPConstants.HEADER_CONTENT_LENGTH);
boolean acceptedContainsBody = false;
if (in.available() > 0 || (contentLength != null && Integer.parseInt(contentLength.getValue()) > 0)) {
acceptedContainsBody = true;
} else {
Header transferEncoding = httpMethod.getResponseHeader(HTTPConstants.HEADER_TRANSFER_ENCODING);
if (transferEncoding != null && transferEncoding.getValue().equals(
HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) {
String responseBody = httpMethod.getResponseBodyAsString();
if (responseBody.length() > 0) {
acceptedContainsBody = true;
in = IOUtils.toInputStream(responseBody, "UTF-8");
}
}
}
if (!acceptedContainsBody) {
/*
* For HTTP 202 Accepted code, if the body is empty string then release connection.
*/
httpMethod.releaseConnection();
return;
}
}
OperationContext opContext = msgContext.getOperationContext();
if (opContext != null) {
opContext.setProperty(MessageContext.TRANSPORT_IN, in);
}
}
/**
* Check whether there is a message body or not for parsed HTTP status code, according to the HTTP spec.
*
* @param statusCode HTTP status code
* @return true if there is a message body for parsed status code, false if not.
*/
private boolean hasResponseBodyForHTTPStatusCode(int statusCode) {
if (statusCode == HttpStatus.SC_NO_CONTENT) {
return false;
} else if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
return false;
} else if (statusCode / 100 == 1) {
return false;
} else {
return true;
}
}
public abstract void send(MessageContext msgContext, URL url, String soapActionString)
throws IOException;
/**
* getting host configuration to support standard http/s, proxy and NTLM support
*
* @param client active HttpClient
* @param msgCtx active MessageContext
* @param targetURL the target URL
* @return a HostConfiguration set up with proxy information
* @throws AxisFault if problems occur
*/
protected HostConfiguration getHostConfiguration(HttpClient client,
MessageContext msgCtx,
URL targetURL)throws AxisFault {
boolean isAuthenticationEnabled = isAuthenticationEnabled(msgCtx);
int port = targetURL.getPort();
String protocol = targetURL.getProtocol();
if (port == -1) {
if (PROTOCOL_HTTP.equals(protocol)) {
port = 80;
} else if (PROTOCOL_HTTPS.equals(protocol)) {
port = 443;
}
}
// to see the host is a proxy and in the proxy list - available in axis2.xml
HostConfiguration config = new HostConfiguration();
// one might need to set his own socket factory. Let's allow that case as well.
Protocol protocolHandler =
(Protocol)msgCtx.getOptions().getProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER);
// setting the real host configuration
// I assume the 90% case, or even 99% case will be no protocol handler case.
if (protocolHandler == null) {
config.setHost(targetURL.getHost(), port, targetURL.getProtocol());
} else {
config.setHost(targetURL.getHost(), port, protocolHandler);
}
if (isAuthenticationEnabled) {
// Basic, Digest, NTLM and custom authentications.
this.setAuthenticationInfo(client, msgCtx, config);
}
// proxy configuration
if (HTTPProxyConfigurationUtil.isProxyEnabled(msgCtx, targetURL)) {
if(log.isDebugEnabled()){
log.debug("Configuring HTTP proxy.");
}
HTTPProxyConfigurationUtil.configure(msgCtx, client, config);
}
return config;
}
protected boolean isAuthenticationEnabled(MessageContext msgCtx) {
return (msgCtx.getProperty(HTTPConstants.AUTHENTICATE) != null);
}
/*
This will handle server Authentication, It could be either NTLM, Digest or Basic Authentication.
Apart from that user can change the priory or add a custom authentication scheme.
*/
protected void setAuthenticationInfo(HttpClient agent,
MessageContext msgCtx,
HostConfiguration config) throws AxisFault {
HttpTransportProperties.Authenticator authenticator;
Object obj = msgCtx.getProperty(HTTPConstants.AUTHENTICATE);
if (obj != null) {
if (obj instanceof HttpTransportProperties.Authenticator) {
authenticator = (HttpTransportProperties.Authenticator) obj;
String username = authenticator.getUsername();
String password = authenticator.getPassword();
String host = authenticator.getHost();
String domain = authenticator.getDomain();
int port = authenticator.getPort();
String realm = authenticator.getRealm();
/* If retrying is available set it first */
isAllowedRetry = authenticator.isAllowedRetry();
Credentials creds;
HttpState tmpHttpState = null;
HttpState httpState = (HttpState)msgCtx.getProperty(HTTPConstants.CACHED_HTTP_STATE);
if (httpState != null) {
tmpHttpState = httpState;
} else {
tmpHttpState = agent.getState();
}
agent.getParams()
.setAuthenticationPreemptive(authenticator.getPreemptiveAuthentication());
if (host != null) {
if (domain != null) {
/*Credentials for NTLM Authentication*/
creds = new NTCredentials(username, password, host, domain);
} else {
/*Credentials for Digest and Basic Authentication*/
creds = new UsernamePasswordCredentials(username, password);
}
tmpHttpState.setCredentials(new AuthScope(host, port, realm), creds);
} else {
if (domain != null) {
/*Credentials for NTLM Authentication when host is ANY_HOST*/
creds = new NTCredentials(username, password, AuthScope.ANY_HOST, domain);
tmpHttpState.setCredentials(
new AuthScope(AuthScope.ANY_HOST, port, realm), creds);
} else {
/*Credentials only for Digest and Basic Authentication*/
creds = new UsernamePasswordCredentials(username, password);
tmpHttpState.setCredentials(new AuthScope(AuthScope.ANY), creds);
}
}
/* Customizing the priority Order */
List schemes = authenticator.getAuthSchemes();
if (schemes != null && schemes.size() > 0) {
List authPrefs = new ArrayList(3);
for (int i = 0; i < schemes.size(); i++) {
if (schemes.get(i) instanceof AuthPolicy) {
authPrefs.add(schemes.get(i));
continue;
}
String scheme = (String) schemes.get(i);
if (HttpTransportProperties.Authenticator.BASIC.equals(scheme)) {
authPrefs.add(AuthPolicy.BASIC);
} else if (HttpTransportProperties.Authenticator.NTLM.equals(scheme)) {
authPrefs.add(AuthPolicy.NTLM);
} else if (HttpTransportProperties.Authenticator.DIGEST.equals(scheme)) {
authPrefs.add(AuthPolicy.DIGEST);
}
}
agent.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY,
authPrefs);
}
} else {
throw new AxisFault("HttpTransportProperties.Authenticator class cast exception");
}
}
}
/**
* Method used to copy all the common properties
*
* @param msgContext - The messageContext of the request message
* @param url - The target URL
* @param httpMethod - The http method used to send the request
* @param httpClient - The httpclient used to send the request
* @param soapActionString - The soap action atring of the request message
* @return MessageFormatter - The messageFormatter for the relavent request message
* @throws AxisFault - Thrown in case an exception occurs
*/
protected MessageFormatter populateCommonProperties(MessageContext msgContext, URL url,
HttpMethodBase httpMethod,
HttpClient httpClient,
String soapActionString)
throws AxisFault {
if (isAuthenticationEnabled(msgContext)) {
httpMethod.setDoAuthentication(true);
}
MessageFormatter messageFormatter = MessageProcessorSelector
.getMessageFormatter(msgContext);
url = messageFormatter.getTargetAddress(msgContext, format, url);
httpMethod.setPath(url.getPath());
httpMethod.setQueryString(url.getQuery());
// If adding the Content-Type header from the message formatter needs to be skipped
if (Boolean.parseBoolean((String)msgContext.getProperty(HTTPConstants.NO_DEFAULT_CONTENT_TYPE))) {
// Check whether message context already has the Content-Type header,
// if so use that as the Content-Type header
Object transportHeadersObj = msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);
if (transportHeadersObj != null && transportHeadersObj instanceof Map) {
Map transportHeaders = (Map) transportHeadersObj;
Object headerContentType = transportHeaders.get(HTTPConstants.HEADER_CONTENT_TYPE);
if (headerContentType != null) {
httpMethod.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE, headerContentType.toString());
}
}
// If NO_DEFAULT_CONTENT_TYPE is set to true and the Content-Type header is not present
// in the message context, backend will receive a request without a Content-Type header
} else {
httpMethod.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE,
messageFormatter.getContentType(msgContext, format, soapActionString));
}
httpMethod.setRequestHeader(HTTPConstants.HEADER_HOST, url.getHost());
if (msgContext.getOptions() != null && msgContext.getOptions().isManageSession()) {
// setting the cookie in the out path
Object cookieString = msgContext.getProperty(HTTPConstants.COOKIE_STRING);
if (cookieString != null) {
StringBuffer buffer = new StringBuffer();
buffer.append(cookieString);
httpMethod.setRequestHeader(HTTPConstants.HEADER_COOKIE, buffer.toString());
}
}
if (httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_10)) {
httpClient.getParams().setVersion(HttpVersion.HTTP_1_0);
}
return messageFormatter;
}
/**
* This is used to get the dynamically set time out values from the
* message context. If the values are not available or invalid then
* the default values or the values set by the configuration will be used
*
* @param msgContext the active MessageContext
* @param httpClient
*/
protected void initializeTimeouts(MessageContext msgContext, HttpClient httpClient) {
// If the SO_TIMEOUT of CONNECTION_TIMEOUT is set by dynamically the
// override the static config
Integer tempSoTimeoutProperty =
(Integer) msgContext.getProperty(HTTPConstants.SO_TIMEOUT);
Integer tempConnTimeoutProperty =
(Integer) msgContext
.getProperty(HTTPConstants.CONNECTION_TIMEOUT);
long timeout = msgContext.getOptions().getTimeOutInMilliSeconds();
if (tempConnTimeoutProperty != null) {
int connectionTimeout = tempConnTimeoutProperty.intValue();
// timeout for initial connection
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);
} else {
// set timeout in client
if (timeout > 0) {
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout((int) timeout);
}
}
if (tempSoTimeoutProperty != null) {
int soTimeout = tempSoTimeoutProperty.intValue();
// SO_TIMEOUT -- timeout for blocking reads
httpClient.getHttpConnectionManager().getParams().setSoTimeout(soTimeout);
httpClient.getParams().setSoTimeout(soTimeout);
} else {
// set timeout in client
if (timeout > 0) {
httpClient.getHttpConnectionManager().getParams().setSoTimeout((int) timeout);
httpClient.getParams().setSoTimeout((int) timeout);
}
}
}
/**
* This is used to get the dynamically set time out values from the
* message context. If the values are not available or invalid then
* the default values or the values set by the configuration will be used
*
* @param msgContext the active MessageContext
* @param httpMethod method
*/
protected void setTimeouts(MessageContext msgContext, HttpMethod httpMethod) {
// If the SO_TIMEOUT of CONNECTION_TIMEOUT is set by dynamically the
// override the static config
Integer tempSoTimeoutProperty =
(Integer) msgContext.getProperty(HTTPConstants.SO_TIMEOUT);
Integer tempConnTimeoutProperty =
(Integer) msgContext
.getProperty(HTTPConstants.CONNECTION_TIMEOUT);
long timeout = msgContext.getOptions().getTimeOutInMilliSeconds();
if (tempConnTimeoutProperty != null) {
// timeout for initial connection
httpMethod.getParams().setParameter("http.connection.timeout",
tempConnTimeoutProperty);
}
if (tempSoTimeoutProperty != null) {
// SO_TIMEOUT -- timeout for blocking reads
httpMethod.getParams().setSoTimeout(tempSoTimeoutProperty);
} else {
// set timeout in client
if (timeout > 0) {
httpMethod.getParams().setSoTimeout((int) timeout);
}
}
}
/**
* Sets keep-alive configuration.
*
* @param msgContext the axis2 message context
* @param httpMethod the http method
*/
protected void setKeepAlive(MessageContext msgContext, HttpMethod httpMethod) {
String disableKeepalive = (String) msgContext.getProperty(HTTPConstants.NO_KEEPALIVE);
if (disableKeepalive != null && Boolean.parseBoolean(disableKeepalive)) {
httpMethod.setRequestHeader(HttpHeaders.CONNECTION, HTTP.CONN_CLOSE);
}
}
public void setFormat(OMOutputFormat format) {
this.format = format;
}
protected HttpClient getHttpClient(MessageContext msgContext) {
ConfigurationContext configContext = msgContext.getConfigurationContext();
HttpClient httpClient = (HttpClient) msgContext.getProperty(
HTTPConstants.CACHED_HTTP_CLIENT);
if (httpClient == null) {
httpClient = (HttpClient) configContext.getProperty(HTTPConstants.CACHED_HTTP_CLIENT);
}
if (httpClient != null) {
httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(0, false));
return httpClient;
}
synchronized (this) {
httpClient = (HttpClient) msgContext.getProperty(HTTPConstants.CACHED_HTTP_CLIENT);
if (httpClient == null) {
httpClient = (HttpClient) configContext.getProperty(
HTTPConstants.CACHED_HTTP_CLIENT);
}
if (httpClient != null) {
httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(0, false));
return httpClient;
}
HttpConnectionManager connManager =
(HttpConnectionManager) msgContext.getProperty(
HTTPConstants.MULTITHREAD_HTTP_CONNECTION_MANAGER);
if (connManager == null) {
connManager =
(HttpConnectionManager) msgContext.getProperty(
HTTPConstants.MUTTITHREAD_HTTP_CONNECTION_MANAGER);
}
if (connManager == null) {
// reuse HttpConnectionManager
synchronized (configContext) {
connManager = (HttpConnectionManager) configContext.getProperty(
HTTPConstants.MULTITHREAD_HTTP_CONNECTION_MANAGER);
if (connManager == null) {
log.trace("Making new ConnectionManager");
connManager = new MultiThreadedHttpConnectionManager();
configContext.setProperty(
HTTPConstants.MULTITHREAD_HTTP_CONNECTION_MANAGER, connManager);
}
}
}
/*
* Create a new instance of HttpClient since the way
* it is used here it's not fully thread-safe.
*/
httpClient = new HttpClient(connManager);
// Set the default timeout in case we have a connection pool starvation to 30sec
httpClient.getParams().setConnectionManagerTimeout(30000);
// Get the timeout values set in the runtime
initializeTimeouts(msgContext, httpClient);
httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(0, false));
return httpClient;
}
}
protected void executeMethod(HttpClient httpClient, MessageContext msgContext, URL url,
HttpMethod method) throws IOException {
HostConfiguration config = this.getHostConfiguration(httpClient, msgContext, url);
// set the custom headers, if available
addCustomHeaders(method, msgContext);
// add compression headers if needed
if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP)) {
method.addRequestHeader(HTTPConstants.HEADER_ACCEPT_ENCODING,
HTTPConstants.COMPRESSION_GZIP);
}
if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
method.addRequestHeader(HTTPConstants.HEADER_CONTENT_ENCODING,
HTTPConstants.COMPRESSION_GZIP);
}
if (msgContext.getProperty(HTTPConstants.HTTP_METHOD_PARAMS) != null) {
HttpMethodParams params = (HttpMethodParams)msgContext
.getProperty(HTTPConstants.HTTP_METHOD_PARAMS);
method.setParams(params);
}
String cookiePolicy = (String) msgContext.getProperty(HTTPConstants.COOKIE_POLICY);
if (cookiePolicy != null) {
method.getParams().setCookiePolicy(cookiePolicy);
}
HttpState httpState = (HttpState)msgContext.getProperty(HTTPConstants.CACHED_HTTP_STATE);
setTimeouts(msgContext, method);
setKeepAlive(msgContext, method);
httpClient.executeMethod(config, method, httpState);
}
public void addCustomHeaders(HttpMethod method, MessageContext msgContext) {
boolean isCustomUserAgentSet = false;
// set the custom headers, if available
Object httpHeadersObj = msgContext.getProperty(HTTPConstants.HTTP_HEADERS);
if (httpHeadersObj != null) {
if (httpHeadersObj instanceof ArrayList) {
ArrayList httpHeaders = (ArrayList) httpHeadersObj;
Header header;
for (int i = 0; i < httpHeaders.size(); i++) {
header = (Header) httpHeaders.get(i);
if (HTTPConstants.HEADER_USER_AGENT.equals(header.getName())) {
isCustomUserAgentSet = true;
}
method.addRequestHeader(header);
}
}
if (httpHeadersObj instanceof Map) {
Map httpHeaders = (Map) httpHeadersObj;
for (Iterator iterator = httpHeaders.entrySet().iterator(); iterator.hasNext();) {
Map.Entry entry = (Map.Entry) iterator.next();
String key = (String) entry.getKey();
String value = (String) entry.getValue();
if (HTTPConstants.HEADER_USER_AGENT.equals(key)) {
isCustomUserAgentSet = true;
}
method.addRequestHeader(key, value);
}
}
}
// we have to consider the TRANSPORT_HEADERS map as well
Map transportHeaders = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);
if (transportHeaders != null) {
removeUnwantedHeaders(msgContext);
Set headerEntries = transportHeaders.entrySet();
for (Object headerEntry : headerEntries) {
if (headerEntry instanceof Map.Entry) {
Header[] headers = method.getRequestHeaders();
boolean headerAdded = false;
for (Header header : headers) {
if (header.getName() != null) {
Object headerKey = ((Map.Entry) headerEntry).getKey();
if (headerKey instanceof String && header.getName().equalsIgnoreCase((String) headerKey)) {
// According to RFC2626 http headers are case insensitive.
// So need to ignore case
headerAdded = true;
break;
}
}
}
if (!headerAdded) {
method.addRequestHeader(((Map.Entry) headerEntry).getKey().toString(),
((Map.Entry) headerEntry).getValue().toString());
}
}
}
}
if (!isCustomUserAgentSet) {
String userAgentString = getUserAgent(msgContext);
method.setRequestHeader(HTTPConstants.HEADER_USER_AGENT, userAgentString);
}
}
/**
* Remove unwanted headers from the transport headers map of outgoing request. These are headers which
* should be dictated by the transport and not the user. We remove these as these may get
* copied from the request messages
*
* @param msgContext the Axis2 Message context from which these headers should be removed
*/
private void removeUnwantedHeaders(MessageContext msgContext) {
Map headers = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);
if (headers == null || headers.isEmpty()) {
return;
}
Iterator iter = headers.keySet().iterator();
while (iter.hasNext()) {
String headerName = (String) iter.next();
if (HTTP.CONN_DIRECTIVE.equalsIgnoreCase(headerName) ||
HTTP.TRANSFER_ENCODING.equalsIgnoreCase(headerName) ||
HTTP.DATE_HEADER.equalsIgnoreCase(headerName) ||
HTTP.CONTENT_TYPE.equalsIgnoreCase(headerName) ||
HTTP.CONTENT_LEN.equalsIgnoreCase(headerName)) {
iter.remove();
}
}
}
private String getUserAgent(MessageContext messageContext) {
String userAgentString = "Axis2";
boolean locked = false;
if (messageContext.getParameter(HTTPConstants.USER_AGENT) != null) {
OMElement userAgentElement =
messageContext.getParameter(HTTPConstants.USER_AGENT).getParameterElement();
userAgentString = userAgentElement.getText().trim();
OMAttribute lockedAttribute = userAgentElement.getAttribute(new QName("locked"));
if (lockedAttribute != null) {
if (lockedAttribute.getAttributeValue().equalsIgnoreCase("true")) {
locked = true;
}
}
}
// Runtime overing part
if (!locked) {
if (messageContext.getProperty(HTTPConstants.USER_AGENT) != null) {
userAgentString = (String) messageContext.getProperty(HTTPConstants.USER_AGENT);
}
}
return userAgentString;
}
}
| |
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.analysis;
import static com.google.devtools.build.lib.analysis.ExtraActionUtils.createExtraActionProvider;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.actions.ActionAnalysisMetadata;
import com.google.devtools.build.lib.actions.Actions;
import com.google.devtools.build.lib.actions.Actions.GeneratingActions;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.MutableActionGraph.ActionConflictException;
import com.google.devtools.build.lib.analysis.config.CoreOptions;
import com.google.devtools.build.lib.analysis.starlark.StarlarkApiProvider;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable;
import com.google.devtools.build.lib.packages.Info;
import com.google.devtools.build.lib.packages.Provider;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.TreeMap;
import javax.annotation.Nullable;
import net.starlark.java.eval.EvalException;
import net.starlark.java.eval.Starlark;
/**
* Extra information about a configured target computed on request of a dependent.
*
* <p>Analogous to {@link ConfiguredTarget}: contains a bunch of transitive info providers, which
* are merged with the providers of the associated configured target before they are passed to the
* configured target factories that depend on the configured target to which this aspect is added.
*
* <p>Aspects are created alongside configured targets on request from dependents.
*
* <p>For more information about aspects, see {@link
* com.google.devtools.build.lib.packages.AspectClass}.
*
* @see com.google.devtools.build.lib.analysis.RuleConfiguredTargetFactory
* @see com.google.devtools.build.lib.packages.AspectClass
*/
@Immutable
public final class ConfiguredAspect implements ProviderCollection {
private final ImmutableList<ActionAnalysisMetadata> actions;
private final TransitiveInfoProviderMap providers;
private ConfiguredAspect(
ImmutableList<ActionAnalysisMetadata> actions, TransitiveInfoProviderMap providers) {
this.actions = actions;
this.providers = providers;
// Initialize every StarlarkApiProvider
for (int i = 0; i < providers.getProviderCount(); i++) {
Object obj = providers.getProviderInstanceAt(i);
if (obj instanceof StarlarkApiProvider) {
((StarlarkApiProvider) obj).init(providers);
}
}
}
public ImmutableList<ActionAnalysisMetadata> getActions() {
return actions;
}
/** Returns the providers created by the aspect. */
public TransitiveInfoProviderMap getProviders() {
return providers;
}
@Override
@Nullable
public <P extends TransitiveInfoProvider> P getProvider(Class<P> providerClass) {
AnalysisUtils.checkProvider(providerClass);
return providers.getProvider(providerClass);
}
@Override
public Info get(Provider.Key key) {
return providers.get(key);
}
@Override
public Object get(String legacyKey) {
if (OutputGroupInfo.STARLARK_NAME.equals(legacyKey)) {
return get(OutputGroupInfo.STARLARK_CONSTRUCTOR.getKey());
}
return providers.get(legacyKey);
}
public static ConfiguredAspect forAlias(ConfiguredAspect real) {
return new ConfiguredAspect(real.getActions(), real.getProviders());
}
public static ConfiguredAspect forNonapplicableTarget() {
return new ConfiguredAspect(
ImmutableList.of(),
new TransitiveInfoProviderMapBuilder().add().build());
}
public static Builder builder(RuleContext ruleContext) {
return new Builder(ruleContext);
}
/**
* Builder for {@link ConfiguredAspect}.
*/
public static class Builder {
private final TransitiveInfoProviderMapBuilder providers =
new TransitiveInfoProviderMapBuilder();
private final Map<String, NestedSetBuilder<Artifact>> outputGroupBuilders = new TreeMap<>();
private final RuleContext ruleContext;
private final LinkedHashSet<String> aspectImplSpecificRequiredConfigFragments =
new LinkedHashSet<>();
public Builder(RuleContext ruleContext) {
this.ruleContext = ruleContext;
}
public <T extends TransitiveInfoProvider> Builder addProvider(
Class<? extends T> providerClass, T provider) {
Preconditions.checkNotNull(provider);
checkProviderClass(providerClass);
providers.put(providerClass, provider);
return this;
}
/** Adds a provider to the aspect. */
public Builder addProvider(TransitiveInfoProvider provider) {
Preconditions.checkNotNull(provider);
addProvider(TransitiveInfoProviderEffectiveClassHelper.get(provider), provider);
return this;
}
private void checkProviderClass(Class<? extends TransitiveInfoProvider> providerClass) {
Preconditions.checkNotNull(providerClass);
}
/** Adds providers to the aspect. */
public Builder addProviders(TransitiveInfoProviderMap providers) {
this.providers.addAll(providers);
return this;
}
/** Adds providers to the aspect. */
public Builder addProviders(TransitiveInfoProvider... providers) {
return addProviders(Arrays.asList(providers));
}
/** Adds providers to the aspect. */
public Builder addProviders(Iterable<TransitiveInfoProvider> providers) {
for (TransitiveInfoProvider provider : providers) {
addProvider(provider);
}
return this;
}
/**
* Adds a set of files to an output group.
*/
public Builder addOutputGroup(String name, NestedSet<Artifact> artifacts) {
NestedSetBuilder<Artifact> nestedSetBuilder = outputGroupBuilders.get(name);
if (nestedSetBuilder == null) {
nestedSetBuilder = NestedSetBuilder.<Artifact>stableOrder();
outputGroupBuilders.put(name, nestedSetBuilder);
}
nestedSetBuilder.addTransitive(artifacts);
return this;
}
public Builder addStarlarkTransitiveInfo(String name, Object value) {
providers.put(name, value);
return this;
}
public Builder addStarlarkDeclaredProvider(Info declaredProvider) throws EvalException {
Provider constructor = declaredProvider.getProvider();
if (!constructor.isExported()) {
throw Starlark.errorf(
"aspect function returned an instance of a provider (defined at %s) that is not a"
+ " global",
constructor.getLocation());
}
addDeclaredProvider(declaredProvider);
return this;
}
private void addDeclaredProvider(Info declaredProvider) {
providers.put(declaredProvider);
}
public Builder addNativeDeclaredProvider(Info declaredProvider) {
Provider constructor = declaredProvider.getProvider();
Preconditions.checkState(constructor.isExported());
addDeclaredProvider(declaredProvider);
return this;
}
/**
* Supplements {@link #maybeAddRequiredConfigFragmentsProvider} with aspect
* implementation-specific requirements.
*/
public Builder addRequiredConfigFragments(Collection<String> fragments) {
aspectImplSpecificRequiredConfigFragments.addAll(fragments);
return this;
}
public ConfiguredAspect build() throws ActionConflictException, InterruptedException {
if (!outputGroupBuilders.isEmpty()) {
ImmutableMap.Builder<String, NestedSet<Artifact>> outputGroups = ImmutableMap.builder();
for (Map.Entry<String, NestedSetBuilder<Artifact>> entry : outputGroupBuilders.entrySet()) {
outputGroups.put(entry.getKey(), entry.getValue().build());
}
if (providers.contains(OutputGroupInfo.STARLARK_CONSTRUCTOR.getKey())) {
throw new IllegalStateException(
"OutputGroupInfo was provided explicitly; do not use addOutputGroup");
}
addDeclaredProvider(new OutputGroupInfo(outputGroups.build()));
}
addProvider(
createExtraActionProvider(
/* actionsWithoutExtraAction= */ ImmutableSet.<ActionAnalysisMetadata>of(),
ruleContext));
AnalysisEnvironment analysisEnvironment = ruleContext.getAnalysisEnvironment();
GeneratingActions generatingActions =
Actions.assignOwnersAndFilterSharedActionsAndThrowActionConflict(
analysisEnvironment.getActionKeyContext(),
analysisEnvironment.getRegisteredActions(),
ruleContext.getOwner(),
/*outputFiles=*/ null);
maybeAddRequiredConfigFragmentsProvider();
return new ConfiguredAspect(generatingActions.getActions(), providers.build());
}
/**
* Adds {@link RequiredConfigFragmentsProvider} if {@link
* CoreOptions#includeRequiredConfigFragmentsProvider} isn't {@link
* CoreOptions.IncludeConfigFragmentsEnum#OFF}.
*
* <p>See {@link com.google.devtools.build.lib.analysis.config.RequiredFragmentsUtil} for a
* description of the meaning of this provider's content. That class contains methods that
* populate the results of {@link RuleContext#getRequiredConfigFragments} and {@link
* #aspectImplSpecificRequiredConfigFragments}.
*/
private void maybeAddRequiredConfigFragmentsProvider() {
if (ruleContext.shouldIncludeRequiredConfigFragmentsProvider()) {
addProvider(
new RequiredConfigFragmentsProvider(
ImmutableSet.<String>builder()
.addAll(ruleContext.getRequiredConfigFragments())
.addAll(aspectImplSpecificRequiredConfigFragments)
.build()));
}
}
}
}
| |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vfs.newvfs.impl;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.testFramework.LightProjectDescriptor;
import com.intellij.testFramework.fixtures.IdeaTestFixture;
import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.TIntObjectHashMap;
import gnu.trove.TLongArrayList;
import org.jetbrains.annotations.NotNull;
import org.junit.Assert;
import javax.swing.*;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
/**
* @author peter
*/
public class FileNameCacheMicroBenchmark {
public static void main(String[] args) throws Exception {
//noinspection SSBasedInspection
SwingUtilities.invokeAndWait(() -> {
try {
IdeaTestFixture fixture = IdeaTestFixtureFactory.getFixtureFactory().createLightFixtureBuilder(LightProjectDescriptor.EMPTY_PROJECT_DESCRIPTOR).getFixture();
fixture.setUp();
long start = System.currentTimeMillis();
runTest(200, "All names in cache");
runTest(50000, "Cache almost overflows");
runTest(120000, "Cache certain overflow");
long elapsed = System.currentTimeMillis() - start;
System.out.println("Total elapsed: " + elapsed/1000.0 +"s");
fixture.tearDown();
}
catch (Exception e) {
throw new RuntimeException(e);
}
});
System.exit(0);
}
private static final TestIteration LONG_RANDOM_ACCESS = new TestIteration() {
@Override
public void doTest(int threadNumber, int[] ids, Random threadRandom, int queryCount) {
final int blackHole = threadRandom.nextInt();
for (int j = 0; j < queryCount; j++) {
final CharSequence name = FileNameCache.getVFileName(ids[threadRandom.nextInt(ids.length)]);
if (blackHole == name.hashCode() && blackHole+1 == name.hashCode()) {
failure();
}
}
}
@Override
public String toString() {
return "random access";
}
};
private static final TestIteration LONG_RANDOM_ACCESS_WITH_GET_PATH = new TestIteration() {
@Override
public void doTest(int threadNumber, int[] ids, Random threadRandom, int queryCount) {
final int blackHole = threadRandom.nextInt();
for (int j = 0; j < queryCount; j++) {
final int hash = getPath(threadRandom.nextInt(ids.length), ids);
if (blackHole == hash) {
failure();
}
}
}
@Override
public String toString() {
return "random access + getPath";
}
};
private static final TestIteration LINEAR_SCAN_AND_RANDOM_ACCESS_WITH_GET_PATH = new TestIteration() {
@Override
public void doTest(int threadNumber, int[] ids, Random threadRandom, int queryCount) {
if (threadNumber % 2 == 1) { // linear scan for every second_case
final int blackHole = threadRandom.nextInt();
int currentId = 0;
for(int j = 0; j < queryCount; ++j) {
final int hash = getPath(currentId++, ids);
if (currentId == ids.length) currentId = 0;
if (blackHole == hash) {
failure();
}
}
return;
}
LONG_RANDOM_ACCESS_WITH_GET_PATH.doTest(threadNumber, ids, threadRandom, queryCount);
}
@Override
public String toString() {
return "linear scan + random access + getPath";
}
};
private static void runTest(int nameCount, String name) throws InterruptedException, ExecutionException {
System.out.println("----- " + name + " ------ name count: "+nameCount);
TIntObjectHashMap<CharSequence> map = generateNames(nameCount);
final int[] ids = map.keys();
checkNames(map, ids);
warmUp(ids);
measureAverageTime(ids, 1, LONG_RANDOM_ACCESS);
measureAverageTime(ids, 4, LONG_RANDOM_ACCESS);
measureAverageTime(ids, 1, LONG_RANDOM_ACCESS_WITH_GET_PATH);
measureAverageTime(ids, 4, LONG_RANDOM_ACCESS_WITH_GET_PATH);
measureAverageTime(ids, 1, LINEAR_SCAN_AND_RANDOM_ACCESS_WITH_GET_PATH);
measureAverageTime(ids, 4, LINEAR_SCAN_AND_RANDOM_ACCESS_WITH_GET_PATH);
}
private static boolean warmedUp;
private static void warmUp(int[] ids) throws InterruptedException, ExecutionException {
if (warmedUp) return;
System.out.println("Warming up");
for (int i = 0; i < 200000; i++) {
runThreads(ids, 2, 1000, LONG_RANDOM_ACCESS);
}
Thread.sleep(10000);
System.out.println("Warmup complete");
warmedUp = true;
}
private static int getPath(int id, int[] ids) {
int result = 0;
while (id > 0) {
result += FileNameCache.getVFileName(ids[id]).hashCode();
id /= 10;
}
return result;
}
private static void measureAverageTime(int[] ids, int threadCount, TestIteration iteration) throws InterruptedException, ExecutionException {
System.out.println("Running "+threadCount+" threads, using "+iteration);
TLongArrayList times = new TLongArrayList();
for (int i = 0; i < 10; i++) {
long time = runThreads(ids, threadCount, 2000000/*0*/, iteration);
System.out.println(time);
times.add(time);
}
times.sort();
long median = times.get(times.size() / 2);
System.out.println("Median for " + threadCount + " threads: " + median+"ms");
System.out.println();
}
private abstract static class TestIteration {
abstract void doTest(int threadNumber, int[] ids, Random threadRandom, int queryCount);
static void failure() {
System.out.println("Failure");
assert false;
}
}
private static long runThreads(final int[] ids, int threadCount, final int queryCount, final TestIteration testIteration) throws InterruptedException, ExecutionException {
long start = System.currentTimeMillis();
List<Future<?>> futures = ContainerUtil.newArrayList();
Random seedRandom = new Random();
for (int i = 0; i < threadCount; i++) {
final Random threadRandom = new Random(seedRandom.nextInt());
final int finalI = i;
futures.add(ApplicationManager.getApplication().executeOnPooledThread(
() -> testIteration.doTest(finalI, ids, threadRandom, queryCount)));
}
for (Future<?> future : futures) {
future.get();
}
return System.currentTimeMillis() - start;
}
private static void checkNames(TIntObjectHashMap<CharSequence> map, int[] ids) {
for (int id : ids) {
Assert.assertEquals(map.get(id), FileNameCache.getVFileName(id).toString());
}
}
@NotNull
private static TIntObjectHashMap<CharSequence> generateNames(int nameCount) {
Random random = new Random();
TIntObjectHashMap<CharSequence> map = new TIntObjectHashMap<>();
for (int i = 0; i < nameCount; i++) {
String name = "some_name_" + random.nextInt() + StringUtil.repeat("a", random.nextInt(10));
int id = FileNameCache.storeName(name);
map.put(id, name);
}
return map;
}
}
| |
/*
* Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.iot.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Describes an action to publish to an Amazon SNS topic.
* </p>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class SnsAction implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The ARN of the SNS topic.
* </p>
*/
private String targetArn;
/**
* <p>
* The ARN of the IAM role that grants access.
* </p>
*/
private String roleArn;
/**
* <p>
* The message format of the message to publish. Optional. Accepted values are "JSON" and "RAW". The default value
* of the attribute is "RAW". SNS uses this setting to determine if the payload should be parsed and relevant
* platform-specific bits of the payload should be extracted. To read more about SNS message formats, see <a
* href="http://docs.aws.amazon.com/sns/latest/dg/json-formats.html"></a> refer to their official documentation.
* </p>
*/
private String messageFormat;
/**
* <p>
* The ARN of the SNS topic.
* </p>
*
* @param targetArn
* The ARN of the SNS topic.
*/
public void setTargetArn(String targetArn) {
this.targetArn = targetArn;
}
/**
* <p>
* The ARN of the SNS topic.
* </p>
*
* @return The ARN of the SNS topic.
*/
public String getTargetArn() {
return this.targetArn;
}
/**
* <p>
* The ARN of the SNS topic.
* </p>
*
* @param targetArn
* The ARN of the SNS topic.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SnsAction withTargetArn(String targetArn) {
setTargetArn(targetArn);
return this;
}
/**
* <p>
* The ARN of the IAM role that grants access.
* </p>
*
* @param roleArn
* The ARN of the IAM role that grants access.
*/
public void setRoleArn(String roleArn) {
this.roleArn = roleArn;
}
/**
* <p>
* The ARN of the IAM role that grants access.
* </p>
*
* @return The ARN of the IAM role that grants access.
*/
public String getRoleArn() {
return this.roleArn;
}
/**
* <p>
* The ARN of the IAM role that grants access.
* </p>
*
* @param roleArn
* The ARN of the IAM role that grants access.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SnsAction withRoleArn(String roleArn) {
setRoleArn(roleArn);
return this;
}
/**
* <p>
* The message format of the message to publish. Optional. Accepted values are "JSON" and "RAW". The default value
* of the attribute is "RAW". SNS uses this setting to determine if the payload should be parsed and relevant
* platform-specific bits of the payload should be extracted. To read more about SNS message formats, see <a
* href="http://docs.aws.amazon.com/sns/latest/dg/json-formats.html"></a> refer to their official documentation.
* </p>
*
* @param messageFormat
* The message format of the message to publish. Optional. Accepted values are "JSON" and "RAW". The default
* value of the attribute is "RAW". SNS uses this setting to determine if the payload should be parsed and
* relevant platform-specific bits of the payload should be extracted. To read more about SNS message
* formats, see <a href="http://docs.aws.amazon.com/sns/latest/dg/json-formats.html"></a> refer to their
* official documentation.
* @see MessageFormat
*/
public void setMessageFormat(String messageFormat) {
this.messageFormat = messageFormat;
}
/**
* <p>
* The message format of the message to publish. Optional. Accepted values are "JSON" and "RAW". The default value
* of the attribute is "RAW". SNS uses this setting to determine if the payload should be parsed and relevant
* platform-specific bits of the payload should be extracted. To read more about SNS message formats, see <a
* href="http://docs.aws.amazon.com/sns/latest/dg/json-formats.html"></a> refer to their official documentation.
* </p>
*
* @return The message format of the message to publish. Optional. Accepted values are "JSON" and "RAW". The default
* value of the attribute is "RAW". SNS uses this setting to determine if the payload should be parsed and
* relevant platform-specific bits of the payload should be extracted. To read more about SNS message
* formats, see <a href="http://docs.aws.amazon.com/sns/latest/dg/json-formats.html"></a> refer to their
* official documentation.
* @see MessageFormat
*/
public String getMessageFormat() {
return this.messageFormat;
}
/**
* <p>
* The message format of the message to publish. Optional. Accepted values are "JSON" and "RAW". The default value
* of the attribute is "RAW". SNS uses this setting to determine if the payload should be parsed and relevant
* platform-specific bits of the payload should be extracted. To read more about SNS message formats, see <a
* href="http://docs.aws.amazon.com/sns/latest/dg/json-formats.html"></a> refer to their official documentation.
* </p>
*
* @param messageFormat
* The message format of the message to publish. Optional. Accepted values are "JSON" and "RAW". The default
* value of the attribute is "RAW". SNS uses this setting to determine if the payload should be parsed and
* relevant platform-specific bits of the payload should be extracted. To read more about SNS message
* formats, see <a href="http://docs.aws.amazon.com/sns/latest/dg/json-formats.html"></a> refer to their
* official documentation.
* @return Returns a reference to this object so that method calls can be chained together.
* @see MessageFormat
*/
public SnsAction withMessageFormat(String messageFormat) {
setMessageFormat(messageFormat);
return this;
}
/**
* <p>
* The message format of the message to publish. Optional. Accepted values are "JSON" and "RAW". The default value
* of the attribute is "RAW". SNS uses this setting to determine if the payload should be parsed and relevant
* platform-specific bits of the payload should be extracted. To read more about SNS message formats, see <a
* href="http://docs.aws.amazon.com/sns/latest/dg/json-formats.html"></a> refer to their official documentation.
* </p>
*
* @param messageFormat
* The message format of the message to publish. Optional. Accepted values are "JSON" and "RAW". The default
* value of the attribute is "RAW". SNS uses this setting to determine if the payload should be parsed and
* relevant platform-specific bits of the payload should be extracted. To read more about SNS message
* formats, see <a href="http://docs.aws.amazon.com/sns/latest/dg/json-formats.html"></a> refer to their
* official documentation.
* @see MessageFormat
*/
public void setMessageFormat(MessageFormat messageFormat) {
this.messageFormat = messageFormat.toString();
}
/**
* <p>
* The message format of the message to publish. Optional. Accepted values are "JSON" and "RAW". The default value
* of the attribute is "RAW". SNS uses this setting to determine if the payload should be parsed and relevant
* platform-specific bits of the payload should be extracted. To read more about SNS message formats, see <a
* href="http://docs.aws.amazon.com/sns/latest/dg/json-formats.html"></a> refer to their official documentation.
* </p>
*
* @param messageFormat
* The message format of the message to publish. Optional. Accepted values are "JSON" and "RAW". The default
* value of the attribute is "RAW". SNS uses this setting to determine if the payload should be parsed and
* relevant platform-specific bits of the payload should be extracted. To read more about SNS message
* formats, see <a href="http://docs.aws.amazon.com/sns/latest/dg/json-formats.html"></a> refer to their
* official documentation.
* @return Returns a reference to this object so that method calls can be chained together.
* @see MessageFormat
*/
public SnsAction withMessageFormat(MessageFormat messageFormat) {
setMessageFormat(messageFormat);
return this;
}
/**
* Returns a string representation of this object; useful for testing and debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getTargetArn() != null)
sb.append("TargetArn: ").append(getTargetArn()).append(",");
if (getRoleArn() != null)
sb.append("RoleArn: ").append(getRoleArn()).append(",");
if (getMessageFormat() != null)
sb.append("MessageFormat: ").append(getMessageFormat());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof SnsAction == false)
return false;
SnsAction other = (SnsAction) obj;
if (other.getTargetArn() == null ^ this.getTargetArn() == null)
return false;
if (other.getTargetArn() != null && other.getTargetArn().equals(this.getTargetArn()) == false)
return false;
if (other.getRoleArn() == null ^ this.getRoleArn() == null)
return false;
if (other.getRoleArn() != null && other.getRoleArn().equals(this.getRoleArn()) == false)
return false;
if (other.getMessageFormat() == null ^ this.getMessageFormat() == null)
return false;
if (other.getMessageFormat() != null && other.getMessageFormat().equals(this.getMessageFormat()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getTargetArn() == null) ? 0 : getTargetArn().hashCode());
hashCode = prime * hashCode + ((getRoleArn() == null) ? 0 : getRoleArn().hashCode());
hashCode = prime * hashCode + ((getMessageFormat() == null) ? 0 : getMessageFormat().hashCode());
return hashCode;
}
@Override
public SnsAction clone() {
try {
return (SnsAction) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.iot.model.transform.SnsActionMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.regionserver;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.Stoppable;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.testclassification.MediumTests;
import org.apache.hadoop.hbase.testclassification.RegionServerTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.FSUtils;
import org.apache.hadoop.hbase.wal.WALFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TestName;
/**
* Tests a race condition between archiving of compacted files in CompactedHFilesDischarger chore
* and HRegion.close();
*/
@Category({RegionServerTests.class, MediumTests.class})
public class TestCompactionArchiveConcurrentClose {
public HBaseTestingUtility testUtil;
private Path testDir;
private AtomicBoolean archived = new AtomicBoolean();
@Rule
public TestName name = new TestName();
@Before
public void setup() throws Exception {
testUtil = HBaseTestingUtility.createLocalHTU();
testDir = testUtil.getDataTestDir("TestStoreFileRefresherChore");
FSUtils.setRootDir(testUtil.getConfiguration(), testDir);
}
@After
public void tearDown() throws Exception {
testUtil.cleanupTestDir();
}
@Test
public void testStoreCloseAndDischargeRunningInParallel() throws Exception {
byte[] fam = Bytes.toBytes("f");
byte[] col = Bytes.toBytes("c");
byte[] val = Bytes.toBytes("val");
final TableName tableName = TableName.valueOf(name.getMethodName());
HTableDescriptor htd = new HTableDescriptor(tableName);
htd.addFamily(new HColumnDescriptor(fam));
HRegionInfo info = new HRegionInfo(tableName, null, null, false);
HRegion region = initHRegion(htd, info);
RegionServerServices rss = mock(RegionServerServices.class);
List<Region> regions = new ArrayList<>();
regions.add(region);
when(rss.getRegions()).thenReturn(regions);
// Create the cleaner object
CompactedHFilesDischarger cleaner =
new CompactedHFilesDischarger(1000, (Stoppable) null, rss, false);
// Add some data to the region and do some flushes
int batchSize = 10;
int fileCount = 10;
for (int f = 0; f < fileCount; f++) {
int start = f * batchSize;
for (int i = start; i < start + batchSize; i++) {
Put p = new Put(Bytes.toBytes("row" + i));
p.addColumn(fam, col, val);
region.put(p);
}
// flush them
region.flush(true);
}
HStore store = region.getStore(fam);
assertEquals(fileCount, store.getStorefilesCount());
Collection<HStoreFile> storefiles = store.getStorefiles();
// None of the files should be in compacted state.
for (HStoreFile file : storefiles) {
assertFalse(file.isCompactedAway());
}
// Do compaction
region.compact(true);
// now run the cleaner with a concurrent close
Thread cleanerThread = new Thread() {
public void run() {
cleaner.chore();
}
};
cleanerThread.start();
// wait for cleaner to pause
synchronized (archived) {
if (!archived.get()) {
archived.wait();
}
}
final AtomicReference<Exception> closeException = new AtomicReference<>();
Thread closeThread = new Thread() {
public void run() {
// wait for the chore to complete and call close
try {
((HRegion) region).close();
} catch (IOException e) {
closeException.set(e);
}
}
};
closeThread.start();
// no error should occur after the execution of the test
closeThread.join();
cleanerThread.join();
if (closeException.get() != null) {
throw closeException.get();
}
}
private HRegion initHRegion(HTableDescriptor htd, HRegionInfo info)
throws IOException {
Configuration conf = testUtil.getConfiguration();
Path tableDir = FSUtils.getTableDir(testDir, htd.getTableName());
HRegionFileSystem fs = new WaitingHRegionFileSystem(conf, tableDir.getFileSystem(conf),
tableDir, info);
ChunkCreator.initialize(MemStoreLABImpl.CHUNK_SIZE_DEFAULT, false, 0, 0, 0, null);
final Configuration walConf = new Configuration(conf);
FSUtils.setRootDir(walConf, tableDir);
final WALFactory wals = new WALFactory(walConf, null, "log_" + info.getEncodedName());
HRegion region =
new HRegion(fs, wals.getWAL(info.getEncodedNameAsBytes(), info.getTable().getNamespace()),
conf, htd, null);
region.initialize();
return region;
}
private class WaitingHRegionFileSystem extends HRegionFileSystem {
public WaitingHRegionFileSystem(final Configuration conf, final FileSystem fs,
final Path tableDir, final HRegionInfo regionInfo) {
super(conf, fs, tableDir, regionInfo);
}
@Override
public void removeStoreFiles(String familyName, Collection<HStoreFile> storeFiles)
throws IOException {
super.removeStoreFiles(familyName, storeFiles);
archived.set(true);
synchronized (archived) {
archived.notifyAll();
}
try {
// unfortunately we can't use a stronger barrier here as the fix synchronizing
// the race condition will then block
Thread.sleep(100);
} catch (InterruptedException ie) {
throw new InterruptedIOException("Interrupted waiting for latch");
}
}
}
}
| |
package com.genie.beans;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Random;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import com.genie.dao.AssignmentDAO;
import com.genie.dao.AuthorityDAO;
import com.genie.dao.CourseDAO;
import com.genie.dao.CoursePlanDAO;
import com.genie.dao.GamificationDAO;
import com.genie.dao.SchoolYearDAO;
import com.genie.dao.SemesterCourseDAO;
import com.genie.dao.SemesterDAO;
import com.genie.dao.UserDAO;
import com.genie.enums.AchievementType;
import com.genie.enums.ComparisonType;
import com.genie.enums.GradingCriteria;
import com.genie.enums.LeaderboardVisibility;
import com.genie.enums.SampleImageFolder;
import com.genie.model.Achievement;
import com.genie.model.Assignment;
import com.genie.model.Authority;
import com.genie.model.Badge;
import com.genie.model.Course;
import com.genie.model.CoursePlan;
import com.genie.model.GamificationSettings;
import com.genie.model.GradeCriteria;
import com.genie.model.LeaderboardSettings;
import com.genie.model.SchoolYear;
import com.genie.model.Semester;
import com.genie.model.SemesterCourse;
import com.genie.model.StudentGamificationSettings;
import com.genie.model.StudentPoint;
import com.genie.model.User;
import com.genie.security.Role;
import com.genie.utils.DataFormatter;
import com.genie.utils.ResourceUtil;
/**
* @author ccubukcu
*
*/
public class AfterLoadControllerBean extends SpringBeanAutowiringSupport implements ApplicationListener<ContextRefreshedEvent>{
private boolean createDummyData = false;
@Autowired
private UserDAO userDAO;
@Autowired
private SchoolYearDAO yearDAO;
@Autowired
private SemesterDAO semesterDAO;
@Autowired
private CourseDAO courseDAO;
@Autowired
private SemesterCourseDAO semesterCourseDAO;
@Autowired
private AuthorityDAO authorityDAO;
@Autowired
private CoursePlanDAO coursePlanDAO;
@Autowired
private AssignmentDAO assignmentDAO;
@Autowired
private GamificationDAO gamificationDAO;
@Override
public void onApplicationEvent(ContextRefreshedEvent arg0) {
checkAdminUser();
if(createDummyData) {
User ins = userDAO.getByUsername("instructor");
if(ins == null) {
createTestUsers();
}
}
}
public void checkAdminUser() {
User admin = userDAO.getByUsername("admin");
if(admin == null) {
admin = createUser("admin", "admin", Role.ROLE_ADMINISTRATOR.toString());
userDAO.saveUserWithAuthority(admin);
}
}
public void createTestUsers() {
//
// Create instructors and demonstrators
//
User i = createUser("i", "i", Role.ROLE_INSTRUCTOR.toString());
userDAO.saveUserWithAuthority(i);
User instructor = createUser("instructor", "instructor", Role.ROLE_INSTRUCTOR.toString());
userDAO.saveUserWithAuthority(instructor);
List<User> instructors = new ArrayList<User>();
for(int insNr = 1; insNr<26; insNr++) {
User instr = createUser("instructor" + insNr, "instructor" + insNr, Role.ROLE_INSTRUCTOR.toString());
userDAO.saveUserWithAuthority(instr);
instructors.add(instr);
}
List<User> students = new ArrayList<User>();
for(int stNr = 1; stNr<26; stNr++) {
User stu = createUser("student" + stNr, "student" + stNr, Role.ROLE_STUDENT.toString());
userDAO.saveUserWithAuthority(stu);
students.add(stu);
}
//
// Create School Year
//
SchoolYear yr1 = new SchoolYear();
yr1.setYearIdentifier("Year of 2014/2015");
yr1.setStartDate(stringToDate("18/09/2014"));
yr1.setEndDate(stringToDate("21/08/2015"));
yr1.setNotes("This is the year of 2014/2015 which starts on 18/09/2014 and ends on 21/08/2015");
yearDAO.save(yr1);
SchoolYear yr2 = new SchoolYear();
yr2.setYearIdentifier("Year of 2015/2016");
yr2.setStartDate(stringToDate("14/10/2015"));
yr2.setEndDate(stringToDate("24/09/2016"));
yr2.setNotes("This is the year of 2015/2016 which starts on 14/10/2015 and ends on 24/09/2016");
yearDAO.save(yr2);
//
// Create 4 semesters
//
List<Semester> semesters = new ArrayList<Semester>();
Semester sm1 = new Semester();
sm1.setSchoolYearId(yr1.getId());
sm1.setSemesterIdentifier("Semester 1 of 14/15");
sm1.setSemesterOrder(1);
sm1.setStartDate(stringToDate("18/09/2014"));
sm1.setEndDate(stringToDate("21/12/2014"));
sm1.setNotes("Semester 1 of year 2014/2015 which starts on 18/09/2014 and ends on 21/12/2014");
semesterDAO.save(sm1);
semesters.add(sm1);
Semester sm2 = new Semester();
sm2.setSchoolYearId(yr1.getId());
sm2.setSemesterIdentifier("Semester 2 of 14/15");
sm2.setSemesterOrder(2);
sm2.setStartDate(stringToDate("12/01/2015"));
sm2.setEndDate(stringToDate("05/06/2015"));
sm2.setNotes("Semester 2 of year 2014/2015 which starts on 12/01/2015 and ends on 05/06/2015");
semesterDAO.save(sm2);
semesters.add(sm2);
Semester sm21 = new Semester();
sm21.setSchoolYearId(yr2.getId());
sm21.setSemesterIdentifier("Semester 1 of 15/16");
sm21.setSemesterOrder(1);
sm21.setStartDate(stringToDate("14/10/2015"));
sm21.setEndDate(stringToDate("29/01/2016"));
sm21.setNotes("Semester 1 of year 2015/2016 which starts on 14/10/2015 and ends on 29/01/2016");
semesterDAO.save(sm21);
semesters.add(sm21);
Semester sm22 = new Semester();
sm22.setSchoolYearId(yr2.getId());
sm22.setSemesterIdentifier("Semester 2 of 15/16");
sm22.setSemesterOrder(2);
sm22.setStartDate(stringToDate("19/02/2016"));
sm22.setEndDate(stringToDate("30/06/2016"));
sm22.setNotes("Semester 2 of year 2015/2016 which starts on 19/02/2016 and ends on 30/06/2016");
semesterDAO.save(sm22);
semesters.add(sm22);
//
// Create 2 courses and related authorities
//
List<SemesterCourse> courses = new ArrayList<SemesterCourse>();
for(int insNr = 0; insNr < instructors.size(); insNr++) {
User user = instructors.get(insNr);
int rand = new Random().nextInt(2)+1;
for(int p = 0; p < rand; p++) {
String courseCode = "C" + Integer.toString(insNr) + "0" + Integer.toString(p+1);
Course c1 = new Course();
c1.setCourseIdentifier(courseCode);
c1.setCourseName("Course by " + user.getUsername());
c1.setInstructor(user.getUsername());
c1.setShortDescription("Short Description of the course " + courseCode + ". Enrollment code: enroll");
c1.setLongDescription("This is the long description for " + courseCode + " - " + c1.getCourseName());
courseDAO.save(c1);
Authority ac1 = new Authority();
ac1.setUsername(user.getUsername());
ac1.setAuthority(Role.ROLE_INSTRUCTOR.toString());
ac1.setCourseId(c1.getId());
authorityDAO.save(ac1);
SemesterCourse sc1 = new SemesterCourse();
Semester sem = semesters.get(new Random().nextInt(semesters.size()));
sc1.setSemesterId(sem.getId());
sc1.setSemester(sem);
sc1.setCourseId(c1.getId());
sc1.setCourse(c1);
sc1.setEnrollmentKey("enroll");
semesterCourseDAO.save(sc1);
createGeneralGamificationSettings(sc1.getId());
createLeaderboardSettings(sc1.getId());
courses.add(sc1);
}
}
//
// Create grading criteria
//
for (SemesterCourse sc : courses) {
sc.setGradeCriteria(createGradeCriteria(sc.getId()));
}
//
// Create 15 week course plan
//
for (SemesterCourse sc : courses) {
List<Long> cpIdList = createCoursePlan(sc.getId());
List<Assignment> asgn = createAssignments(cpIdList, sc.getSemester());
Collections.shuffle(students, new Random(System.nanoTime()));
int studentCount = new Random().nextInt(7)+5;
List<User> subList = students.subList(0, studentCount);
for (User stu : subList) {
Authority ac = new Authority();
ac.setUsername(stu.getUsername());
ac.setAuthority(Role.ROLE_STUDENT.toString());
ac.setCourseId(sc.getCourseId());
ac.setSemesterId(sc.getSemesterId());
authorityDAO.save(ac);
createStudentGamificationSettings(sc.getId(), stu.getUsername());
}
createStudentPoints(subList, sc);
List<Badge> badges = createBadges(sc);
createAchievements(sc, badges, asgn);
}
}
public void createAchievements(SemesterCourse sc, List<Badge> badges, List<Assignment> assignments) {
Random random = new Random();
int nr = random.nextInt(25);
for(int i=0; i<nr; i++) {
Achievement ach = new Achievement();
ach.setName("Achievement " + i);
ach.setDescription(("This achievement is created automatically for testing purposes which is a achievement for " + sc.getCourse().getCourseIdentifier() + " on " + sc.getSemester().getSemesterIdentifier()));
SampleImageFolder sif = SampleImageFolder.randomFolder();
ach.setUsingUploadedImage(false);
ach.setResourceImageFolder(sif.getIndex());
ach.setResourceImageName(ResourceUtil.getRandomImageFromFolder(sif.getResourceFolderPath()));
ach.setSemesterCourseId(sc.getId());
GradeCriteria targetGC = sc.getGradeCriteria().get(random.nextInt(sc.getGradeCriteria().size()));
ach.setTargetGradeCriteriaId(targetGC.getId());
ach.setAchievementType(AchievementType.getRandomType().getIndex());
ach.setThresholdValue(random.nextInt(100)+1);
ach.setTargetCount(random.nextInt(5)+1);
ach.setComparisonType(ComparisonType.getRandomType().getIndex());
if(random.nextBoolean()) {
ach.setPointReward(random.nextInt(500)+250L);
}
if(random.nextBoolean() && badges.size() > 0) {
Badge randomBadge = badges.get(random.nextInt(badges.size()));
ach.setBadgeRewardId(randomBadge.getId());
}
if(random.nextBoolean()) {
GradeCriteria gc = sc.getGradeCriteria().get(random.nextInt(sc.getGradeCriteria().size()));
int grade = random.nextInt(100)+1;
ach.setGradeReward(grade);
if(gc.getGradingCriteria() == GradingCriteria.ASSIGNMENT.getIndex()) {
Assignment asgn = assignments.get(random.nextInt(assignments.size()));
ach.setRewardAssignmentId(asgn.getId());
} else if (gc.getGradingCriteria() == GradingCriteria.ATTENDANCE.getIndex()) {
ach.setWeekReward(random.nextInt(15));
} else {
GradeCriteria rewardGC = sc.getGradeCriteria().get(random.nextInt(sc.getGradeCriteria().size()));
ach.setRewardGradeCriteriaId(rewardGC.getId());
}
}
gamificationDAO.save(ach);
}
}
public List<Badge> createBadges(SemesterCourse sc) {
int nr = new Random().nextInt(25);
List<Badge> badges = new ArrayList<Badge>();
for(int i=0; i<nr; i++) {
Badge badge = new Badge();
badge.setName("Badge " + i);
badge.setSemesterCourseId(sc.getId());
SampleImageFolder sif = SampleImageFolder.randomFolder();
badge.setUsingUploadedImage(false);
badge.setResourceImageFolder(sif.getIndex());
badge.setResourceImageName(ResourceUtil.getRandomImageFromFolder(sif.getResourceFolderPath()));
badge.setDescription(("This badge is created automatically for testing purposes which is a badge for " + sc.getCourse().getCourseIdentifier() + " on " + sc.getSemester().getSemesterIdentifier()));
gamificationDAO.save(badge);
badges.add(badge);
}
return badges;
}
public void createStudentPoints(List<User> students, SemesterCourse sc) {
Random random = new Random();
for (User stu : students) {
int count = random.nextInt(10);
for(int i = 0; i < count; i++) {
int points = random.nextInt(1500)+200;
StudentPoint sp = new StudentPoint();
sp.setSemesterCourseId(sc.getId());
sp.setPoints((long)points);
sp.setUsername(stu.getUsername());
gamificationDAO.save(sp);
}
}
}
public void createGeneralGamificationSettings(long scid) {
Random random = new Random();
GamificationSettings gs = new GamificationSettings();
gs.setGamificationEnabled(true);
gs.setLeaderboardsEnabled(true);
gs.setBadgesEnabled(true);
gs.setAchievementsEnabled(true);
gs.setMaxConvertablePoints(random.nextInt(10000));
gs.setPointsName("Points");
gs.setSemesterCourseId(scid);
courseDAO.save(gs);
}
public void createLeaderboardSettings(long scid) {
LeaderboardSettings ls = new LeaderboardSettings();
Random random = new Random();
ls.setAnonymous(random.nextBoolean());
ls.setTopStudents(random.nextInt(5)+1);
ls.setBottomStudents(random.nextInt(5)+1);
ls.setVisibility(LeaderboardVisibility.getRandomVisibility().getIndex());
gamificationDAO.save(ls);
}
public void createStudentGamificationSettings(long scid, String username) {
StudentGamificationSettings gs = new StudentGamificationSettings();
gs.setGamificationEnabled(true);
gs.setLeaderboardsEnabled(true);
gs.setBadgesEnabled(true);
gs.setAchievementsEnabled(true);
gs.setSemesterCourseId(scid);
gs.setStudentName(username);
courseDAO.save(gs);
}
public List<GradeCriteria> createGradeCriteria(long scid) {
Random random = new Random();
List<GradeCriteria> list = new ArrayList<GradeCriteria>();
int totalWeight = 100;
GradeCriteria gc1 = new GradeCriteria();
gc1.setName("Midterm 1");
gc1.setGradingCriteria(GradingCriteria.EXAM.getIndex());
gc1.setWeight(random.nextInt(10)+5);
gc1.setSemesterCourseId(scid);
semesterCourseDAO.save(gc1);
list.add(gc1);
totalWeight -= gc1.getWeight();
GradeCriteria gc2 = new GradeCriteria();
gc2.setName("Midterm 2");
gc2.setGradingCriteria(GradingCriteria.EXAM.getIndex());
gc2.setWeight(random.nextInt(10)+5);
gc2.setSemesterCourseId(scid);
semesterCourseDAO.save(gc2);
list.add(gc2);
totalWeight -= gc2.getWeight();
GradeCriteria gc3 = new GradeCriteria();
gc3.setName("Final");
gc3.setGradingCriteria(GradingCriteria.EXAM.getIndex());
gc3.setWeight(random.nextInt(15)+15);
gc3.setSemesterCourseId(scid);
semesterCourseDAO.save(gc3);
list.add(gc3);
totalWeight -= gc3.getWeight();
GradeCriteria gc4 = new GradeCriteria();
gc4.setName("Attendance");
gc4.setGradingCriteria(GradingCriteria.ATTENDANCE.getIndex());
gc4.setWeight(random.nextInt(totalWeight/3));
gc4.setSemesterCourseId(scid);
semesterCourseDAO.save(gc4);
list.add(gc4);
totalWeight -= gc4.getWeight();
GradeCriteria gc5 = new GradeCriteria();
gc5.setName("Attendance");
gc5.setGradingCriteria(GradingCriteria.GAMIFICATION.getIndex());
gc5.setWeight(random.nextInt(totalWeight/3));
gc5.setSemesterCourseId(scid);
semesterCourseDAO.save(gc5);
list.add(gc5);
totalWeight -= gc5.getWeight();
GradeCriteria gc6 = new GradeCriteria();
gc6.setName("Participation");
gc6.setGradingCriteria(GradingCriteria.OTHER.getIndex());
gc6.setWeight(random.nextInt(totalWeight/2));
gc6.setSemesterCourseId(scid);
semesterCourseDAO.save(gc6);
list.add(gc6);
totalWeight -= gc6.getWeight();
GradeCriteria gc7 = new GradeCriteria();
gc7.setName("Assignments");
gc7.setGradingCriteria(GradingCriteria.ASSIGNMENT.getIndex());
gc7.setWeight(totalWeight);
gc7.setSemesterCourseId(scid);
semesterCourseDAO.save(gc7);
list.add(gc7);
return list;
}
public List<Long> createCoursePlan(long scid) {
List<Long> idList = new ArrayList<Long>();
Random random = new Random();
int weekLength = random.nextInt(10) + 10;
int totalLength = 0;
int i = 1;
while(totalLength < weekLength) {
int currentLength = random.nextInt(5) + 1;
if(currentLength + totalLength > weekLength) {
currentLength = weekLength - totalLength;
}
CoursePlan cp1 = new CoursePlan();
cp1.setCoursePlanTitle("Course Plan Section " + i);
cp1.setSemesterCourseId(scid);
cp1.setPlanOrder(i);
cp1.setPlanLength(currentLength);
cp1.setDescription("This is the details of the section " + i + " of the course plan");
coursePlanDAO.save(cp1);
idList.add(cp1.getId());
totalLength += currentLength;
i++;
}
return idList;
}
public List<Assignment> createAssignments(List<Long> idList, Semester sem) {
DateTime start = new DateTime(sem.getStartDate());
List<Assignment> assignments = new ArrayList<Assignment>();
int k = 1;
int asgnCount = new Random().nextInt(10) + 1;
int individualWeight = 100 / asgnCount;
for (int i = 0; i < asgnCount; i++) {
Assignment asgn = new Assignment();
asgn.setPlanId(idList.get(new Random().nextInt(idList.size())));
asgn.setName("Assignment " + Integer.toString(k));
asgn.setWeight((long)individualWeight);
asgn.setDescription("Assignment Description, a very detailed one " + Integer.toString(k));
asgn.setDueDate(start.toDate());
assignmentDAO.save(asgn);
assignments.add(asgn);
k++;
}
return assignments;
}
public Date stringToDate(String date) {
return DataFormatter.stringToDate(date);
}
public User createUser(String username, String password, String authority) {
User newUser = new User();
newUser.setPassword(DataFormatter.md5String(password));
newUser.setUsername(username);
newUser.setFullName(username);
newUser.setActive(true);
List<Authority> authList = new ArrayList<Authority>();
Authority auth = new Authority();
auth.setUsername(newUser.getUsername());
auth.setAuthority(authority);
authList.add(auth);
newUser.setAuthorities(authList);
return newUser;
}
public User createUser(String username, String password, String authority, Long courseId, Long semesterId) {
User newUser = new User();
newUser.setPassword(DataFormatter.md5String(password));
newUser.setUsername(username);
newUser.setFullName(username);
newUser.setActive(true);
List<Authority> authList = new ArrayList<Authority>();
Authority auth = new Authority();
auth.setUsername(newUser.getUsername());
auth.setAuthority(authority);
auth.setCourseId(courseId);
auth.setSemesterId(semesterId);
authList.add(auth);
newUser.setAuthorities(authList);
return newUser;
}
}
| |
/*
* Copyright 2014 Yaroslav Mytkalyk
* 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.docd.purefm;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import com.docd.purefm.commandline.CommandListBusyboxApplets;
import com.docd.purefm.commandline.CommandLine;
import com.docd.purefm.commandline.ShellHolder;
import com.docd.purefm.utils.StorageHelper;
import com.stericson.RootTools.execution.Shell;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
public final class Environment {
private Environment() {}
@NonNull
private static final ActivityMonitorListener sActivityMonitorListener = new ActivityMonitorListener();
@NonNull
public static final File sRootDirectory = File.listRoots()[0];
@NonNull
public static final File sAndroidRootDirectory = android.os.Environment.getRootDirectory();
private static boolean sExternalStorageMounted;
private static Context sContext;
public static boolean sHasRoot;
public static String sBusybox;
private static List<StorageHelper.Volume> sVolumes;
private static List<StorageHelper.StorageVolume> sStorages;
public static void init(final Application context) {
sContext = context;
sBusybox = getUtilPath("busybox");
if (sBusybox == null) {
sBusybox = getUtilPath("busybox-ba");
}
sHasRoot = isUtilAvailable("su");
updateExternalStorageState();
context.registerActivityLifecycleCallbacks(sActivityMonitorListener);
}
public static boolean isReadOnly(@NonNull final StorageHelper.StorageVolume volume) {
if (volume.file.getAbsolutePath().equals(
android.os.Environment.getExternalStorageDirectory().getAbsolutePath())) {
return android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED_READ_ONLY);
}
if (volume.getType() == StorageHelper.StorageVolume.Type.EXTERNAL) {
return volume.isReadOnly() || Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
}
return false;
}
@NonNull
public static List<StorageHelper.Volume> getVolumes() {
if (sVolumes == null) {
throw new IllegalStateException("Environment was not initialized");
}
return sVolumes;
}
@NonNull
public static List<StorageHelper.StorageVolume> getStorageVolumes() {
if (sStorages == null) {
throw new IllegalStateException("Environment was not initialized");
}
return sStorages;
}
public static boolean hasBusybox() {
return sBusybox != null;
}
@Nullable
public static String getBusybox() {
return sBusybox;
}
public static boolean isExternalStorageMounted() {
return sExternalStorageMounted;
}
@SuppressWarnings("ForLoopReplaceableByForEach")
@SuppressLint("SdCardPath")
@Nullable
public static String getUtilPath(String utilname) {
final String[] places = { "/sbin/", "/system/bin/", "/system/xbin/", "/data/local/xbin/",
"/data/local/bin/", "/system/sd/xbin/", "/system/bin/failsafe/", "/data/local/", "/data/data/burrows.apps.busybox/app_busybox/", "/data/data/burrows.apps.busybox.paid/app_busybox/"};
for (int i = 0; i < places.length; i++) {
final File[] files = new File(places[i]).listFiles();
if (files != null) {
for (int j = 0; j < files.length; j++) {
final File current = files[j];
if (current.getName().equals(utilname)) {
return current.getAbsolutePath();
}
}
}
}
return null;
}
@SuppressWarnings("ForLoopReplaceableByForEach")
@SuppressLint("SdCardPath")
public static boolean isUtilAvailable(String utilname) {
final String[] places = { "/sbin/", "/system/bin/", "/system/xbin/", "/data/local/xbin/",
"/data/local/bin/", "/system/sd/xbin/", "/system/bin/failsafe/", "/data/local/", "/data/data/burrows.apps.busybox/app_busybox/", "/data/data/burrows.apps.busybox.paid/app_busybox/"};
for (int i = 0; i < places.length; i++) {
final String[] files = new File(places[i]).list();
if (files != null) {
for (int j = 0; j < files.length; j++) {
if (files[j].equals(utilname)) {
return true;
}
}
}
}
return false;
}
public static boolean needsRemount(final @NonNull String path) {
if (path.equals(sRootDirectory.getAbsolutePath())) {
return true;
}
if (path.startsWith(sAndroidRootDirectory.getAbsolutePath())) {
return true;
}
for (final StorageHelper.Volume volume : sVolumes) {
if (path.startsWith(volume.file.getAbsolutePath())) {
return volume.isReadOnly();
}
try {
if (path.startsWith(volume.file.getCanonicalPath())) {
return volume.isReadOnly();
}
} catch (IOException e) {
//ignored
}
}
return true;
}
@Nullable
public static StorageHelper.StorageVolume volumeOfPath(@NonNull final String path) {
for (final StorageHelper.StorageVolume volume : sStorages) {
if (path.startsWith(volume.file.getAbsolutePath())) {
return volume;
}
}
return null;
}
public static boolean isBusyboxUtilAvailable(@NonNull final String util) {
if (sBusybox == null) {
return false;
}
final List<String> result = CommandLine.executeForResult(new CommandListBusyboxApplets());
if (result != null) {
for (final String resultLine : result) {
if (resultLine.equals(util)) {
return true;
}
}
}
return false;
}
private static boolean isExternalMounted() {
final String state = android.os.Environment.getExternalStorageState();
return state.equals(android.os.Environment.MEDIA_MOUNTED) ||
state.equals(android.os.Environment.MEDIA_MOUNTED_READ_ONLY);
}
// ============== STORAGE LISTENER ===============
private static void updateExternalStorageState() {
final boolean isExternalStorageMounted = isExternalMounted();
if (sVolumes == null && isExternalStorageMounted || sExternalStorageMounted != isExternalStorageMounted) {
sExternalStorageMounted = isExternalStorageMounted;
sVolumes = StorageHelper.getAllDevices();
sStorages = StorageHelper.getStorageVolumes(sVolumes);
// longest names should be first to detect mount point properly
Collections.sort(sVolumes, StorageHelper.VOLUME_PATH_LENGTH_COMPARATOR);
}
}
private static final ExternalStorageStateReceiver externalStorageStateReceiver =
new ExternalStorageStateReceiver();
static final class ExternalStorageStateReceiver extends BroadcastReceiver {
static final IntentFilter intentFilter = new IntentFilter();
static {
intentFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
intentFilter.addAction(Intent.ACTION_MEDIA_REMOVED);
}
@Override
public void onReceive(Context context, Intent intent) {
updateExternalStorageState();
}
}
// =============== ACTIVITY MONITOR ===============
private static final class ActivityMonitorListener implements
Application.ActivityLifecycleCallbacks {
private static final Object LOCK = new Object();
private volatile boolean mIsReceiverRegistered;
private volatile int mStartedCount;
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityStarted(Activity activity) {
if (++mStartedCount == 1) {
synchronized (LOCK) {
if (!mIsReceiverRegistered) {
sContext.registerReceiver(externalStorageStateReceiver, ExternalStorageStateReceiver.intentFilter);
mIsReceiverRegistered = true;
updateExternalStorageState();
}
}
}
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
if (--mStartedCount == 0) {
synchronized (LOCK) {
if (this.mIsReceiverRegistered) {
sContext.unregisterReceiver(externalStorageStateReceiver);
this.mIsReceiverRegistered = false;
}
}
}
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
}
}
| |
/*
* Copyright 2015 LG CNS.
*
* 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.
*
*
* The initial idea for this class is from "org.apache.commons.lang.IntHashMap";
* http://commons.apache.org/commons-lang-2.6-src.zip
*
*/
package scouter.util;
import java.util.Enumeration;
import java.util.NoSuchElementException;
public class LongKeyLinkedMap<V> {
private static final int DEFAULT_CAPACITY = 101;
private static final float DEFAULT_LOAD_FACTOR = 0.75f;
private ENTRY<V> table[];
private ENTRY<V> header;
private int count;
private int threshold;
private float loadFactor;
public LongKeyLinkedMap(int initCapacity, float loadFactor) {
if (initCapacity < 0)
throw new RuntimeException("Capacity Error: " + initCapacity);
if (loadFactor <= 0)
throw new RuntimeException("Load Count Error: " + loadFactor);
if (initCapacity == 0)
initCapacity = 1;
this.loadFactor = loadFactor;
this.table = new ENTRY[initCapacity];
this.header =new ENTRY(0,null,null);
this.header.link_next = header.link_prev = header;
threshold = (int) (initCapacity * loadFactor);
}
public LongKeyLinkedMap() {
this(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR);
}
public int size() {
return count;
}
public long[] keyArray() {
long[] _keys=new long[this.size()];
LongEnumer en = this.keys();
for(int i = 0 ; i<_keys.length;i++)
_keys[i]=en.nextLong();
return _keys;
}
public synchronized LongEnumer keys() {
return new Enumer(TYPE.KEYS);
}
public synchronized Enumeration<V> values() {
return new Enumer<V>(TYPE.VALUES);
}
public synchronized Enumeration<ENTRY> entries() {
return new Enumer<ENTRY>(TYPE.ENTRIES);
}
public synchronized boolean containsValue(Object value) {
if (value == null) {
return false;
}
ENTRY tab[] = table;
int i = tab.length; while(i-->0){
for (ENTRY e = tab[i]; e != null; e = e.next) {
if (CompareUtil.equals(e.value,value)) {
return true;
}
}
}
return false;
}
public synchronized boolean containsKey(long key) {
ENTRY tab[] = table;
int index = hash(key) % tab.length;
for (ENTRY e = tab[index]; e != null; e = e.next) {
if (CompareUtil.equals(e.key,key)) {
return true;
}
}
return false;
}
public synchronized V get(long key) {
ENTRY<V> tab[] = table;
int index = hash(key) % tab.length;
for (ENTRY<V> e = tab[index]; e != null; e = e.next) {
if (CompareUtil.equals(e.key,key)) {
return e.value;
}
}
return null;
}
public synchronized long getFirstKey() {
return this.header.link_next.key;
}
public synchronized long getLastKey() {
return this.header.link_prev.key;
}
public synchronized V getFirstValue() {
return this.header.link_next.value;
}
public synchronized V getLastValue() {
return this.header.link_prev.value;
}
private int hash(long key) {
return (int) (key ^ (key >>> 32)) & Integer.MAX_VALUE;
}
protected void rehash() {
int oldCapacity = table.length;
ENTRY oldMap[] = table;
int newCapacity = oldCapacity * 2 + 1;
ENTRY newMap[] = new ENTRY[newCapacity];
threshold = (int) (newCapacity * loadFactor);
table = newMap;
for (int i = oldCapacity; i-- > 0;) {
ENTRY old = oldMap[i]; while(old!=null) {
ENTRY e = old;
old = old.next;
long key = e.key;
int index = hash(key) % newCapacity;
e.next = newMap[index];
newMap[index] = e;
}
}
}
private int max;
public LongKeyLinkedMap<V> setMax(int max){
this.max=max;
return this;
}
private static enum MODE{FORCE_FIRST, FORCE_LAST, FIRST, LAST};
public V put(long key, V value) {
return _put(key, value, MODE.LAST);
}
public V putLast(long key, V value) {
return _put(key, value, MODE.FORCE_LAST);
}
public V putFirst(long key, V value) {
return _put(key, value, MODE.FORCE_FIRST);
}
private synchronized V _put(long key, V value, MODE m) {
ENTRY tab[] = table;
int index = hash(key) % tab.length;
for (ENTRY<V> e = tab[index]; e != null; e = e.next) {
if (CompareUtil.equals(e.key,key)) {
V old = e.value;
e.value = value;
switch(m){
case FORCE_FIRST:
if(header.link_next!=e){
unchain(e);
chain(header, header.link_next, e);
}
break;
case FORCE_LAST:
if(header.link_prev!=e){
unchain(e);
chain(header.link_prev, header, e);
}
break;
}
return old;
}
}
if(max >0){
switch(m){
case FORCE_FIRST:
case FIRST:
while(count >= max){
removeLast();
}
break;
case FORCE_LAST:
case LAST:
while(count >= max){
removeFirst();
}
break;
}
}
if (count >= threshold) {
rehash();
tab = table;
index = hash(key) % tab.length;
}
ENTRY e = new ENTRY(key, value, tab[index]);
tab[index] = e;
switch(m){
case FORCE_FIRST:
case FIRST:
chain(header, header.link_next, e);
break;
case FORCE_LAST:
case LAST:
chain(header.link_prev, header, e);
break;
}
count++;
return null;
}
public synchronized V remove(long key) {
ENTRY tab[] = table;
int index = hash(key) % tab.length;
for (ENTRY<V> e = tab[index], prev = null; e != null; prev = e, e = e.next) {
if (CompareUtil.equals(e.key,key)) {
if (prev != null) {
prev.next = e.next;
} else {
tab[index] = e.next;
}
count--;
V oldValue = e.value;
e.value = null;
//
unchain(e);
return oldValue;
}
}
return null;
}
public synchronized V removeFirst() {
if (isEmpty())
return null;
return remove(header.link_next.key);
}
public synchronized V removeLast() {
if (isEmpty())
return null;
return remove(header.link_prev.key);
}
public boolean isEmpty() {
return size() == 0;
}
public synchronized void clear() {
ENTRY tab[] = table;
for (int index = tab.length; --index >= 0;)
tab[index] = null;
this.header.link_next = header.link_prev = header;
count = 0;
}
public String toString() {
StringBuffer buf = new StringBuffer();
Enumeration it = entries();
buf.append("{");
for(int i=0;it.hasMoreElements();i++){
ENTRY e = (ENTRY) (it.nextElement());
if (i>0)
buf.append(", ");
buf.append(e.getKey() + "=" + e.getValue());
}
buf.append("}");
return buf.toString();
}
public String toFormatString() {
StringBuffer buf = new StringBuffer();
Enumeration it = entries();
buf.append("{\n");
while(it.hasMoreElements()){
ENTRY e = (ENTRY)it.nextElement();
buf.append("\t").append(e.getKey() + "=" + e.getValue()).append("\n");
}
buf.append("}");
return buf.toString();
}
public static class ENTRY<V> {
long key;
V value;
ENTRY<V> next;
ENTRY<V> link_next, link_prev;
protected ENTRY(long key, V value, ENTRY<V> next) {
this.key = key;
this.value = value;
this.next = next;
}
protected Object clone() {
return new ENTRY(key, value, (next == null ? null : (ENTRY) next.clone()));
}
public long getKey() {
return key;
}
public V getValue() {
return value;
}
public V setValue(V value) {
if (value == null)
throw new NullPointerException();
V oldValue = this.value;
this.value = value;
return oldValue;
}
public boolean equals(Object o) {
if (!(o instanceof ENTRY))
return false;
ENTRY e = (ENTRY) o;
return CompareUtil.equals(e.key,key) && CompareUtil.equals(e.value,value);
}
public int hashCode() {
return (int) (key ^ (key >>> 32)) ^ (value == null ? 0 : value.hashCode());
}
public String toString() {
return key + "=" + value;
}
}
private enum TYPE{KEYS, VALUES, ENTRIES }
private class Enumer<V> implements Enumeration, LongEnumer {
TYPE type;
ENTRY entry = LongKeyLinkedMap.this.header.link_next;
Enumer(TYPE type) {
this.type = type;
}
public boolean hasMoreElements() {
return header!=entry;
}
public V nextElement() {
if (entry != null) {
ENTRY e = entry;
entry = e.link_next;
switch (type) {
case KEYS:
return (V)new Long(e.key);
case VALUES:
return (V)e.value;
default:
return (V)e;
}
}
throw new NoSuchElementException("Enumerator");
}
public long nextLong() {
if (entry != null) {
ENTRY e = entry;
entry = e.link_next;
return e.key;
}
throw new NoSuchElementException("Enumer");
}
}
private void chain(ENTRY link_prev, ENTRY link_next, ENTRY e) {
e.link_prev = link_prev;
e.link_next = link_next;
link_prev.link_next = e;
link_next.link_prev = e;
}
private void unchain(ENTRY e) {
e.link_prev.link_next = e.link_next;
e.link_next.link_prev = e.link_prev;
e.link_prev = null;
e.link_next = null;
}
public static void main(String[] args) {
LongKeyLinkedMap m = new LongKeyLinkedMap().setMax(2);
m.putLast(10, 10);
m.putLast(20, 20);
m.putFirst(30, 30);
//m.removeFirst();
System.out.println(m);
m = new LongKeyLinkedMap().setMax(2);
m.putFirst(10, 10);
m.putFirst(20, 20);
m.putFirst(30, 30);
//m.removeLast();
System.out.println(m);
}
private static void print(Object e) {
System.out.println(e);
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.examples.complete;
import com.google.api.services.bigquery.model.TableRow;
import java.util.List;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.coders.TableRowJsonCoder;
import org.apache.beam.sdk.io.TextIO;
import org.apache.beam.sdk.options.Default;
import org.apache.beam.sdk.options.Description;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.options.Validation;
import org.apache.beam.sdk.transforms.Count;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.PTransform;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.transforms.SerializableComparator;
import org.apache.beam.sdk.transforms.Top;
import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
import org.apache.beam.sdk.transforms.windowing.CalendarWindows;
import org.apache.beam.sdk.transforms.windowing.IntervalWindow;
import org.apache.beam.sdk.transforms.windowing.Sessions;
import org.apache.beam.sdk.transforms.windowing.Window;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PCollection;
import org.joda.time.Duration;
import org.joda.time.Instant;
/**
* An example that reads Wikipedia edit data from Cloud Storage and computes the user with
* the longest string of edits separated by no more than an hour within each month.
*
* <p>Concepts: Using Windowing to perform time-based aggregations of data.
*
* <p>It is not recommended to execute this pipeline locally, given the size of the default input
* data.
*
* <p>To execute this pipeline using a selected runner and an output prefix on GCS, specify:
* <pre>{@code
* --runner=YOUR_SELECTED_RUNNER
* --output=gs://YOUR_OUTPUT_PREFIX
* }
* </pre>
* See examples/java/README.md for instructions about how to configure different runners.
*
* <p>The default input is {@code gs://apache-beam-samples/wikipedia_edits/*.json} and can be
* overridden with {@code --input}.
*
* <p>The input for this example is large enough that it's a good place to enable (experimental)
* autoscaling:
* <pre>{@code
* --autoscalingAlgorithm=BASIC
* --maxNumWorkers=20
* }
* </pre>
* This will automatically scale the number of workers up over time until the job completes.
*/
public class TopWikipediaSessions {
private static final String EXPORTED_WIKI_TABLE =
"gs://apache-beam-samples/wikipedia_edits/*.json";
/**
* Extracts user and timestamp from a TableRow representing a Wikipedia edit.
*/
static class ExtractUserAndTimestamp extends DoFn<TableRow, String> {
@ProcessElement
public void processElement(ProcessContext c) {
TableRow row = c.element();
int timestamp = (Integer) row.get("timestamp");
String userName = (String) row.get("contributor_username");
if (userName != null) {
// Sets the implicit timestamp field to be used in windowing.
c.outputWithTimestamp(userName, new Instant(timestamp * 1000L));
}
}
}
/**
* Computes the number of edits in each user session. A session is defined as
* a string of edits where each is separated from the next by less than an hour.
*/
static class ComputeSessions
extends PTransform<PCollection<String>, PCollection<KV<String, Long>>> {
@Override
public PCollection<KV<String, Long>> apply(PCollection<String> actions) {
return actions
.apply(Window.<String>into(Sessions.withGapDuration(Duration.standardHours(1))))
.apply(Count.<String>perElement());
}
}
/**
* Computes the longest session ending in each month.
*/
private static class TopPerMonth
extends PTransform<PCollection<KV<String, Long>>, PCollection<List<KV<String, Long>>>> {
@Override
public PCollection<List<KV<String, Long>>> apply(PCollection<KV<String, Long>> sessions) {
return sessions
.apply(Window.<KV<String, Long>>into(CalendarWindows.months(1)))
.apply(Top.of(1, new SerializableComparator<KV<String, Long>>() {
@Override
public int compare(KV<String, Long> o1, KV<String, Long> o2) {
return Long.compare(o1.getValue(), o2.getValue());
}
}).withoutDefaults());
}
}
static class SessionsToStringsDoFn extends DoFn<KV<String, Long>, KV<String, Long>> {
@ProcessElement
public void processElement(ProcessContext c, BoundedWindow window) {
c.output(KV.of(
c.element().getKey() + " : " + window, c.element().getValue()));
}
}
static class FormatOutputDoFn extends DoFn<List<KV<String, Long>>, String> {
@ProcessElement
public void processElement(ProcessContext c, BoundedWindow window) {
for (KV<String, Long> item : c.element()) {
String session = item.getKey();
long count = item.getValue();
c.output(session + " : " + count + " : " + ((IntervalWindow) window).start());
}
}
}
static class ComputeTopSessions extends PTransform<PCollection<TableRow>, PCollection<String>> {
private final double samplingThreshold;
public ComputeTopSessions(double samplingThreshold) {
this.samplingThreshold = samplingThreshold;
}
@Override
public PCollection<String> apply(PCollection<TableRow> input) {
return input
.apply(ParDo.of(new ExtractUserAndTimestamp()))
.apply("SampleUsers", ParDo.of(
new DoFn<String, String>() {
@ProcessElement
public void processElement(ProcessContext c) {
if (Math.abs(c.element().hashCode()) <= Integer.MAX_VALUE * samplingThreshold) {
c.output(c.element());
}
}
}))
.apply(new ComputeSessions())
.apply("SessionsToStrings", ParDo.of(new SessionsToStringsDoFn()))
.apply(new TopPerMonth())
.apply("FormatOutput", ParDo.of(new FormatOutputDoFn()));
}
}
/**
* Options supported by this class.
*
* <p>Inherits standard Beam configuration options.
*/
private interface Options extends PipelineOptions {
@Description(
"Input specified as a GCS path containing a BigQuery table exported as json")
@Default.String(EXPORTED_WIKI_TABLE)
String getInput();
void setInput(String value);
@Description("File to output results to")
@Validation.Required
String getOutput();
void setOutput(String value);
}
public static void main(String[] args) {
Options options = PipelineOptionsFactory.fromArgs(args)
.withValidation()
.as(Options.class);
Pipeline p = Pipeline.create(options);
double samplingThreshold = 0.1;
p.apply(TextIO.Read
.from(options.getInput())
.withCoder(TableRowJsonCoder.of()))
.apply(new ComputeTopSessions(samplingThreshold))
.apply("Write", TextIO.Write.withoutSharding().to(options.getOutput()));
p.run().waitUntilFinish();
}
}
| |
package shadow.interpreter;
import java.math.BigInteger;
import shadow.interpreter.InterpreterException.Error;
import shadow.typecheck.type.ArrayType;
import shadow.typecheck.type.ModifiedType;
import shadow.typecheck.type.Modifiers;
import shadow.typecheck.type.Type;
/**
* An abstract class that is the base of all values (array, boolean, code, number, object, string) in Shadow.
*/
public abstract class ShadowValue implements ModifiedType {
// Exposed here for convenience
public static final ShadowInvalid INVALID = ShadowInvalid.INVALID;
private Modifiers modifiers;
protected ShadowValue() {
this.modifiers = new Modifiers();
}
protected ShadowValue(int modifiers) {
this.modifiers = new Modifiers(modifiers);
}
@Override
public final Modifiers getModifiers() {
return modifiers;
}
@Override
public final void setType(Type type) {
throw new UnsupportedOperationException();
}
/** Applies the specified binary operation to this {@link ShadowValue} and another */
public final ShadowValue apply(BinaryOperator operator, ShadowValue right) throws InterpreterException {
if (this instanceof ShadowInvalid || right instanceof ShadowInvalid) {
return INVALID;
}
switch (operator) {
case COALESCE: return coalesce(right);
case OR: return or(right);
case XOR: return xor(right);
case AND: return and(right);
case BITWISE_OR: return bitwiseOr(right);
case BITWISE_XOR: return bitwiseXor(right);
case BITWISE_AND: return bitwiseAnd(right);
case EQUAL: return equal(right);
case NOT_EQUAL: return notEqual(right);
case REFERENCE_EQUAL: return referenceEqual(right);
case REFERENCE_NOT_EQUAL: return referenceNotEqual(right);
case LESS_THAN: return lessThan(right);
case GREATER_THAN: return greaterThan(right);
case LESS_THAN_OR_EQUAL: return lessThanOrEqual(right);
case GREATER_THAN_OR_EQUAL: return greaterThanOrEqual(right);
case CAT: return cat(right);
case RIGHT_SHIFT: return bitShiftRight(right);
case LEFT_SHIFT: return bitShiftLeft(right);
case RIGHT_ROTATE: return bitRotateRight(right);
case LEFT_ROTATE: return bitRotateLeft(right);
case ADD: return add(right);
case SUBTRACT: return subtract(right);
case MULTIPLY: return multiply(right);
case DIVIDE: return divide(right);
case MODULUS: return modulus(right);
default: throw new InterpreterException(Error.UNSUPPORTED_OPERATION,
"Unexpected binary operator " + operator.getName());
}
}
/** Applies the specified unary operation to this {@link ShadowValue} */
public final ShadowValue apply(UnaryOperator operator) throws InterpreterException {
if (this instanceof ShadowInvalid) {
return INVALID;
}
switch (operator) {
case CAT: return unaryCat();
case BITWISE_COMPLEMENT: return bitwiseComplement();
case NOT: return not();
case NEGATE: return negate();
default: throw new UnsupportedOperationException(
"Unexpected unary operator " + operator.getName());
}
}
public ShadowString unaryCat() throws InterpreterException {
return new ShadowString(toString());
}
public ShadowValue negate() throws InterpreterException {
throw new InterpreterException(Error.UNSUPPORTED_OPERATION, "Negate operation not supported");
}
public ShadowValue bitwiseComplement() throws InterpreterException {
throw new InterpreterException(Error.UNSUPPORTED_OPERATION, "Bitwise complement operation not supported");
}
public ShadowBoolean not() throws InterpreterException {
throw new InterpreterException(Error.UNSUPPORTED_OPERATION, "Not operation not supported");
}
public final ShadowValue coalesce(ShadowValue value) throws InterpreterException {
return (this instanceof ShadowNull) ? value : this;
}
public ShadowValue cat(ShadowValue value) throws InterpreterException {
return new ShadowString(toString() + value.toString());
}
// binary operations
public ShadowValue add(ShadowValue value) throws InterpreterException {
throw new InterpreterException(Error.UNSUPPORTED_OPERATION, "Add operation not supported");
}
public ShadowValue subtract(ShadowValue value) throws InterpreterException {
throw new InterpreterException(Error.UNSUPPORTED_OPERATION, "Subtract operation not supported");
}
public ShadowValue multiply(ShadowValue value) throws InterpreterException {
throw new InterpreterException(Error.UNSUPPORTED_OPERATION, "Multiply operation not supported");
}
public ShadowValue divide(ShadowValue value) throws InterpreterException {
throw new InterpreterException(Error.UNSUPPORTED_OPERATION, "Divide operation not supported");
}
public ShadowValue modulus(ShadowValue value) throws InterpreterException {
throw new InterpreterException(Error.UNSUPPORTED_OPERATION, "Modulus operation not supported");
}
public ShadowValue bitShiftLeft(ShadowValue value) throws InterpreterException {
throw new InterpreterException(Error.UNSUPPORTED_OPERATION, "Left shift operation not supported");
}
public ShadowValue bitShiftRight(ShadowValue value) throws InterpreterException {
throw new InterpreterException(Error.UNSUPPORTED_OPERATION, "Right shift operation not supported");
}
public ShadowValue bitRotateLeft(ShadowValue value) throws InterpreterException {
throw new InterpreterException(Error.UNSUPPORTED_OPERATION, "Left rotate operation not supported");
}
public ShadowValue bitRotateRight(ShadowValue value) throws InterpreterException {
throw new InterpreterException(Error.UNSUPPORTED_OPERATION, "Right rotate operation not supported");
}
public ShadowBoolean equal(ShadowValue value) throws InterpreterException {
throw new InterpreterException(Error.UNSUPPORTED_OPERATION, "Equal operation not supported");
}
public final ShadowBoolean notEqual(ShadowValue value) throws InterpreterException {
try {
final ShadowBoolean result = equal(value);
return new ShadowBoolean(!result.getValue());
} catch (Exception e) {
throw new InterpreterException(Error.UNSUPPORTED_OPERATION, "Not equal operation not supported");
}
}
public ShadowBoolean referenceEqual(ShadowValue value) throws InterpreterException {
throw new InterpreterException(Error.UNSUPPORTED_OPERATION, "Reference equal operation not supported");
}
public final ShadowBoolean referenceNotEqual(ShadowValue value) throws InterpreterException {
try {
ShadowBoolean result = this.referenceEqual(value);
return new ShadowBoolean(!result.getValue());
} catch (Exception e) {
throw new InterpreterException(Error.UNSUPPORTED_OPERATION, "Reference not equal operation not supported");
}
}
public ShadowBoolean lessThan(ShadowValue value) throws InterpreterException {
throw new InterpreterException(Error.UNSUPPORTED_OPERATION, "Less than operation not supported");
}
public ShadowBoolean lessThanOrEqual(ShadowValue value)
throws InterpreterException {
throw new InterpreterException(Error.UNSUPPORTED_OPERATION, "Less than or equal operation not supported");
}
public ShadowBoolean greaterThan(ShadowValue value) throws InterpreterException {
throw new InterpreterException(Error.UNSUPPORTED_OPERATION, "Greater than operation not supported");
}
public ShadowBoolean greaterThanOrEqual(ShadowValue value) throws InterpreterException {
throw new InterpreterException(Error.UNSUPPORTED_OPERATION, "Greater than or equal operation not supported");
}
public ShadowBoolean or(ShadowValue value) throws InterpreterException {
throw new InterpreterException(Error.UNSUPPORTED_OPERATION, "Or operation not supported");
}
public ShadowBoolean xor(ShadowValue value) throws InterpreterException {
throw new InterpreterException(Error.UNSUPPORTED_OPERATION, "Exclusive or operation not supported");
}
public ShadowBoolean and(ShadowValue value) throws InterpreterException {
throw new InterpreterException(Error.UNSUPPORTED_OPERATION, "And operation not supported");
}
public ShadowValue bitwiseAnd(ShadowValue value) throws InterpreterException {
throw new InterpreterException(Error.UNSUPPORTED_OPERATION, "Bitwise and operation not supported");
}
public ShadowValue bitwiseOr(ShadowValue value) throws InterpreterException {
throw new InterpreterException(Error.UNSUPPORTED_OPERATION, "Bitwise or operation not supported");
}
public ShadowValue bitwiseXor(ShadowValue value) throws InterpreterException {
throw new InterpreterException(Error.UNSUPPORTED_OPERATION, "Bitwise xor operation not supported");
}
public final boolean isSubtype(ShadowValue other) {
return getType().isSubtype(other.getType());
}
public final boolean isStrictSubtype(ShadowValue other) {
return getType().isStrictSubtype(other.getType());
}
public abstract ShadowValue cast(Type type) throws InterpreterException;
public abstract ShadowValue copy() throws InterpreterException;
/**
* Sets the {@link Modifiers} immutable flag on the value.
* @return a copy of the value, or this if it is already immutable.
* @throws InterpreterException
*/
public ShadowValue freeze() throws InterpreterException {
if (getModifiers().isImmutable())
return this;
// ??? why make a copy here?
// because an immutable value can't be changed
// which would be possible when there are other references to the original
final ShadowValue copy = copy();
copy.getModifiers().addModifier(Modifiers.IMMUTABLE);
return copy;
}
@Override
public String toString() {
return getType().toString(Type.PACKAGES | Type.TYPE_PARAMETERS);
}
/**
* Returns a "default" value for a type if it's supported: array or nullable
* @param type the {@link ModifiedType} to get the default value for.
* @return the default value.
* @throws ShadowException
*/
public static ShadowValue getDefault(ModifiedType type) throws InterpreterException {
if (type.getModifiers().isNullable())
return new ShadowNull(type.getType());
if (type instanceof ArrayType) {
final ArrayType arrayType = (ArrayType) type;
return new ShadowArray(arrayType, 0);
}
throw new InterpreterException(Error.INVALID_TYPE, "Unsupported type " + type.getType());
}
public ShadowInteger hash() throws InterpreterException {
throw new InterpreterException(Error.UNSUPPORTED_OPERATION, "Hash not supported");
}
/**
* Checks to see if two values are equal.
* @param second the other value to compare.
* @return true if they are "equal", or false otherwise.
* @throws ShadowException
*/
public boolean equals(ShadowValue second) throws InterpreterException {
ShadowValue first = this;
if (first.isStrictSubtype(second))
first = first.cast(second.getType());
else if (second.isStrictSubtype(first))
second = second.cast(first.getType());
if( (first instanceof ShadowUndefined) != (second instanceof ShadowUndefined))
return false;
if (first.getType().equals(second.getType())) {
if (first instanceof ShadowInteger) {
BigInteger value1 = ((ShadowInteger) first).getValue();
BigInteger value2 = ((ShadowInteger) second).getValue();
return value1.equals(value2);
}
else if (first instanceof ShadowFloat) {
float value1 = ((ShadowFloat) first).getValue();
float value2 = ((ShadowFloat) second).getValue();
return value1 == value2;
}
else if (first instanceof ShadowDouble) {
double value1 = ((ShadowDouble) first).getValue();
double value2 = ((ShadowDouble) second).getValue();
return value1 == value2;
}
else if (first instanceof ShadowString) {
String value1 = ((ShadowString) first).getValue();
String value2 = ((ShadowString) second).getValue();
return value1.equals(value2);
}
else if ( first instanceof ShadowUndefined )
return second instanceof ShadowUndefined;
else if( first instanceof ShadowNull )
return second instanceof ShadowNull;
}
return false;
}
/**
* Compares one value to another.
* @param second the other value to compare to.
* @return same values as Java's compareTo
* @throws InterpreterException
*/
public int compareTo(ShadowValue second) throws InterpreterException {
ShadowValue first = this;
if (first.isStrictSubtype(second))
first = first.cast(second.getType());
else if (second.isStrictSubtype(first))
second = second.cast(first.getType());
if (first.getType().equals(second.getType())) {
if (first instanceof ShadowInteger) {
BigInteger value1 = ((ShadowInteger) first).getValue();
BigInteger value2 = ((ShadowInteger) second).getValue();
return value1.compareTo(value2);
}
else if (first instanceof ShadowFloat) {
float value1 = ((ShadowFloat) first).getValue();
float value2 = ((ShadowFloat) second).getValue();
return Float.compare(value1, value2);
}
else if (first instanceof ShadowDouble) {
double value1 = ((ShadowDouble) first).getValue();
double value2 = ((ShadowDouble) second).getValue();
return Double.compare(value1, value2);
}
else if (first instanceof ShadowString) {
String value1 = ((ShadowString) first).getValue();
String value2 = ((ShadowString) second).getValue();
return value1.compareTo(value2);
}
}
throw new InterpreterException(Error.MISMATCHED_TYPE, "Cannot compare types " + first.getType() + " and " + second.getType());
}
/** Returns a valid Shadow literal representation of the value */
public abstract String toLiteral();
public ShadowValue callMethod(String method, ShadowValue ... arguments) throws InterpreterException {
if(arguments.length == 0) {
switch(method) {
case "bitwiseComplement": return bitwiseComplement();
case "hash": return hash();
case "negate": return negate();
case "not": return not();
case "toString": return new ShadowString(toLiteral());
}
}
else if(arguments.length == 1) {
ShadowValue value = arguments[0];
switch(method) {
case "add": return add(value);
case "and": return and(value);
case "bitRotateLeft": return bitRotateLeft(value);
case "bitRotateRight": return bitRotateRight(value);
case "bitShiftLeft": return bitShiftLeft(value);
case "bitShiftRight": return bitShiftRight(value);
case "bitwiseAnd": return bitwiseAnd(value);
case "bitwiseOr": return bitwiseOr(value);
case "bitwiseXor": return bitwiseXor(value);
case "compareTo": return new ShadowInteger(compareTo(value));
case "divide": return divide(value);
case "equal": return equal(value);
case "greaterThan": return greaterThan(value);
case "greaterThanOrEqual": return greaterThanOrEqual(value);
case "lessThan": return lessThan(value);
case "lessThanOrEqual": return lessThanOrEqual(value);
case "modulus": return modulus(value);
case "multiply": return multiply(value);
case "notEqual": return notEqual(value);
case "or": return or(value);
case "referenceEqual": return referenceEqual(value);
case "referenceNotEqual": return referenceNotEqual(value);
case "subtract": return subtract(value);
case "xor": return xor(value);
}
}
StringBuilder builder = new StringBuilder("(");
boolean first = true;
for(ShadowValue value : arguments) {
if(first)
first = false;
else
builder.append(", ");
builder.append(value);
}
builder.append(")");
throw new InterpreterException(Error.UNSUPPORTED_OPERATION, "Method " + method + " not supported with arguments " + builder.toString());
}
}
| |
package br.com.bea.androidtools.api.proxy;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.ProtocolVersion;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.json.JSONArray;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import br.com.bea.androidtools.api.android.AbstractEntityHandler;
import br.com.bea.androidtools.api.json.JSONContext;
import br.com.bea.androidtools.api.model.ValueObject;
public class HttpProxy<E extends ValueObject> implements Proxy<E> {
private static final DefaultHttpClient client;
static {
final HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
params.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, HTTP.UTF_8);
params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15000);
params.setParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false);
final SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
final ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
client = new DefaultHttpClient(cm, params);
}
private String encoding = "UTF-8";
private Handler handler;
private final Map<String, String> parameters = new HashMap<String, String>(0);
private String password;
private final Class<E> targetClass;
private URL url;
private String user;
public HttpProxy(final Class<E> targetClass) {
this.targetClass = targetClass;
}
@Override
public Proxy<E> addHandler(final Handler handler) {
this.handler = handler;
return this;
}
@Override
public Proxy<E> addParameter(final String key, final String value) {
this.parameters.put(key, value);
return this;
}
private HttpParams adjustToGet(final Map<String, String> params) {
final HttpParams requestParams = new BasicHttpParams();
for (final String key : params.keySet())
requestParams.setParameter(key, params.get(key));
return requestParams;
}
private List<NameValuePair> adjustToPost(final Map<String, String> params) {
final List<NameValuePair> list = new ArrayList<NameValuePair>(0);
for (final String key : params.keySet())
list.add(new BasicNameValuePair(key, params.get(key)));
return list;
}
@Override
public Proxy<E> authenticateWith(final String user, final String password) {
this.user = user;
this.password = password;
return this;
}
@Override
public Proxy<E> connectTo(final URL url) {
this.url = url;
return this;
}
private HttpRequestBase createRequest(final boolean post) throws ConnectException {
if (null != url) {
if (post) {
final HttpPost method = new HttpPost(url.toString());
final List<NameValuePair> adjustParams = adjustToPost(parameters);
if (!adjustParams.isEmpty()) try {
method.setEntity(new UrlEncodedFormEntity(adjustParams, HTTP.UTF_8));
} catch (final UnsupportedEncodingException e) {
e.printStackTrace();
}
return method;
}
final HttpGet method = new HttpGet(url.toString());
method.setParams(adjustToGet(parameters));
return method;
}
throw new ConnectException("Nao foi possivel criar request !");
}
private ResponseHandler<List<E>> createResponseHandler(final Handler handler) {
return new ResponseHandler<List<E>>() {
@Override
public List<E> handleResponse(final HttpResponse response) {
final HttpEntity httpEntity = response.getEntity();
if (null != httpEntity)
try {
final Message message = handler.obtainMessage();
message.setData(new Bundle());
final StringBuilder builder = read(httpEntity);
if (handler instanceof AbstractEntityHandler) {
final List<E> list = new JSONContext<E>(targetClass).unmarshal(new JSONArray(builder
.toString()));
message.getData().putSerializable(RESPONSE, (Serializable) list);
} else message.getData().putSerializable(RESPONSE, builder.toString());
handler.sendMessage(message);
} catch (final Exception e) {
e.printStackTrace();
}
return Collections.emptyList();
}
};
}
@Override
public List<E> doGet() {
if (null != user && null != password)
client.getCredentialsProvider().setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(user, password));
if (null != handler) {
final ResponseHandler<List<E>> responseHandler = createResponseHandler(handler);
try {
client.execute(createRequest(false), responseHandler);
} catch (final Exception e) {
throwException(responseHandler, e);
}
} else try {
return new JSONContext<E>(targetClass).unmarshal(new JSONArray(read(
client.execute(createRequest(false))
.getEntity()).toString()));
} catch (final Exception e) {
e.printStackTrace();
}
return Collections.emptyList();
}
@Override
public List<E> doPost() {
if (null != user && null != password)
client.getCredentialsProvider().setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(user, password));
final Map<String, String> headers = new HashMap<String, String>(0);
headers.put("Content-Type", "application/x-www-form-urlencoded");
client.addRequestInterceptor(new HttpRequestInterceptor() {
@Override
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
for (final String key : headers.keySet())
if (!request.containsHeader(key)) request.addHeader(key, headers.get(key));
}
});
if (null != handler) {
final ResponseHandler<List<E>> responseHandler = createResponseHandler(handler);
try {
client.execute(createRequest(true), responseHandler);
} catch (final Exception e) {
throwException(responseHandler, e);
}
} else try {
return new JSONContext<E>(targetClass).unmarshal(new JSONArray(read(
client.execute(createRequest(false))
.getEntity()).toString()));
} catch (final Exception e) {
e.printStackTrace();
}
return Collections.emptyList();
}
@Override
public Proxy<E> encoding(final String encoding) {
this.encoding = encoding;
return this;
}
private StringBuilder read(final HttpEntity httpEntity) throws UnsupportedEncodingException, IOException {
final StringBuilder builder = new StringBuilder();
final BufferedReader reader = new BufferedReader(new InputStreamReader(httpEntity.getContent(), encoding));
String line = null;
while ((line = reader.readLine()) != null)
builder.append(line);
return builder;
}
private void throwException(final ResponseHandler<List<E>> responseHandler, final Exception e) {
final BasicHttpResponse errorResponse = new BasicHttpResponse(new ProtocolVersion("HTTP_ERROR", 1, 1),
500,
"ERROR");
errorResponse.setReasonPhrase(e.getMessage());
try {
responseHandler.handleResponse(errorResponse);
} catch (final Exception ex) {
}
}
}
| |
/**
* <copyright>
* </copyright>
*
*/
package org.ioicompanies.lang.iOI.impl;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.impl.EPackageImpl;
import org.ioicompanies.lang.iOI.Company;
import org.ioicompanies.lang.iOI.Department;
import org.ioicompanies.lang.iOI.Employee;
import org.ioicompanies.lang.iOI.IOIFactory;
import org.ioicompanies.lang.iOI.IOIPackage;
import org.ioicompanies.lang.iOI.Manager;
import org.ioicompanies.lang.iOI.Model;
import org.ioicompanies.lang.iOI.Position;
/**
* <!-- begin-user-doc -->
* An implementation of the model <b>Package</b>.
* <!-- end-user-doc -->
* @generated
*/
public class IOIPackageImpl extends EPackageImpl implements IOIPackage
{
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass modelEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass employeeEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass companyEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass departmentEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass positionEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass managerEClass = null;
/**
* Creates an instance of the model <b>Package</b>, registered with
* {@link org.eclipse.emf.ecore.EPackage.Registry EPackage.Registry} by the package
* package URI value.
* <p>Note: the correct way to create the package is via the static
* factory method {@link #init init()}, which also performs
* initialization of the package, or returns the registered package,
* if one already exists.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.eclipse.emf.ecore.EPackage.Registry
* @see org.ioicompanies.lang.iOI.IOIPackage#eNS_URI
* @see #init()
* @generated
*/
private IOIPackageImpl()
{
super(eNS_URI, IOIFactory.eINSTANCE);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static boolean isInited = false;
/**
* Creates, registers, and initializes the <b>Package</b> for this model, and for any others upon which it depends.
*
* <p>This method is used to initialize {@link IOIPackage#eINSTANCE} when that field is accessed.
* Clients should not invoke it directly. Instead, they should simply access that field to obtain the package.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #eNS_URI
* @see #createPackageContents()
* @see #initializePackageContents()
* @generated
*/
public static IOIPackage init()
{
if (isInited) return (IOIPackage)EPackage.Registry.INSTANCE.getEPackage(IOIPackage.eNS_URI);
// Obtain or create and register package
IOIPackageImpl theIOIPackage = (IOIPackageImpl)(EPackage.Registry.INSTANCE.get(eNS_URI) instanceof IOIPackageImpl ? EPackage.Registry.INSTANCE.get(eNS_URI) : new IOIPackageImpl());
isInited = true;
// Create package meta-data objects
theIOIPackage.createPackageContents();
// Initialize created meta-data
theIOIPackage.initializePackageContents();
// Mark meta-data to indicate it can't be changed
theIOIPackage.freeze();
// Update the registry and return the package
EPackage.Registry.INSTANCE.put(IOIPackage.eNS_URI, theIOIPackage);
return theIOIPackage;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getModel()
{
return modelEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getModel_Name()
{
return (EAttribute)modelEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getModel_Companies()
{
return (EReference)modelEClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getEmployee()
{
return employeeEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getEmployee_Name()
{
return (EAttribute)employeeEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getEmployee_Salary()
{
return (EAttribute)employeeEClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getEmployee_Works_on()
{
return (EReference)employeeEClass.getEStructuralFeatures().get(2);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getCompany()
{
return companyEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getCompany_Name()
{
return (EAttribute)companyEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getCompany_Positions()
{
return (EReference)companyEClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getCompany_Departments()
{
return (EReference)companyEClass.getEStructuralFeatures().get(2);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getDepartment()
{
return departmentEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getDepartment_Name()
{
return (EAttribute)departmentEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getDepartment_Manager()
{
return (EReference)departmentEClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getDepartment_Employees()
{
return (EReference)departmentEClass.getEStructuralFeatures().get(2);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getDepartment_Sub_department()
{
return (EReference)departmentEClass.getEStructuralFeatures().get(3);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getPosition()
{
return positionEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getPosition_Name()
{
return (EAttribute)positionEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getManager()
{
return managerEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public IOIFactory getIOIFactory()
{
return (IOIFactory)getEFactoryInstance();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private boolean isCreated = false;
/**
* Creates the meta-model objects for the package. This method is
* guarded to have no affect on any invocation but its first.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void createPackageContents()
{
if (isCreated) return;
isCreated = true;
// Create classes and their features
modelEClass = createEClass(MODEL);
createEAttribute(modelEClass, MODEL__NAME);
createEReference(modelEClass, MODEL__COMPANIES);
employeeEClass = createEClass(EMPLOYEE);
createEAttribute(employeeEClass, EMPLOYEE__NAME);
createEAttribute(employeeEClass, EMPLOYEE__SALARY);
createEReference(employeeEClass, EMPLOYEE__WORKS_ON);
companyEClass = createEClass(COMPANY);
createEAttribute(companyEClass, COMPANY__NAME);
createEReference(companyEClass, COMPANY__POSITIONS);
createEReference(companyEClass, COMPANY__DEPARTMENTS);
departmentEClass = createEClass(DEPARTMENT);
createEAttribute(departmentEClass, DEPARTMENT__NAME);
createEReference(departmentEClass, DEPARTMENT__MANAGER);
createEReference(departmentEClass, DEPARTMENT__EMPLOYEES);
createEReference(departmentEClass, DEPARTMENT__SUB_DEPARTMENT);
positionEClass = createEClass(POSITION);
createEAttribute(positionEClass, POSITION__NAME);
managerEClass = createEClass(MANAGER);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private boolean isInitialized = false;
/**
* Complete the initialization of the package and its meta-model. This
* method is guarded to have no affect on any invocation but its first.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void initializePackageContents()
{
if (isInitialized) return;
isInitialized = true;
// Initialize package
setName(eNAME);
setNsPrefix(eNS_PREFIX);
setNsURI(eNS_URI);
// Create type parameters
// Set bounds for type parameters
// Add supertypes to classes
managerEClass.getESuperTypes().add(this.getEmployee());
// Initialize classes and features; add operations and parameters
initEClass(modelEClass, Model.class, "Model", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEAttribute(getModel_Name(), ecorePackage.getEString(), "name", null, 0, 1, Model.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getModel_Companies(), this.getCompany(), null, "companies", null, 0, -1, Model.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(employeeEClass, Employee.class, "Employee", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEAttribute(getEmployee_Name(), ecorePackage.getEString(), "name", null, 0, 1, Employee.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getEmployee_Salary(), ecorePackage.getEInt(), "salary", null, 0, 1, Employee.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getEmployee_Works_on(), this.getPosition(), null, "works_on", null, 0, 1, Employee.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(companyEClass, Company.class, "Company", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEAttribute(getCompany_Name(), ecorePackage.getEString(), "name", null, 0, 1, Company.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getCompany_Positions(), this.getPosition(), null, "positions", null, 0, -1, Company.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getCompany_Departments(), this.getDepartment(), null, "departments", null, 0, -1, Company.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(departmentEClass, Department.class, "Department", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEAttribute(getDepartment_Name(), ecorePackage.getEString(), "name", null, 0, 1, Department.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getDepartment_Manager(), this.getManager(), null, "manager", null, 0, 1, Department.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getDepartment_Employees(), this.getEmployee(), null, "employees", null, 0, -1, Department.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getDepartment_Sub_department(), this.getDepartment(), null, "sub_department", null, 0, 1, Department.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(positionEClass, Position.class, "Position", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEAttribute(getPosition_Name(), ecorePackage.getEString(), "name", null, 0, 1, Position.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(managerEClass, Manager.class, "Manager", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
// Create resource
createResource(eNS_URI);
}
} //IOIPackageImpl
| |
/*
* WbStoreProfile.java
*
* This file is part of SQL Workbench/J, http://www.sql-workbench.net
*
* Copyright 2002-2015, Thomas Kellerer
*
* 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.
*
* To contact the author please send an email to: support@sql-workbench.net
*
*/
package workbench.sql.wbcommands.console;
import java.sql.SQLException;
import java.util.List;
import workbench.AppArguments;
import workbench.resource.ResourceMgr;
import workbench.db.ConnectionMgr;
import workbench.db.ConnectionProfile;
import workbench.db.DbDriver;
import workbench.sql.DelimiterDefinition;
import workbench.sql.SqlCommand;
import workbench.sql.StatementRunnerResult;
import workbench.sql.wbcommands.ConnectionDescriptor;
import workbench.util.ArgumentParser;
import workbench.util.ArgumentType;
import workbench.util.StringUtil;
/**
*
* @author Thomas Kellerer
*/
public class WbCreateProfile
extends SqlCommand
{
public static final String VERB = "WbCreateProfile";
public static final String ARG_DRV_NAME = "driverName";
public WbCreateProfile()
{
super();
cmdLine = new ArgumentParser();
cmdLine.addArgument(WbStoreProfile.ARG_PROFILE_NAME);
cmdLine.addArgument(WbStoreProfile.ARG_SAVE_PASSWORD, ArgumentType.BoolArgument);
cmdLine.addArgument(AppArguments.ARG_CONN_AUTOCOMMIT);
cmdLine.addArgument(AppArguments.ARG_CONN_DRIVER_CLASS);
cmdLine.addArgument(AppArguments.ARG_CONN_PWD);
cmdLine.addArgument(AppArguments.ARG_CONN_URL);
cmdLine.addArgument(AppArguments.ARG_CONN_USER);
cmdLine.addArgument("user");
cmdLine.addArgument(AppArguments.ARG_CONN_FETCHSIZE);
cmdLine.addArgument(AppArguments.ARG_CONN_EMPTYNULL);
cmdLine.addArgument(AppArguments.ARG_ALT_DELIMITER);
cmdLine.addArgument(AppArguments.ARG_CONN_SEPARATE);
cmdLine.addArgument(AppArguments.ARG_CONN_TRIM_CHAR);
cmdLine.addArgument(AppArguments.ARG_CONN_REMOVE_COMMENTS);
cmdLine.addArgument(AppArguments.ARG_CONN_CHECK_OPEN_TRANS);
cmdLine.addArgument(AppArguments.ARG_READ_ONLY);
cmdLine.addArgument(AppArguments.ARG_CONN_PROPS);
cmdLine.addArgument(AppArguments.ARG_CONN_EMPTYNULL);
cmdLine.addArgument(ARG_DRV_NAME);
cmdLine.addArgument(AppArguments.ARG_PROFILE_GROUP);
cmdLine.addArgument(AppArguments.ARG_CONN_DESCRIPTOR);
}
@Override
protected boolean isConnectionRequired()
{
return false;
}
@Override
public String getVerb()
{
return VERB;
}
@Override
public StatementRunnerResult execute(String sql)
throws SQLException, Exception
{
StatementRunnerResult result = new StatementRunnerResult();
cmdLine.parse(getCommandLine(sql));
String name = cmdLine.getValue(WbStoreProfile.ARG_PROFILE_NAME);
if (StringUtil.isBlank(name))
{
result.addMessage("Profile name required");
result.setFailure();
return result;
}
ConnectionProfile profile = null;
String descriptor = cmdLine.getValue(AppArguments.ARG_CONN_DESCRIPTOR);
if (StringUtil.isNonBlank(descriptor))
{
ConnectionDescriptor parser = new ConnectionDescriptor();
profile = parser.parseDefinition(descriptor);
}
if (profile == null)
{
String url = cmdLine.getValue(AppArguments.ARG_CONN_URL);
String driverclass = cmdLine.getValue(AppArguments.ARG_CONN_DRIVER);
profile = ConnectionProfile.createEmptyProfile();
String user = cmdLine.getValue(AppArguments.ARG_CONN_USER);
if (StringUtil.isBlank(user))
{
user = cmdLine.getValue("user");
}
String pwd = cmdLine.getValue(AppArguments.ARG_CONN_PWD);
profile.setUrl(url);
profile.setUsername(user);
if (StringUtil.isNonBlank(pwd))
{
profile.setPassword(pwd);
profile.setStorePassword(true);
}
else
{
profile.setStorePassword(false);
}
String drvName = cmdLine.getValue(ARG_DRV_NAME);
if (drvName != null)
{
List<DbDriver> drivers = ConnectionMgr.getInstance().getDrivers();
DbDriver drv = null;
for (DbDriver dbDriver : drivers)
{
if (dbDriver.getName().equalsIgnoreCase(drvName))
{
drv = dbDriver;
break;
}
}
if (drv != null)
{
profile.setDriver(drv);
}
}
else if (driverclass != null)
{
DbDriver drv = ConnectionMgr.getInstance().findDriver(driverclass);
if (drv != null)
{
profile.setDriver(drv);
profile.setDriverName(null);
}
}
else
{
driverclass = ConnectionDescriptor.findDriverClassFromUrl(url);
DbDriver drv = ConnectionMgr.getInstance().findDriver(driverclass);
if (drv != null)
{
profile.setDriver(drv);
profile.setDriverName(null);
}
}
}
profile.setTemporaryProfile(false);
boolean commit = cmdLine.getBoolean(AppArguments.ARG_CONN_AUTOCOMMIT, false);
String delimDef = cmdLine.getValue(AppArguments.ARG_ALT_DELIMITER);
DelimiterDefinition delim = DelimiterDefinition.parseCmdLineArgument(delimDef);
boolean trimCharData = cmdLine.getBoolean(AppArguments.ARG_CONN_TRIM_CHAR, false);
boolean rollback = cmdLine.getBoolean(AppArguments.ARG_CONN_ROLLBACK, false);
boolean separate = cmdLine.getBoolean(AppArguments.ARG_CONN_SEPARATE, true);
boolean savePwd = cmdLine.getBoolean(WbStoreProfile.ARG_SAVE_PASSWORD, true);
profile.setStorePassword(savePwd);
profile.setAutocommit(commit);
profile.setStoreExplorerSchema(false);
profile.setRollbackBeforeDisconnect(rollback);
profile.setAlternateDelimiter(delim);
profile.setTrimCharData(trimCharData);
profile.setUseSeparateConnectionPerTab(separate);
profile.setEmptyStringIsNull(cmdLine.getBoolean(AppArguments.ARG_CONN_EMPTYNULL, false));
profile.setRemoveComments(cmdLine.getBoolean(AppArguments.ARG_CONN_REMOVE_COMMENTS, false));
profile.setDetectOpenTransaction(cmdLine.getBoolean(AppArguments.ARG_CONN_CHECK_OPEN_TRANS, false));
profile.setReadOnly(cmdLine.getBoolean(AppArguments.ARG_READ_ONLY, false));
int fetchSize = cmdLine.getIntValue(AppArguments.ARG_CONN_FETCHSIZE, -1);
profile.setDefaultFetchSize(fetchSize);
profile.setName(name);
String group = cmdLine.getValue(AppArguments.ARG_PROFILE_GROUP);
if (group != null)
{
profile.setGroup(group);
}
ConnectionMgr.getInstance().addProfile(profile);
ConnectionMgr.getInstance().saveProfiles();
result.addMessage(ResourceMgr.getFormattedString("MsgProfileAdded", profile.getKey().toString()));
return result;
}
@Override
public boolean isWbCommand()
{
return true;
}
}
| |
/*
* 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.cloud.scheduler.v1;
import static com.google.cloud.scheduler.v1.CloudSchedulerClient.ListJobsPagedResponse;
import com.google.api.gax.core.NoCredentialsProvider;
import com.google.api.gax.grpc.GaxGrpcProperties;
import com.google.api.gax.grpc.testing.LocalChannelProvider;
import com.google.api.gax.grpc.testing.MockGrpcService;
import com.google.api.gax.grpc.testing.MockServiceHelper;
import com.google.api.gax.rpc.ApiClientHeaderProvider;
import com.google.api.gax.rpc.InvalidArgumentException;
import com.google.common.collect.Lists;
import com.google.protobuf.Empty;
import com.google.protobuf.FieldMask;
import com.google.protobuf.GeneratedMessageV3;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
@javax.annotation.Generated("by GAPIC")
public class CloudSchedulerClientTest {
private static MockCloudScheduler mockCloudScheduler;
private static MockServiceHelper serviceHelper;
private CloudSchedulerClient client;
private LocalChannelProvider channelProvider;
@BeforeClass
public static void startStaticServer() {
mockCloudScheduler = new MockCloudScheduler();
serviceHelper =
new MockServiceHelper("in-process-1", Arrays.<MockGrpcService>asList(mockCloudScheduler));
serviceHelper.start();
}
@AfterClass
public static void stopServer() {
serviceHelper.stop();
}
@Before
public void setUp() throws IOException {
serviceHelper.reset();
channelProvider = serviceHelper.createChannelProvider();
CloudSchedulerSettings settings =
CloudSchedulerSettings.newBuilder()
.setTransportChannelProvider(channelProvider)
.setCredentialsProvider(NoCredentialsProvider.create())
.build();
client = CloudSchedulerClient.create(settings);
}
@After
public void tearDown() throws Exception {
client.close();
}
@Test
@SuppressWarnings("all")
public void listJobsTest() {
String nextPageToken = "";
Job jobsElement = Job.newBuilder().build();
List<Job> jobs = Arrays.asList(jobsElement);
ListJobsResponse expectedResponse =
ListJobsResponse.newBuilder().setNextPageToken(nextPageToken).addAllJobs(jobs).build();
mockCloudScheduler.addResponse(expectedResponse);
LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
ListJobsPagedResponse pagedListResponse = client.listJobs(parent);
List<Job> resources = Lists.newArrayList(pagedListResponse.iterateAll());
Assert.assertEquals(1, resources.size());
Assert.assertEquals(expectedResponse.getJobsList().get(0), resources.get(0));
List<GeneratedMessageV3> actualRequests = mockCloudScheduler.getRequests();
Assert.assertEquals(1, actualRequests.size());
ListJobsRequest actualRequest = (ListJobsRequest) actualRequests.get(0);
Assert.assertEquals(parent, LocationName.parse(actualRequest.getParent()));
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
@SuppressWarnings("all")
public void listJobsExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockCloudScheduler.addException(exception);
try {
LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
client.listJobs(parent);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
@Test
@SuppressWarnings("all")
public void getJobTest() {
JobName name2 = JobName.of("[PROJECT]", "[LOCATION]", "[JOB]");
String description = "description-1724546052";
String schedule = "schedule-697920873";
String timeZone = "timeZone36848094";
Job expectedResponse =
Job.newBuilder()
.setName(name2.toString())
.setDescription(description)
.setSchedule(schedule)
.setTimeZone(timeZone)
.build();
mockCloudScheduler.addResponse(expectedResponse);
JobName name = JobName.of("[PROJECT]", "[LOCATION]", "[JOB]");
Job actualResponse = client.getJob(name);
Assert.assertEquals(expectedResponse, actualResponse);
List<GeneratedMessageV3> actualRequests = mockCloudScheduler.getRequests();
Assert.assertEquals(1, actualRequests.size());
GetJobRequest actualRequest = (GetJobRequest) actualRequests.get(0);
Assert.assertEquals(name, JobName.parse(actualRequest.getName()));
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
@SuppressWarnings("all")
public void getJobExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockCloudScheduler.addException(exception);
try {
JobName name = JobName.of("[PROJECT]", "[LOCATION]", "[JOB]");
client.getJob(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
@Test
@SuppressWarnings("all")
public void createJobTest() {
JobName name = JobName.of("[PROJECT]", "[LOCATION]", "[JOB]");
String description = "description-1724546052";
String schedule = "schedule-697920873";
String timeZone = "timeZone36848094";
Job expectedResponse =
Job.newBuilder()
.setName(name.toString())
.setDescription(description)
.setSchedule(schedule)
.setTimeZone(timeZone)
.build();
mockCloudScheduler.addResponse(expectedResponse);
LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
Job job = Job.newBuilder().build();
Job actualResponse = client.createJob(parent, job);
Assert.assertEquals(expectedResponse, actualResponse);
List<GeneratedMessageV3> actualRequests = mockCloudScheduler.getRequests();
Assert.assertEquals(1, actualRequests.size());
CreateJobRequest actualRequest = (CreateJobRequest) actualRequests.get(0);
Assert.assertEquals(parent, LocationName.parse(actualRequest.getParent()));
Assert.assertEquals(job, actualRequest.getJob());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
@SuppressWarnings("all")
public void createJobExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockCloudScheduler.addException(exception);
try {
LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
Job job = Job.newBuilder().build();
client.createJob(parent, job);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
@Test
@SuppressWarnings("all")
public void updateJobTest() {
JobName name = JobName.of("[PROJECT]", "[LOCATION]", "[JOB]");
String description = "description-1724546052";
String schedule = "schedule-697920873";
String timeZone = "timeZone36848094";
Job expectedResponse =
Job.newBuilder()
.setName(name.toString())
.setDescription(description)
.setSchedule(schedule)
.setTimeZone(timeZone)
.build();
mockCloudScheduler.addResponse(expectedResponse);
Job job = Job.newBuilder().build();
FieldMask updateMask = FieldMask.newBuilder().build();
Job actualResponse = client.updateJob(job, updateMask);
Assert.assertEquals(expectedResponse, actualResponse);
List<GeneratedMessageV3> actualRequests = mockCloudScheduler.getRequests();
Assert.assertEquals(1, actualRequests.size());
UpdateJobRequest actualRequest = (UpdateJobRequest) actualRequests.get(0);
Assert.assertEquals(job, actualRequest.getJob());
Assert.assertEquals(updateMask, actualRequest.getUpdateMask());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
@SuppressWarnings("all")
public void updateJobExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockCloudScheduler.addException(exception);
try {
Job job = Job.newBuilder().build();
FieldMask updateMask = FieldMask.newBuilder().build();
client.updateJob(job, updateMask);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
@Test
@SuppressWarnings("all")
public void deleteJobTest() {
Empty expectedResponse = Empty.newBuilder().build();
mockCloudScheduler.addResponse(expectedResponse);
JobName name = JobName.of("[PROJECT]", "[LOCATION]", "[JOB]");
client.deleteJob(name);
List<GeneratedMessageV3> actualRequests = mockCloudScheduler.getRequests();
Assert.assertEquals(1, actualRequests.size());
DeleteJobRequest actualRequest = (DeleteJobRequest) actualRequests.get(0);
Assert.assertEquals(name, JobName.parse(actualRequest.getName()));
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
@SuppressWarnings("all")
public void deleteJobExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockCloudScheduler.addException(exception);
try {
JobName name = JobName.of("[PROJECT]", "[LOCATION]", "[JOB]");
client.deleteJob(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
@Test
@SuppressWarnings("all")
public void pauseJobTest() {
JobName name2 = JobName.of("[PROJECT]", "[LOCATION]", "[JOB]");
String description = "description-1724546052";
String schedule = "schedule-697920873";
String timeZone = "timeZone36848094";
Job expectedResponse =
Job.newBuilder()
.setName(name2.toString())
.setDescription(description)
.setSchedule(schedule)
.setTimeZone(timeZone)
.build();
mockCloudScheduler.addResponse(expectedResponse);
JobName name = JobName.of("[PROJECT]", "[LOCATION]", "[JOB]");
Job actualResponse = client.pauseJob(name);
Assert.assertEquals(expectedResponse, actualResponse);
List<GeneratedMessageV3> actualRequests = mockCloudScheduler.getRequests();
Assert.assertEquals(1, actualRequests.size());
PauseJobRequest actualRequest = (PauseJobRequest) actualRequests.get(0);
Assert.assertEquals(name, JobName.parse(actualRequest.getName()));
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
@SuppressWarnings("all")
public void pauseJobExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockCloudScheduler.addException(exception);
try {
JobName name = JobName.of("[PROJECT]", "[LOCATION]", "[JOB]");
client.pauseJob(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
@Test
@SuppressWarnings("all")
public void resumeJobTest() {
JobName name2 = JobName.of("[PROJECT]", "[LOCATION]", "[JOB]");
String description = "description-1724546052";
String schedule = "schedule-697920873";
String timeZone = "timeZone36848094";
Job expectedResponse =
Job.newBuilder()
.setName(name2.toString())
.setDescription(description)
.setSchedule(schedule)
.setTimeZone(timeZone)
.build();
mockCloudScheduler.addResponse(expectedResponse);
JobName name = JobName.of("[PROJECT]", "[LOCATION]", "[JOB]");
Job actualResponse = client.resumeJob(name);
Assert.assertEquals(expectedResponse, actualResponse);
List<GeneratedMessageV3> actualRequests = mockCloudScheduler.getRequests();
Assert.assertEquals(1, actualRequests.size());
ResumeJobRequest actualRequest = (ResumeJobRequest) actualRequests.get(0);
Assert.assertEquals(name, JobName.parse(actualRequest.getName()));
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
@SuppressWarnings("all")
public void resumeJobExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockCloudScheduler.addException(exception);
try {
JobName name = JobName.of("[PROJECT]", "[LOCATION]", "[JOB]");
client.resumeJob(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
@Test
@SuppressWarnings("all")
public void runJobTest() {
JobName name2 = JobName.of("[PROJECT]", "[LOCATION]", "[JOB]");
String description = "description-1724546052";
String schedule = "schedule-697920873";
String timeZone = "timeZone36848094";
Job expectedResponse =
Job.newBuilder()
.setName(name2.toString())
.setDescription(description)
.setSchedule(schedule)
.setTimeZone(timeZone)
.build();
mockCloudScheduler.addResponse(expectedResponse);
JobName name = JobName.of("[PROJECT]", "[LOCATION]", "[JOB]");
Job actualResponse = client.runJob(name);
Assert.assertEquals(expectedResponse, actualResponse);
List<GeneratedMessageV3> actualRequests = mockCloudScheduler.getRequests();
Assert.assertEquals(1, actualRequests.size());
RunJobRequest actualRequest = (RunJobRequest) actualRequests.get(0);
Assert.assertEquals(name, JobName.parse(actualRequest.getName()));
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
@SuppressWarnings("all")
public void runJobExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockCloudScheduler.addException(exception);
try {
JobName name = JobName.of("[PROJECT]", "[LOCATION]", "[JOB]");
client.runJob(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
}
| |
/*
* Copyright 2018 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 io.quarkus.container.spi;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.common.base.Strings;
/**
* This is basically a simplified version of {@code com.google.cloud.tools.jib.api.ImageReference}
*/
public class ImageReference {
private static final String DOCKER_HUB_REGISTRY = "registry-1.docker.io";
private static final String DEFAULT_TAG = "latest";
private static final String LIBRARY_REPOSITORY_PREFIX = "library/";
/**
* Matches all sequences of alphanumeric characters possibly separated by any number of dashes in
* the middle.
*/
private static final String REGISTRY_COMPONENT_REGEX = "(?:[a-zA-Z\\d]|(?:[a-zA-Z\\d][a-zA-Z\\d-]*[a-zA-Z\\d]))";
/**
* Matches sequences of {@code REGISTRY_COMPONENT_REGEX} separated by a dot, with an optional
* {@code :port} at the end.
*/
private static final String REGISTRY_REGEX = String.format("%s(?:\\.%s)*(?::\\d+)?", REGISTRY_COMPONENT_REGEX,
REGISTRY_COMPONENT_REGEX);
/**
* Matches all sequences of alphanumeric characters separated by a separator.
*
* <p>
* A separator is either an underscore, a dot, two underscores, or any number of dashes.
*/
private static final String REPOSITORY_COMPONENT_REGEX = "[a-z\\d]+(?:(?:[_.]|__|-+)[a-z\\d]+)*";
/** Matches all repetitions of {@code REPOSITORY_COMPONENT_REGEX} separated by a backslash. */
private static final String REPOSITORY_REGEX = String.format("(?:%s/)*%s", REPOSITORY_COMPONENT_REGEX,
REPOSITORY_COMPONENT_REGEX);
/** Matches a tag of max length 128. */
private static final String TAG_REGEX = "[\\w][\\w.-]{0,127}";
/** Pattern matches a SHA-256 hash - 32 bytes in lowercase hexadecimal. */
private static final String HASH_REGEX = String.format("[a-f0-9]{%d}", 64);
/** The algorithm prefix for the digest string. */
private static final String DIGEST_PREFIX = "sha256:";
/** Pattern matches a SHA-256 digest - a SHA-256 hash prefixed with "sha256:". */
private static final String DIGEST_REGEX = DIGEST_PREFIX + HASH_REGEX;
/**
* Matches a full image reference, which is the registry, repository, and tag/digest separated by
* backslashes. The repository is required, but the registry and tag/digest are optional.
*/
private static final String REFERENCE_REGEX = String.format(
"^(?:(%s)/)?(%s)(?::(%s))?(?:@(%s))?$",
REGISTRY_REGEX, REPOSITORY_REGEX, TAG_REGEX, DIGEST_REGEX);
private static final Pattern REFERENCE_PATTERN = Pattern.compile(REFERENCE_REGEX);
private final String registry;
private final String repository;
private final String tag;
private final String digest;
/**
* Returns {@code true} if {@code registry} is a valid registry string. For example, a valid
* registry could be {@code gcr.io} or {@code localhost:5000}.
*
* @param registry the registry to check
* @return {@code true} if is a valid registry; {@code false} otherwise
*/
public static boolean isValidRegistry(String registry) {
return registry.matches(REGISTRY_REGEX);
}
/**
* Returns {@code true} if {@code repository} is a valid repository string. For example, a valid
* repository could be {@code distroless} or {@code my/container-image/repository}.
*
* @param repository the repository to check
* @return {@code true} if is a valid repository; {@code false} otherwise
*/
public static boolean isValidRepository(String repository) {
return repository.matches(REPOSITORY_REGEX);
}
/**
* Returns {@code true} if {@code tag} is a valid tag string. For example, a valid tag could be
* {@code v120.5-release}.
*
* @param tag the tag to check
* @return {@code true} if is a valid tag; {@code false} otherwise
*/
public static boolean isValidTag(String tag) {
return tag.matches(TAG_REGEX);
}
/**
* Parses a string {@code reference} into an {@link ImageReference}.
*
* <p>
* Image references should generally be in the form: {@code <registry>/<repository>:<tag>} For
* example, an image reference could be {@code gcr.io/distroless/java:debug}.
*
* <p>
* See <a
* href=
* "https://docs.docker.com/engine/reference/commandline/tag/#extended-description">https://docs.docker.com/engine/reference/commandline/tag/#extended-description</a>
* for a description of valid image reference format. Note, however, that the image reference is
* referred confusingly as {@code tag} on that page.
*
* @param reference the string to parse
* @return an {@link ImageReference} parsed from the string
* @throws IllegalArgumentException if {@code reference} is formatted incorrectly
*/
public static ImageReference parse(String reference) {
Matcher matcher = REFERENCE_PATTERN.matcher(reference);
if (!matcher.find() || matcher.groupCount() < 4) {
throw new IllegalArgumentException("Reference " + reference + " is invalid");
}
String registry = matcher.group(1);
String repository = matcher.group(2);
String tag = matcher.group(3);
String digest = matcher.group(4);
// If no registry was matched, use Docker Hub by default.
if (Strings.isNullOrEmpty(registry)) {
registry = DOCKER_HUB_REGISTRY;
}
if (Strings.isNullOrEmpty(repository)) {
throw new IllegalArgumentException("Reference " + reference + " is invalid: The repository was not set");
}
/*
* If a registry was matched but it does not contain any dots or colons, it should actually be
* part of the repository unless it is "localhost".
*
* See https://github.com/docker/distribution/blob/245ca4659e09e9745f3cc1217bf56e946509220c/reference/normalize.go#L62
*/
if (!registry.contains(".") && !registry.contains(":") && !"localhost".equals(registry)) {
repository = registry + "/" + repository;
registry = DOCKER_HUB_REGISTRY;
}
/*
* For Docker Hub, if the repository is only one component, then it should be prefixed with
* 'library/'.
*
* See https://docs.docker.com/engine/reference/commandline/pull/#pull-an-image-from-docker-hub
*/
if (DOCKER_HUB_REGISTRY.equals(registry) && repository.indexOf('/') < 0) {
repository = LIBRARY_REPOSITORY_PREFIX + repository;
}
if (Strings.isNullOrEmpty(tag) && Strings.isNullOrEmpty(digest)) {
tag = DEFAULT_TAG;
}
if (Strings.isNullOrEmpty(tag)) {
tag = null;
}
if (Strings.isNullOrEmpty(digest)) {
digest = null;
}
return new ImageReference(registry, repository, tag, digest);
}
private ImageReference(
String registry, String repository, String tag, String digest) {
this.registry = registry;
this.repository = repository;
this.tag = tag;
this.digest = digest;
}
public String getRegistry() {
return registry;
}
public String getRepository() {
return repository;
}
public String getTag() {
return tag;
}
public String getDigest() {
return digest;
}
}
| |
/**
* 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.zookeeper.server.quorum;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.BindException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import org.apache.jute.BinaryOutputArchive;
import org.apache.log4j.Logger;
import org.apache.zookeeper.server.FinalRequestProcessor;
import org.apache.zookeeper.server.Request;
import org.apache.zookeeper.server.RequestProcessor;
import org.apache.zookeeper.server.quorum.QuorumPeer.LearnerType;
/**
* This class has the control logic for the Leader.
*/
public class Leader {
private static final Logger LOG = Logger.getLogger(Leader.class);
static final private boolean nodelay = System.getProperty("leader.nodelay", "true").equals("true");
static {
LOG.info("TCP NoDelay set to: " + nodelay);
}
static public class Proposal {
public QuorumPacket packet;
public HashSet<Long> ackSet = new HashSet<Long>();
public Request request;
@Override
public String toString() {
return packet.getType() + ", " + packet.getZxid() + ", " + request;
}
}
final LeaderZooKeeperServer zk;
final QuorumPeer self;
// the follower acceptor thread
LearnerCnxAcceptor cnxAcceptor;
// list of all the followers
public final HashSet<LearnerHandler> learners =
new HashSet<LearnerHandler>();
// list of followers that are ready to follow (i.e synced with the leader)
public final HashSet<LearnerHandler> forwardingFollowers =
new HashSet<LearnerHandler>();
protected final HashSet<LearnerHandler> observingLearners =
new HashSet<LearnerHandler>();
//Pending sync requests
public final HashMap<Long,List<LearnerSyncRequest>> pendingSyncs =
new HashMap<Long,List<LearnerSyncRequest>>();
//Follower counter
final AtomicLong followerCounter = new AtomicLong(-1);
/**
* Adds peer to the leader.
*
* @param learner
* instance of learner handle
*/
void addLearnerHandler(LearnerHandler learner) {
synchronized (learners) {
learners.add(learner);
}
}
/**
* Remove the learner from the learner list
*
* @param peer
*/
void removeLearnerHandler(LearnerHandler peer) {
synchronized (forwardingFollowers) {
forwardingFollowers.remove(peer);
}
synchronized (learners) {
learners.remove(peer);
}
}
boolean isLearnerSynced(LearnerHandler peer){
synchronized (forwardingFollowers) {
return forwardingFollowers.contains(peer);
}
}
ServerSocket ss;
Leader(QuorumPeer self,LeaderZooKeeperServer zk) throws IOException {
System.out.println("130:Leader");
this.self = self;
try {
ss = new ServerSocket();
ss.setReuseAddress(true);
ss.bind(new InetSocketAddress(self.getQuorumAddress().getPort()));
} catch (BindException e) {
LOG.error("Couldn't bind to port "
+ self.getQuorumAddress().getPort(), e);
throw e;
}
this.zk=zk;
}
/**
* This message is for follower to expect diff
*/
final static int DIFF = 13;
/**
* This is for follower to truncate its logs
*/
final static int TRUNC = 14;
/**
* This is for follower to download the snapshots
*/
final static int SNAP = 15;
/**
* This tells the leader that the connecting peer is actually an observer
*/
final static int OBSERVERINFO = 16;
/**
* This message type is sent by the leader to indicate it's zxid and if
* needed, its database.
*/
final static int NEWLEADER = 10;
/**
* This message type is sent by a follower to pass the last zxid. This is here
* for backward compatibility purposes.
*/
final static int FOLLOWERINFO = 11;
/**
* This message type is sent by the leader to indicate that the follower is
* now uptodate andt can start responding to clients.
*/
final static int UPTODATE = 12;
/**
* This message type is sent to a leader to request and mutation operation.
* The payload will consist of a request header followed by a request.
*/
final static int REQUEST = 1;
/**
* This message type is sent by a leader to propose a mutation.
*/
public final static int PROPOSAL = 2;
/**
* This message type is sent by a follower after it has synced a proposal.
*/
final static int ACK = 3;
/**
* This message type is sent by a leader to commit a proposal and cause
* followers to start serving the corresponding data.
*/
final static int COMMIT = 4;
/**
* This message type is enchanged between follower and leader (initiated by
* follower) to determine liveliness.
*/
final static int PING = 5;
/**
* This message type is to validate a session that should be active.
*/
final static int REVALIDATE = 6;
/**
* This message is a reply to a synchronize command flushing the pipe
* between the leader and the follower.
*/
final static int SYNC = 7;
/**
* This message type informs observers of a committed proposal.
*/
final static int INFORM = 8;
private ConcurrentMap<Long, Proposal> outstandingProposals = new ConcurrentHashMap<Long, Proposal>();
ConcurrentLinkedQueue<Proposal> toBeApplied = new ConcurrentLinkedQueue<Proposal>();
Proposal newLeaderProposal = new Proposal();
class LearnerCnxAcceptor extends Thread{
private volatile boolean stop = false;
@Override
public void run() {
try {
while (!stop) {
try{
Socket s = ss.accept();
s.setSoTimeout(self.tickTime * self.syncLimit);
s.setTcpNoDelay(nodelay);
LearnerHandler fh = new LearnerHandler(s, Leader.this);
fh.start();
} catch (SocketException e) {
if (stop) {
LOG.info("exception while shutting down acceptor: "
+ e);
// When Leader.shutdown() calls ss.close(),
// the call to accept throws an exception.
// We catch and set stop to true.
stop = true;
} else {
throw e;
}
}
}
} catch (Exception e) {
LOG.warn("Exception while accepting follower", e);
}
}
public void halt() {
stop = true;
}
}
/**
* This method is main function that is called to lead
*
* @throws IOException
* @throws InterruptedException
*/
void lead() throws IOException, InterruptedException {
zk.registerJMX(new LeaderBean(this, zk), self.jmxLocalPeerBean);
try {
self.tick = 0;
zk.loadData();
long epoch = self.getLastLoggedZxid() >> 32L;
epoch++;
zk.setZxid(epoch << 32L);
synchronized(this){
lastProposed = zk.getZxid();
}
newLeaderProposal.packet = new QuorumPacket(NEWLEADER, zk.getZxid(),
null, null);
if ((newLeaderProposal.packet.getZxid() & 0xffffffffL) != 0) {
LOG.info("NEWLEADER proposal has Zxid of "
+ Long.toHexString(newLeaderProposal.packet.getZxid()));
}
outstandingProposals.put(newLeaderProposal.packet.getZxid(), newLeaderProposal);
// Start thread that waits for connection requests from
// new followers.
cnxAcceptor = new LearnerCnxAcceptor();
cnxAcceptor.start();
// We have to get at least a majority of servers in sync with
// us. We do this by waiting for the NEWLEADER packet to get
// acknowledged
newLeaderProposal.ackSet.add(self.getId());
while (!self.getQuorumVerifier().containsQuorum(newLeaderProposal.ackSet)){
//while (newLeaderProposal.ackCount <= self.quorumPeers.size() / 2) {
if (self.tick > self.initLimit) {
// Followers aren't syncing fast enough,
// renounce leadership!
StringBuilder ackToString = new StringBuilder();
for(Long id : newLeaderProposal.ackSet)
ackToString.append(id + ": ");
shutdown("Waiting for a quorum of followers, only synced with: " + ackToString);
HashSet<Long> followerSet = new HashSet<Long>();
for(LearnerHandler f : learners)
followerSet.add(f.getSid());
if (self.getQuorumVerifier().containsQuorum(followerSet)) {
//if (followers.size() >= self.quorumPeers.size() / 2) {
LOG.warn("Enough followers present. "+
"Perhaps the initTicks need to be increased.");
}
return;
}
Thread.sleep(self.tickTime);
self.tick++;
}
/**
* WARNING: do not use this for anything other than QA testing
* on a real cluster. Specifically to enable verification that quorum
* can handle the lower 32bit roll-over issue identified in
* ZOOKEEPER-1277. Without this option it would take a very long
* time (on order of a month say) to see the 4 billion writes
* necessary to cause the roll-over to occur.
*
* This field allows you to override the zxid of the server. Typically
* you'll want to set it to something like 0xfffffff0 and then
* start the quorum, run some operations and see the re-election.
*/
String initialZxid = System.getProperty("zookeeper.testingonly.initialZxid");
if (initialZxid != null) {
long zxid = Long.parseLong(initialZxid);
zk.setZxid((zk.getZxid() & 0xffffffff00000000L) | zxid);
}
if (!System.getProperty("zookeeper.leaderServes", "yes").equals("no")) {
self.cnxnFactory.setZooKeeperServer(zk);
}
// Everything is a go, simply start counting the ticks
// WARNING: I couldn't find any wait statement on a synchronized
// block that would be notified by this notifyAll() call, so
// I commented it out
//synchronized (this) {
// notifyAll();
//}
// We ping twice a tick, so we only update the tick every other
// iteration
boolean tickSkip = true;
while (true) {
Thread.sleep(self.tickTime / 2);
if (!tickSkip) {
self.tick++;
}
int syncedCount = 0;
HashSet<Long> syncedSet = new HashSet<Long>();
// lock on the followers when we use it.
syncedSet.add(self.getId());
synchronized (learners) {
for (LearnerHandler f : learners) {
if (f.synced()) {
syncedCount++;
syncedSet.add(f.getSid());
}
f.ping();
}
}
if (!tickSkip && !self.getQuorumVerifier().containsQuorum(syncedSet)) {
//if (!tickSkip && syncedCount < self.quorumPeers.size() / 2) {
// Lost quorum, shutdown
// TODO: message is wrong unless majority quorums used
shutdown("Only " + syncedCount + " followers, need "
+ (self.getVotingView().size() / 2));
// make sure the order is the same!
// the leader goes to looking
return;
}
tickSkip = !tickSkip;
}
} finally {
zk.unregisterJMX(this);
}
}
boolean isShutdown;
/**
* Close down all the LearnerHandlers
*/
void shutdown(String reason) {
if (isShutdown) {
return;
}
LOG.info("Shutdown called",
new Exception("shutdown Leader! reason: " + reason));
if (cnxAcceptor != null) {
cnxAcceptor.halt();
}
// NIO should not accept conenctions
self.cnxnFactory.setZooKeeperServer(null);
try {
ss.close();
} catch (IOException e) {
LOG.warn("Ignoring unexpected exception during close",e);
}
// clear all the connections
self.cnxnFactory.clear();
// shutdown the previous zk
if (zk != null) {
zk.shutdown();
}
synchronized (learners) {
for (Iterator<LearnerHandler> it = learners.iterator(); it
.hasNext();) {
LearnerHandler f = it.next();
it.remove();
f.shutdown();
}
}
isShutdown = true;
}
/**
* Keep a count of acks that are received by the leader for a particular
* proposal
*
* @param zxid
* the zxid of the proposal sent out
* @param followerAddr
*/
synchronized public void processAck(long sid, long zxid, SocketAddress followerAddr) {
boolean first = true;
if (LOG.isTraceEnabled()) {
LOG.trace("Ack zxid: 0x" + Long.toHexString(zxid));
for (Proposal p : outstandingProposals.values()) {
long packetZxid = p.packet.getZxid();
LOG.trace("outstanding proposal: 0x"
+ Long.toHexString(packetZxid));
}
LOG.trace("outstanding proposals all");
}
if (outstandingProposals.size() == 0) {
if (LOG.isDebugEnabled()) {
LOG.debug("outstanding is 0");
}
return;
}
if (lastCommitted >= zxid) {
if (LOG.isDebugEnabled()) {
LOG.debug("proposal has already been committed, pzxid:"
+ lastCommitted
+ " zxid: 0x" + Long.toHexString(zxid));
}
// The proposal has already been committed
return;
}
Proposal p = outstandingProposals.get(zxid);
if (p == null) {
LOG.warn("Trying to commit future proposal: zxid 0x"
+ Long.toHexString(zxid) + " from " + followerAddr);
return;
}
p.ackSet.add(sid);
if (LOG.isDebugEnabled()) {
LOG.debug("Count for zxid: 0x" + Long.toHexString(zxid)
+ " is " + p.ackSet.size());
}
if (self.getQuorumVerifier().containsQuorum(p.ackSet)){
if (zxid != lastCommitted+1) {
LOG.warn("Commiting zxid 0x" + Long.toHexString(zxid)
+ " from " + followerAddr + " not first!");
LOG.warn("First is "
+ (lastCommitted+1));
}
outstandingProposals.remove(zxid);
if (p.request != null) {
toBeApplied.add(p);
}
// We don't commit the new leader proposal
if ((zxid & 0xffffffffL) != 0) {
if (p.request == null) {
LOG.warn("Going to commmit null: " + p);
}
commit(zxid);
inform(p);
zk.commitProcessor.commit(p.request);
if(pendingSyncs.containsKey(zxid)){
for(LearnerSyncRequest r: pendingSyncs.remove(zxid)) {
sendSync(r);
}
}
return;
} else {
lastCommitted = zxid;
if(LOG.isInfoEnabled()){
LOG.info("Have quorum of supporters; starting up and setting last processed zxid: " + zk.getZxid());
}
zk.startup();
zk.getZKDatabase().setlastProcessedZxid(zk.getZxid());
}
}
}
static class ToBeAppliedRequestProcessor implements RequestProcessor {
private RequestProcessor next;
private ConcurrentLinkedQueue<Proposal> toBeApplied;
/**
* This request processor simply maintains the toBeApplied list. For
* this to work next must be a FinalRequestProcessor and
* FinalRequestProcessor.processRequest MUST process the request
* synchronously!
*
* @param next
* a reference to the FinalRequestProcessor
*/
ToBeAppliedRequestProcessor(RequestProcessor next,
ConcurrentLinkedQueue<Proposal> toBeApplied) {
if (!(next instanceof FinalRequestProcessor)) {
throw new RuntimeException(ToBeAppliedRequestProcessor.class
.getName()
+ " must be connected to "
+ FinalRequestProcessor.class.getName()
+ " not "
+ next.getClass().getName());
}
this.toBeApplied = toBeApplied;
this.next = next;
}
/*
* (non-Javadoc)
*
* @see org.apache.zookeeper.server.RequestProcessor#processRequest(org.apache.zookeeper.server.Request)
*/
public void processRequest(Request request) throws RequestProcessorException {
// request.addRQRec(">tobe");
next.processRequest(request);
Proposal p = toBeApplied.peek();
if (p != null && p.request != null
&& p.request.zxid == request.zxid) {
toBeApplied.remove();
}
}
/*
* (non-Javadoc)
*
* @see org.apache.zookeeper.server.RequestProcessor#shutdown()
*/
public void shutdown() {
next.shutdown();
}
}
/**
* send a packet to all the followers ready to follow
*
* @param qp
* the packet to be sent
*/
void sendPacket(QuorumPacket qp) {
synchronized (forwardingFollowers) {
for (LearnerHandler f : forwardingFollowers) {
f.queuePacket(qp);
}
}
}
/**
* send a packet to all observers
*/
void sendObserverPacket(QuorumPacket qp) {
synchronized(observingLearners) {
for (LearnerHandler f : observingLearners) {
f.queuePacket(qp);
}
}
}
long lastCommitted = -1;
/**
* Create a commit packet and send it to all the members of the quorum
*
* @param zxid
*/
public void commit(long zxid) {
synchronized(this){
lastCommitted = zxid;
}
QuorumPacket qp = new QuorumPacket(Leader.COMMIT, zxid, null, null);
sendPacket(qp);
}
/**
* Create an inform packet and send it to all observers.
* @param zxid
* @param proposal
*/
public void inform(Proposal proposal) {
QuorumPacket qp = new QuorumPacket(Leader.INFORM, proposal.request.zxid,
proposal.packet.getData(), null);
sendObserverPacket(qp);
}
long lastProposed;
/**
* Returns the current epoch of the leader.
*
* @return
*/
public long getEpoch(){
return lastProposed >> 32L;
}
@SuppressWarnings("serial")
public static class XidRolloverException extends Exception {
public XidRolloverException(String message) {
super(message);
}
}
/**
* create a proposal and send it out to all the members
*
* @param request
* @return the proposal that is queued to send to all the members
*/
public Proposal propose(Request request) throws XidRolloverException {
/**
* Address the rollover issue. All lower 32bits set indicate a new leader
* election. Force a re-election instead. See ZOOKEEPER-1277
*/
if ((request.zxid & 0xffffffffL) == 0xffffffffL) {
String msg =
"zxid lower 32 bits have rolled over, forcing re-election, and therefore new epoch start";
shutdown(msg);
throw new XidRolloverException(msg);
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BinaryOutputArchive boa = BinaryOutputArchive.getArchive(baos);
try {
request.hdr.serialize(boa, "hdr");
if (request.txn != null) {
request.txn.serialize(boa, "txn");
}
baos.close();
} catch (IOException e) {
LOG.warn("This really should be impossible", e);
}
QuorumPacket pp = new QuorumPacket(Leader.PROPOSAL, request.zxid,
baos.toByteArray(), null);
Proposal p = new Proposal();
p.packet = pp;
p.request = request;
synchronized (this) {
if (LOG.isDebugEnabled()) {
LOG.debug("Proposing:: " + request);
}
lastProposed = p.packet.getZxid();
outstandingProposals.put(lastProposed, p);
sendPacket(pp);
}
return p;
}
/**
* Process sync requests
*
* @param r the request
*/
synchronized public void processSync(LearnerSyncRequest r){
if(outstandingProposals.isEmpty()){
sendSync(r);
} else {
List<LearnerSyncRequest> l = pendingSyncs.get(lastProposed);
if (l == null) {
l = new ArrayList<LearnerSyncRequest>();
}
l.add(r);
pendingSyncs.put(lastProposed, l);
}
}
/**
* Sends a sync message to the appropriate server
*
* @param f
* @param r
*/
public void sendSync(LearnerSyncRequest r){
QuorumPacket qp = new QuorumPacket(Leader.SYNC, 0, null, null);
r.fh.queuePacket(qp);
}
/**
* lets the leader know that a follower is capable of following and is done
* syncing
*
* @param handler handler of the follower
* @return last proposed zxid
*/
synchronized public long startForwarding(LearnerHandler handler,
long lastSeenZxid) {
// Queue up any outstanding requests enabling the receipt of
// new requests
if (lastProposed > lastSeenZxid) {
for (Proposal p : toBeApplied) {
if (p.packet.getZxid() <= lastSeenZxid) {
continue;
}
handler.queuePacket(p.packet);
// Since the proposal has been committed we need to send the
// commit message also
QuorumPacket qp = new QuorumPacket(Leader.COMMIT, p.packet
.getZxid(), null, null);
handler.queuePacket(qp);
}
List<Long>zxids = new ArrayList<Long>(outstandingProposals.keySet());
Collections.sort(zxids);
for (Long zxid: zxids) {
if (zxid <= lastSeenZxid) {
continue;
}
handler.queuePacket(outstandingProposals.get(zxid).packet);
}
}
if (handler.getLearnerType() == LearnerType.PARTICIPANT) {
synchronized (forwardingFollowers) {
forwardingFollowers.add(handler);
}
} else {
synchronized (observingLearners) {
observingLearners.add(handler);
}
}
return lastProposed;
}
}
| |
/**
* 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.storm.jdbc.common;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.*;
import java.sql.Date;
import java.util.*;
public class JdbcClient {
private static final Logger LOG = LoggerFactory.getLogger(JdbcClient.class);
private ConnectionProvider connectionProvider;
private int queryTimeoutSecs;
public JdbcClient(ConnectionProvider connectionProvider, int queryTimeoutSecs) {
this.connectionProvider = connectionProvider;
this.queryTimeoutSecs = queryTimeoutSecs;
}
public void insert(String tableName, List<List<Column>> columnLists) {
String query = constructInsertQuery(tableName, columnLists);
executeInsertQuery(query, columnLists);
}
public void executeInsertQuery(String query, List<List<Column>> columnLists) {
Connection connection = null;
try {
connection = connectionProvider.getConnection();
boolean autoCommit = connection.getAutoCommit();
if(autoCommit) {
connection.setAutoCommit(false);
}
LOG.debug("Executing query {}", query);
PreparedStatement preparedStatement = connection.prepareStatement(query);
if(queryTimeoutSecs > 0) {
preparedStatement.setQueryTimeout(queryTimeoutSecs);
}
for(List<Column> columnList : columnLists) {
setPreparedStatementParams(preparedStatement, columnList);
preparedStatement.addBatch();
}
int[] results = preparedStatement.executeBatch();
if(Arrays.asList(results).contains(Statement.EXECUTE_FAILED)) {
connection.rollback();
throw new RuntimeException("failed at least one sql statement in the batch, operation rolled back.");
} else {
try {
connection.commit();
} catch (SQLException e) {
throw new RuntimeException("Failed to commit insert query " + query, e);
}
}
} catch (SQLException e) {
throw new RuntimeException("Failed to execute insert query " + query, e);
} finally {
closeConnection(connection);
}
}
private String constructInsertQuery(String tableName, List<List<Column>> columnLists) {
StringBuilder sb = new StringBuilder();
sb.append("Insert into ").append(tableName).append(" (");
Collection<String> columnNames = Collections2.transform(columnLists.get(0), new Function<Column, String>() {
@Override
public String apply(Column input) {
return input.getColumnName();
}
});
String columns = Joiner.on(",").join(columnNames);
sb.append(columns).append(") values ( ");
String placeHolders = StringUtils.chop(StringUtils.repeat("?,", columnNames.size()));
sb.append(placeHolders).append(")");
return sb.toString();
}
public List<List<Column>> select(String sqlQuery, List<Column> queryParams) {
Connection connection = null;
try {
connection = connectionProvider.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(sqlQuery);
if(queryTimeoutSecs > 0) {
preparedStatement.setQueryTimeout(queryTimeoutSecs);
}
setPreparedStatementParams(preparedStatement, queryParams);
ResultSet resultSet = preparedStatement.executeQuery();
List<List<Column>> rows = Lists.newArrayList();
while(resultSet.next()){
ResultSetMetaData metaData = resultSet.getMetaData();
int columnCount = metaData.getColumnCount();
List<Column> row = Lists.newArrayList();
for(int i=1 ; i <= columnCount; i++) {
String columnLabel = metaData.getColumnLabel(i);
int columnType = metaData.getColumnType(i);
Class columnJavaType = Util.getJavaType(columnType);
if (columnJavaType.equals(String.class)) {
row.add(new Column<String>(columnLabel, resultSet.getString(columnLabel), columnType));
} else if (columnJavaType.equals(Integer.class)) {
row.add(new Column<Integer>(columnLabel, resultSet.getInt(columnLabel), columnType));
} else if (columnJavaType.equals(Double.class)) {
row.add(new Column<Double>(columnLabel, resultSet.getDouble(columnLabel), columnType));
} else if (columnJavaType.equals(Float.class)) {
row.add(new Column<Float>(columnLabel, resultSet.getFloat(columnLabel), columnType));
} else if (columnJavaType.equals(Short.class)) {
row.add(new Column<Short>(columnLabel, resultSet.getShort(columnLabel), columnType));
} else if (columnJavaType.equals(Boolean.class)) {
row.add(new Column<Boolean>(columnLabel, resultSet.getBoolean(columnLabel), columnType));
} else if (columnJavaType.equals(byte[].class)) {
row.add(new Column<byte[]>(columnLabel, resultSet.getBytes(columnLabel), columnType));
} else if (columnJavaType.equals(Long.class)) {
row.add(new Column<Long>(columnLabel, resultSet.getLong(columnLabel), columnType));
} else if (columnJavaType.equals(Date.class)) {
row.add(new Column<Date>(columnLabel, resultSet.getDate(columnLabel), columnType));
} else if (columnJavaType.equals(Time.class)) {
row.add(new Column<Time>(columnLabel, resultSet.getTime(columnLabel), columnType));
} else if (columnJavaType.equals(Timestamp.class)) {
row.add(new Column<Timestamp>(columnLabel, resultSet.getTimestamp(columnLabel), columnType));
} else {
throw new RuntimeException("type = " + columnType + " for column " + columnLabel + " not supported.");
}
}
rows.add(row);
}
return rows;
} catch (SQLException e) {
throw new RuntimeException("Failed to execute select query " + sqlQuery, e);
} finally {
closeConnection(connection);
}
}
public List<Column> getColumnSchema(String tableName) {
Connection connection = null;
List<Column> columns = new ArrayList<Column>();
try {
connection = connectionProvider.getConnection();
DatabaseMetaData metaData = connection.getMetaData();
ResultSet resultSet = metaData.getColumns(null, null, tableName, null);
while (resultSet.next()) {
columns.add(new Column(resultSet.getString("COLUMN_NAME"), resultSet.getInt("DATA_TYPE")));
}
return columns;
} catch (SQLException e) {
throw new RuntimeException("Failed to get schema for table " + tableName, e);
} finally {
closeConnection(connection);
}
}
public void executeSql(String sql) {
Connection connection = null;
try {
connection = connectionProvider.getConnection();
Statement statement = connection.createStatement();
statement.execute(sql);
} catch (SQLException e) {
throw new RuntimeException("Failed to execute SQL", e);
} finally {
closeConnection(connection);
}
}
private void setPreparedStatementParams(PreparedStatement preparedStatement, List<Column> columnList) throws SQLException {
int index = 1;
for (Column column : columnList) {
Class columnJavaType = Util.getJavaType(column.getSqlType());
if (column.getVal() == null) {
preparedStatement.setNull(index, column.getSqlType());
} else if (columnJavaType.equals(String.class)) {
preparedStatement.setString(index, (String) column.getVal());
} else if (columnJavaType.equals(Integer.class)) {
preparedStatement.setInt(index, (Integer) column.getVal());
} else if (columnJavaType.equals(Double.class)) {
preparedStatement.setDouble(index, (Double) column.getVal());
} else if (columnJavaType.equals(Float.class)) {
preparedStatement.setFloat(index, (Float) column.getVal());
} else if (columnJavaType.equals(Short.class)) {
preparedStatement.setShort(index, (Short) column.getVal());
} else if (columnJavaType.equals(Boolean.class)) {
preparedStatement.setBoolean(index, (Boolean) column.getVal());
} else if (columnJavaType.equals(byte[].class)) {
preparedStatement.setBytes(index, (byte[]) column.getVal());
} else if (columnJavaType.equals(Long.class)) {
preparedStatement.setLong(index, (Long) column.getVal());
} else if (columnJavaType.equals(Date.class)) {
preparedStatement.setDate(index, (Date) column.getVal());
} else if (columnJavaType.equals(Time.class)) {
preparedStatement.setTime(index, (Time) column.getVal());
} else if (columnJavaType.equals(Timestamp.class)) {
preparedStatement.setTimestamp(index, (Timestamp) column.getVal());
} else {
throw new RuntimeException("Unknown type of value " + column.getVal() + " for column " + column.getColumnName());
}
++index;
}
}
private void closeConnection(Connection connection) {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
throw new RuntimeException("Failed to close connection", e);
}
}
}
}
| |
/*
* Copyright (C) 2013 Dr. John Lindsay <jlindsay@uoguelph.ca>
*
* 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 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package plugins;
import java.util.Date;
import whitebox.geospatialfiles.WhiteboxRaster;
import whitebox.interfaces.WhiteboxPlugin;
import whitebox.interfaces.WhiteboxPluginHost;
/**
* This tool can be used to calculate the downslope index described by Hjerdt et al (2004).
*
* @author Dr. John Lindsay email: jlindsay@uoguelph.ca
*/
public class DownslopeIndex implements WhiteboxPlugin {
private WhiteboxPluginHost myHost = null;
private String[] args;
// Constants
private static final double LnOf2 = 0.693147180559945;
/**
* Used to retrieve the plugin tool's name. This is a short, unique name
* containing no spaces.
*
* @return String containing plugin name.
*/
@Override
public String getName() {
return "DownslopeIndex";
}
/**
* Used to retrieve the plugin tool's descriptive name. This can be a longer
* name (containing spaces) and is used in the interface to list the tool.
*
* @return String containing the plugin descriptive name.
*/
@Override
public String getDescriptiveName() {
return "Downslope Index";
}
/**
* Used to retrieve a short description of what the plugin tool does.
*
* @return String containing the plugin's description.
*/
@Override
public String getToolDescription() {
return "Calculates the downslope index of Hjerdt et al. (WRR 2004)";
}
/**
* Used to identify which toolboxes this plugin tool should be listed in.
*
* @return Array of Strings.
*/
@Override
public String[] getToolbox() {
String[] ret = {"FlowpathTAs", "HydroTools"};
return ret;
}
/**
* Sets the WhiteboxPluginHost to which the plugin tool is tied. This is the
* class that the plugin will send all feedback messages, progress updates,
* and return objects.
*
* @param host The WhiteboxPluginHost that called the plugin tool.
*/
@Override
public void setPluginHost(WhiteboxPluginHost host) {
myHost = host;
}
/**
* Used to communicate feedback pop-up messages between a plugin tool and
* the main Whitebox user-interface.
*
* @param feedback String containing the text to display.
*/
private void showFeedback(String message) {
if (myHost != null) {
myHost.showFeedback(message);
} else {
System.out.println(message);
}
}
/**
* Used to communicate a return object from a plugin tool to the main
* Whitebox user-interface.
*
* @return Object, such as an output WhiteboxRaster.
*/
private void returnData(Object ret) {
if (myHost != null) {
myHost.returnData(ret);
}
}
private int previousProgress = 0;
private String previousProgressLabel = "";
/**
* Used to communicate a progress update between a plugin tool and the main
* Whitebox user interface.
*
* @param progressLabel A String to use for the progress label.
* @param progress Float containing the progress value (between 0 and 100).
*/
private void updateProgress(String progressLabel, int progress) {
if (myHost != null && ((progress != previousProgress)
|| (!progressLabel.equals(previousProgressLabel)))) {
myHost.updateProgress(progressLabel, progress);
}
previousProgress = progress;
previousProgressLabel = progressLabel;
}
/**
* Used to communicate a progress update between a plugin tool and the main
* Whitebox user interface.
*
* @param progress Float containing the progress value (between 0 and 100).
*/
private void updateProgress(int progress) {
if (myHost != null && progress != previousProgress) {
myHost.updateProgress(progress);
}
previousProgress = progress;
}
/**
* Sets the arguments (parameters) used by the plugin.
*
* @param args An array of string arguments.
*/
@Override
public void setArgs(String[] args) {
this.args = args.clone();
}
private boolean cancelOp = false;
/**
* Used to communicate a cancel operation from the Whitebox GUI.
*
* @param cancel Set to true if the plugin should be canceled.
*/
@Override
public void setCancelOp(boolean cancel) {
cancelOp = cancel;
}
private void cancelOperation() {
showFeedback("Operation cancelled.");
updateProgress("Progress: ", 0);
}
private boolean amIActive = false;
/**
* Used by the Whitebox GUI to tell if this plugin is still running.
*
* @return a boolean describing whether or not the plugin is actively being
* used.
*/
@Override
public boolean isActive() {
return amIActive;
}
/**
* Used to execute this plugin tool.
*/
@Override
public void run() {
amIActive = true;
String pointerHeader, DEMHeader, outputHeader;
int row, col, x, y;
int progress;
int c;
int[] dX = new int[]{1, 1, 1, 0, -1, -1, -1, 0};
int[] dY = new int[]{-1, 0, 1, 1, 1, 0, -1, -1};
boolean flag;
double flowDir, flowLength, flowLengthThroughCell;
double zSt, zCurrent, zLastCell;
double rad2Deg = 180.0 / Math.PI;
if (args.length <= 0) {
showFeedback("Plugin parameters have not been set.");
return;
}
pointerHeader = args[0];
DEMHeader = args[1];
outputHeader = args[2];
double d = Double.parseDouble(args[3]);
if (d <= 0) {
showFeedback("The vertical drop parameter must be set to a positive numerical value.");
return;
}
String outputType = args[4].toLowerCase().trim();
// check to see that the inputHeader and outputHeader are not null.
if (pointerHeader.isEmpty() || DEMHeader.isEmpty() || outputHeader.isEmpty()) {
showFeedback("One or more of the input parameters have not been set properly.");
return;
}
try {
WhiteboxRaster pointer = new WhiteboxRaster(pointerHeader, "r");
int rows = pointer.getNumberRows();
int cols = pointer.getNumberColumns();
double noData = pointer.getNoDataValue();
double gridResX = pointer.getCellSizeX();
double gridResY = pointer.getCellSizeY();
double diagGridRes = Math.sqrt(gridResX * gridResX + gridResY * gridResY);
double[] gridLengths = new double[]{diagGridRes, gridResX, diagGridRes, gridResY, diagGridRes, gridResX, diagGridRes, gridResY};
WhiteboxRaster dem = new WhiteboxRaster(DEMHeader, "r");
if (dem.getNumberColumns() != cols || dem.getNumberRows() != rows) {
showFeedback("Each of the input images must have the same dimensions (i.e. rows and columns).");
return;
}
double demNoData = dem.getNoDataValue();
if (pointer.getXYUnits().toLowerCase().contains("deg") ||
dem.getXYUnits().toLowerCase().contains("deg")) {
double p1 = 111412.84; // longitude calculation term 1
double p2 = -93.5; // longitude calculation term 2
double p3 = 0.118; // longitude calculation term 3
double lat = Math.toRadians((pointer.getNorth() - pointer.getSouth()) / 2.0);
double longlen = (p1 * Math.cos(lat)) + (p2 * Math.cos(3 * lat)) +
(p3 * Math.cos(5 * lat));
for (int i = 0;i < 8; i++) {
gridLengths[i] = gridLengths[i] * longlen;
}
}
WhiteboxRaster output = new WhiteboxRaster(outputHeader, "rw",
pointerHeader, WhiteboxRaster.DataType.FLOAT, noData);
output.setPreferredPalette("spectrum.pal");
output.setDataScale(WhiteboxRaster.DataScale.CONTINUOUS);
switch (outputType) {
case "tangent":
for (row = 0; row < rows; row++) {
for (col = 0; col < cols; col++) {
if (pointer.getValue(row, col) != noData && dem.getValue(row, col) != demNoData) {
zSt = dem.getValue(row, col);
flag = false;
x = col;
y = row;
flowLength = 0;
do {
zLastCell = dem.getValue(row, col);
// find it's downslope neighbour
flowDir = pointer.getValue(y, x);
if (flowDir > 0) {
// what's the flow direction as an int?
c = (int) (Math.log(flowDir) / LnOf2);
//move x and y accordingly
x += dX[c];
y += dY[c];
zCurrent = dem.getValue(y, x);
if (zCurrent != demNoData) {
if ((zSt - zCurrent) < d) {
flowLength += gridLengths[c];
} else {
//interpolate the distance
flowLengthThroughCell = gridLengths[c] * (zLastCell - (zSt - d)) / (zLastCell - zCurrent);
flowLength += flowLengthThroughCell;
output.setValue(row, col, d / flowLength);
flag = true;
}
} else {
if (flowLength > 0) {
output.setValue(row, col, (zSt - zLastCell) / flowLength);
} else {
output.setValue(row, col, noData);
}
flag = true;
}
} else { // you've hit the edge or a pit cell.
if (flowLength > 0) {
output.setValue(row, col, (zSt - zLastCell) / flowLength);
} else {
output.setValue(row, col, noData);
}
flag = true;
}
} while (!flag);
}
}
if (cancelOp) {
cancelOperation();
return;
}
progress = (int) (100f * row / (rows - 1));
updateProgress(progress);
}
break;
case "degrees":
for (row = 0; row < rows; row++) {
for (col = 0; col < cols; col++) {
if (pointer.getValue(row, col) != noData && dem.getValue(row, col) != demNoData) {
zSt = dem.getValue(row, col);
flag = false;
x = col;
y = row;
flowLength = 0;
do {
zLastCell = dem.getValue(row, col);
// find it's downslope neighbour
flowDir = pointer.getValue(y, x);
if (flowDir > 0) {
// what's the flow direction as an int?
c = (int) (Math.log(flowDir) / LnOf2);
//move x and y accordingly
x += dX[c];
y += dY[c];
zCurrent = dem.getValue(y, x);
if (zCurrent != demNoData) {
if ((zSt - zCurrent) < d) {
flowLength += gridLengths[c];
} else {
//interpolate the distance
flowLengthThroughCell = gridLengths[c] * (zLastCell - (zSt - d)) / (zLastCell - zCurrent);
flowLength += flowLengthThroughCell;
output.setValue(row, col, Math.atan(d / flowLength) * rad2Deg);
flag = true;
}
} else {
if (flowLength > 0) {
output.setValue(row, col, Math.atan((zSt - zLastCell) / flowLength) * rad2Deg);
} else {
output.setValue(row, col, noData);
}
flag = true;
}
} else { // you've hit the edge or a pit cell.
if (flowLength > 0) {
output.setValue(row, col, Math.atan((zSt - zLastCell) / flowLength) * rad2Deg);
} else {
output.setValue(row, col, noData);
}
flag = true;
}
} while (!flag);
}
}
if (cancelOp) {
cancelOperation();
return;
}
progress = (int) (100f * row / (rows - 1));
updateProgress(progress);
}
break;
case "radians":
for (row = 0; row < rows; row++) {
for (col = 0; col < cols; col++) {
if (pointer.getValue(row, col) != noData && dem.getValue(row, col) != demNoData) {
zSt = dem.getValue(row, col);
flag = false;
x = col;
y = row;
flowLength = 0;
do {
zLastCell = dem.getValue(row, col);
// find it's downslope neighbour
flowDir = pointer.getValue(y, x);
if (flowDir > 0) {
// what's the flow direction as an int?
c = (int) (Math.log(flowDir) / LnOf2);
//move x and y accordingly
x += dX[c];
y += dY[c];
zCurrent = dem.getValue(y, x);
if (zCurrent != demNoData) {
if ((zSt - zCurrent) < d) {
flowLength += gridLengths[c];
} else {
//interpolate the distance
flowLengthThroughCell = gridLengths[c] * (zLastCell - (zSt - d)) / (zLastCell - zCurrent);
flowLength += flowLengthThroughCell;
output.setValue(row, col, Math.atan(d / flowLength));
flag = true;
}
} else {
if (flowLength > 0) {
output.setValue(row, col, Math.atan((zSt - zLastCell) / flowLength));
} else {
output.setValue(row, col, noData);
}
flag = true;
}
} else { // you've hit the edge or a pit cell.
if (flowLength > 0) {
output.setValue(row, col, Math.atan((zSt - zLastCell) / flowLength));
} else {
output.setValue(row, col, noData);
}
flag = true;
}
} while (!flag);
}
}
if (cancelOp) {
cancelOperation();
return;
}
progress = (int) (100f * row / (rows - 1));
updateProgress(progress);
}
break;
case "distance":
for (row = 0; row < rows; row++) {
for (col = 0; col < cols; col++) {
if (pointer.getValue(row, col) != noData && dem.getValue(row, col) != demNoData) {
zSt = dem.getValue(row, col);
flag = false;
x = col;
y = row;
flowLength = 0;
do {
zLastCell = dem.getValue(row, col);
// find it's downslope neighbour
flowDir = pointer.getValue(y, x);
if (flowDir > 0) {
// what's the flow direction as an int?
c = (int) (Math.log(flowDir) / LnOf2);
//move x and y accordingly
x += dX[c];
y += dY[c];
zCurrent = dem.getValue(y, x);
if (zCurrent != demNoData) {
if ((zSt - zCurrent) < d) {
flowLength += gridLengths[c];
} else {
//interpolate the distance
flowLengthThroughCell = gridLengths[c] * (zLastCell - (zSt - d)) / (zLastCell - zCurrent);
flowLength += flowLengthThroughCell;
output.setValue(row, col, flowLength);
flag = true;
}
} else {
if (flowLength > 0) {
output.setValue(row, col, flowLength);
} else {
output.setValue(row, col, noData);
}
flag = true;
}
} else { // you've hit the edge or a pit cell.
if (flowLength > 0) {
output.setValue(row, col, flowLength);
} else {
output.setValue(row, col, noData);
}
flag = true;
}
} while (!flag);
}
}
if (cancelOp) {
cancelOperation();
return;
}
progress = (int) (100f * row / (rows - 1));
updateProgress(progress);
}
break;
}
output.addMetadataEntry("Created by the "
+ getDescriptiveName() + " tool.");
output.addMetadataEntry("Created on " + new Date());
pointer.close();
dem.close();
output.close();
// returning a header file string displays the image.
returnData(outputHeader);
} catch (OutOfMemoryError oe) {
myHost.showFeedback("An out-of-memory error has occurred during operation.");
} catch (Exception e) {
myHost.showFeedback("An error has occurred during operation. See log file for details.");
myHost.logException("Error in " + getDescriptiveName(), e);
} finally {
updateProgress("Progress: ", 0);
// tells the main application that this process is completed.
amIActive = false;
myHost.pluginComplete();
}
}
// /**
// * This method is only used during testing.
// */
// // this is only used for testing the tool
// public static void main(String[] args) {
// args = new String[5];
// args[0] = "/Users/johnlindsay/Documents/Data/SouthernOnt/tmp10.dep";
// args[1] = "/Users/johnlindsay/Documents/Data/SouthernOnt/tmp4.dep";
// args[2] = "/Users/johnlindsay/Documents/Data/SouthernOnt/tmp11.dep";
// args[3] = "5";
// args[4] = "distance";
//
// DownslopeIndex di = new DownslopeIndex();
// di.setArgs(args);
// di.run();
//
// }
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.management.internal.pulse;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.Map;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.apache.geode.cache.Cache;
import org.apache.geode.distributed.DistributedMember;
import org.apache.geode.distributed.Locator;
import org.apache.geode.internal.cache.GemFireCacheImpl;
import org.apache.geode.internal.cache.wan.WANTestBase;
import org.apache.geode.management.DistributedSystemMXBean;
import org.apache.geode.management.GatewayReceiverMXBean;
import org.apache.geode.management.GatewaySenderMXBean;
import org.apache.geode.management.ManagementService;
import org.apache.geode.management.ManagementTestBase;
import org.apache.geode.management.RegionMXBean;
import org.apache.geode.management.internal.MBeanJMXAdapter;
import org.apache.geode.test.dunit.Host;
import org.apache.geode.test.dunit.LogWriterUtils;
import org.apache.geode.test.dunit.SerializableRunnable;
import org.apache.geode.test.dunit.VM;
import org.apache.geode.test.dunit.Wait;
import org.apache.geode.test.dunit.WaitCriterion;
import org.apache.geode.test.junit.categories.DistributedTest;
import org.apache.geode.test.junit.categories.FlakyTest;
/**
* This is for testing remote Cluster
*
*
*/
@Category(DistributedTest.class)
public class TestRemoteClusterDUnitTest extends ManagementTestBase {
private static final long serialVersionUID = 1L;
public static MBeanServer mbeanServer = MBeanJMXAdapter.mbeanServer;
public TestRemoteClusterDUnitTest() throws Exception {
super();
}
@Category(FlakyTest.class) // GEODE-1629
@Test
public void testMBeanCallback() throws Exception {
VM nyLocator = getManagedNodeList().get(0);
VM nyReceiver = getManagedNodeList().get(1);
VM puneSender = getManagedNodeList().get(2);
VM managing = getManagingNode();
VM puneLocator = Host.getLocator();
int dsIdPort = puneLocator.invoke(() -> TestRemoteClusterDUnitTest.getLocatorPort());
Integer nyPort = nyLocator.invoke(() -> WANTestBase.createFirstRemoteLocator(12, dsIdPort));
puneSender.invoke(() -> WANTestBase.createCache(dsIdPort));
managing.invoke(() -> WANTestBase.createManagementCache(dsIdPort));
startManagingNode(managing);
puneSender
.invoke(() -> WANTestBase.createSender("pn", 12, true, 100, 300, false, false, null, true));
managing
.invoke(() -> WANTestBase.createSender("pn", 12, true, 100, 300, false, false, null, true));
puneSender.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "pn",
1, 100, false));
managing.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "pn", 1,
100, false));
WANTestBase.createCacheInVMs(nyPort, nyReceiver);
nyReceiver.invoke(() -> WANTestBase.createReceiver());
nyReceiver.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", null,
1, 100, false));
WANTestBase.startSenderInVMs("pn", puneSender, managing);
// make sure all the senders are running before doing any puts
puneSender.invoke(() -> WANTestBase.waitForSenderRunningState("pn"));
managing.invoke(() -> WANTestBase.waitForSenderRunningState("pn"));
checkSenderMBean(puneSender, getTestMethodName() + "_PR");
checkSenderMBean(managing, getTestMethodName() + "_PR");
checkReceiverMBean(nyReceiver);
stopGatewaySender(puneSender);
startGatewaySender(puneSender);
DistributedMember puneMember = puneSender.invoke(() -> TestRemoteClusterDUnitTest.getMember());
checkRemoteClusterStatus(managing, puneMember);
}
private static int getLocatorPort() {
return Locator.getLocators().get(0).getPort();
}
private static DistributedMember getMember() {
return GemFireCacheImpl.getInstance().getMyId();
}
/**
* Checks Proxy GatewaySender
*
* @param vm reference to VM
*/
@SuppressWarnings("serial")
protected void checkRemoteClusterStatus(final VM vm, final DistributedMember senderMember) {
SerializableRunnable checkProxySender = new SerializableRunnable("DS Map Size") {
public void run() {
Cache cache = GemFireCacheImpl.getInstance();
final WaitCriterion waitCriteria2 = new WaitCriterion() {
@Override
public boolean done() {
Cache cache = GemFireCacheImpl.getInstance();
final ManagementService service = ManagementService.getManagementService(cache);
final DistributedSystemMXBean dsBean = service.getDistributedSystemMXBean();
return dsBean != null;
}
@Override
public String description() {
return "wait for getDistributedSystemMXBean to complete and get results";
}
};
Wait.waitForCriterion(waitCriteria2, 2 * 60 * 1000, 5000, true);
ManagementService service = ManagementService.getManagementService(cache);
final DistributedSystemMXBean dsBean = service.getDistributedSystemMXBean();
assertNotNull(dsBean);
Map<String, Boolean> dsMap = dsBean.viewRemoteClusterStatus();
LogWriterUtils.getLogWriter().info("Ds Map is: " + dsMap.size());
assertNotNull(dsMap);
assertEquals(true, dsMap.size() > 0);
}
};
vm.invoke(checkProxySender);
}
/**
* stops a gateway sender
*
* @param vm reference to VM
*/
@SuppressWarnings("serial")
protected void stopGatewaySender(final VM vm) {
SerializableRunnable stopGatewaySender = new SerializableRunnable("Stop Gateway Sender") {
public void run() {
Cache cache = GemFireCacheImpl.getInstance();
ManagementService service = ManagementService.getManagementService(cache);
GatewaySenderMXBean bean = service.getLocalGatewaySenderMXBean("pn");
assertNotNull(bean);
bean.stop();
assertFalse(bean.isRunning());
}
};
vm.invoke(stopGatewaySender);
}
/**
* start a gateway sender
*
* @param vm reference to VM
*/
@SuppressWarnings("serial")
protected void startGatewaySender(final VM vm) {
SerializableRunnable stopGatewaySender = new SerializableRunnable("Start Gateway Sender") {
public void run() {
Cache cache = GemFireCacheImpl.getInstance();
ManagementService service = ManagementService.getManagementService(cache);
GatewaySenderMXBean bean = service.getLocalGatewaySenderMXBean("pn");
assertNotNull(bean);
bean.start();
assertTrue(bean.isRunning());
}
};
vm.invoke(stopGatewaySender);
}
/**
* Checks whether a GatewayReceiverMBean is created or not
*
* @param vm reference to VM
*/
@SuppressWarnings("serial")
protected void checkReceiverMBean(final VM vm) {
SerializableRunnable checkMBean = new SerializableRunnable("Check Receiver MBean") {
public void run() {
Cache cache = GemFireCacheImpl.getInstance();
ManagementService service = ManagementService.getManagementService(cache);
GatewayReceiverMXBean bean = service.getLocalGatewayReceiverMXBean();
assertNotNull(bean);
}
};
vm.invoke(checkMBean);
}
/**
* Checks whether a GatewayReceiverMBean is created or not
*
* @param vm reference to VM
*/
@SuppressWarnings("serial")
protected void checkSenderMBean(final VM vm, final String regionPath) {
SerializableRunnable checkMBean = new SerializableRunnable("Check Sender MBean") {
public void run() {
Cache cache = GemFireCacheImpl.getInstance();
ManagementService service = ManagementService.getManagementService(cache);
GatewaySenderMXBean bean = service.getLocalGatewaySenderMXBean("pn");
assertNotNull(bean);
assertTrue(bean.isConnected());
ObjectName regionBeanName = service.getRegionMBeanName(
cache.getDistributedSystem().getDistributedMember(), "/" + regionPath);
RegionMXBean rBean = service.getMBeanInstance(regionBeanName, RegionMXBean.class);
assertTrue(rBean.isGatewayEnabled());
}
};
vm.invoke(checkMBean);
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. The ASF
* licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.cloudera.flume.handlers.avro;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.avro.Protocol;
import org.apache.avro.ipc.CallFuture;
import org.apache.avro.ipc.Callback;
import org.apache.avro.ipc.NettyTransportCodec.NettyDataPack;
import org.apache.avro.ipc.NettyTransportCodec.NettyFrameDecoder;
import org.apache.avro.ipc.NettyTransportCodec.NettyFrameEncoder;
import org.apache.avro.ipc.Transceiver;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.*;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.ChannelGroupFuture;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A Netty-based {@link Transceiver} implementation.
*
* Based off the one in Avro IPC but modified to check channel.isWritable()
* before writing. That way, slow/blocked downstream servers don't cause buffers
* to fill up, ultimately causing OutOfMemoryErrors.
*/
public class AvroNettyTransceiver extends Transceiver {
/**
* If not specified, the default connection timeout will be used (60 sec).
*/
public static final long DEFAULT_CONNECTION_TIMEOUT_MILLIS = 60 * 1000L;
public static final String NETTY_CONNECT_TIMEOUT_OPTION =
"connectTimeoutMillis";
public static final String NETTY_TCP_NODELAY_OPTION = "tcpNoDelay";
public static final boolean DEFAULT_TCP_NODELAY_VALUE = true;
private static final Logger LOG = LoggerFactory.getLogger(AvroNettyTransceiver.class
.getName());
private final AtomicInteger serialGenerator = new AtomicInteger(0);
private final Map<Integer, Callback<List<ByteBuffer>>> requests =
new ConcurrentHashMap<Integer, Callback<List<ByteBuffer>>>();
private final ChannelFactory channelFactory;
private final long connectTimeoutMillis;
private final ClientBootstrap bootstrap;
private final InetSocketAddress remoteAddr;
private final AtomicLong sentEvents;
private final AtomicLong droppedEvents;
private final Timer eventsLogTimer;
volatile ChannelFuture channelFuture;
volatile boolean stopping;
private final Object channelFutureLock = new Object();
/**
* Read lock must be acquired whenever using non-final state. Write lock
* must be acquired whenever modifying state.
*/
private final ReentrantReadWriteLock stateLock = new ReentrantReadWriteLock();
private Channel channel; // Synchronized on stateLock
private Protocol remote; // Synchronized on stateLock
private final String logicalName;
private final ChannelGroup allChannels = new DefaultChannelGroup("AvroNettyTransceiver Channel Group") {
AtomicBoolean closed = new AtomicBoolean(false);
@Override
public boolean add(Channel channel) {
if (closed.get()) {
channel.close();
return false;
}
else {
return super.add(channel);
}
}
@Override
public ChannelGroupFuture close() {
closed.set(true);
return super.close();
}
};
AvroNettyTransceiver(String logicalName) {
channelFactory = null;
connectTimeoutMillis = 0L;
bootstrap = null;
remoteAddr = null;
sentEvents = null;
droppedEvents = null;
eventsLogTimer = null;
channelFuture = null;
this.logicalName = logicalName;
}
/**
* Creates a NettyTransceiver, and attempts to connect to the given address.
* {@link #DEFAULT_CONNECTION_TIMEOUT_MILLIS} is used for the connection
* timeout.
*
* @param addr the address to connect to.
* @param channelFactory the factory to use to create a new Netty Channel.
* @throws IOException if an error occurs connecting to the given address.
*/
public AvroNettyTransceiver(InetSocketAddress addr, ChannelFactory channelFactory, String logicalName)
throws IOException {
this(addr, channelFactory, buildDefaultBootstrapOptions(null), logicalName);
}
/**
* Creates a NettyTransceiver, and attempts to connect to the given address.
*
* @param addr the address to connect to.
* @param channelFactory the factory to use to create a new Netty Channel.
* @param connectTimeoutMillis maximum amount of time to wait for connection
* establishment in milliseconds, or null to use
* {@link #DEFAULT_CONNECTION_TIMEOUT_MILLIS}.
* @throws IOException if an error occurs connecting to the given address.
*/
public AvroNettyTransceiver(InetSocketAddress addr, ChannelFactory channelFactory, String logicalName,
Long connectTimeoutMillis) throws IOException {
this(addr, channelFactory,
buildDefaultBootstrapOptions(connectTimeoutMillis), logicalName);
}
/**
* Creates a NettyTransceiver, and attempts to connect to the given address.
* It is strongly recommended that the {@link #NETTY_CONNECT_TIMEOUT_OPTION}
* option be set to a reasonable timeout value (a Long value in
* milliseconds) to prevent connect/disconnect attempts from hanging
* indefinitely. It is also recommended that the
* {@link #NETTY_TCP_NODELAY_OPTION} option be set to true to minimize RPC
* latency.
*
* @param addr the address to connect to.
* @param channelFactory the factory to use to create a new Netty Channel.
* @param nettyClientBootstrapOptions map of Netty ClientBootstrap options
* to use.
* @throws IOException if an error occurs connecting to the given address.
*/
public AvroNettyTransceiver(InetSocketAddress addr, ChannelFactory channelFactory,
Map<String, Object> nettyClientBootstrapOptions, final String logicalName) throws IOException {
if (channelFactory == null) {
throw new NullPointerException("channelFactory is null");
}
this.logicalName = logicalName;
// Set up.
this.channelFactory = channelFactory;
this.connectTimeoutMillis = (Long) nettyClientBootstrapOptions.get(NETTY_CONNECT_TIMEOUT_OPTION);
bootstrap = new ClientBootstrap(channelFactory);
remoteAddr = addr;
// Configure the event pipeline factory.
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
@Override
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline p = Channels.pipeline();
p.addLast("frameDecoder", new NettyFrameDecoder());
p.addLast("frameEncoder", new NettyFrameEncoder());
p.addLast("handler", new NettyClientAvroHandler(logicalName));
return p;
}
});
if (nettyClientBootstrapOptions != null) {
LOG.debug("Using Netty bootstrap options: "
+ nettyClientBootstrapOptions);
bootstrap.setOptions(nettyClientBootstrapOptions);
}
// Make a new connection.
stateLock.readLock().lock();
try {
getChannel();
}
finally {
stateLock.readLock().unlock();
}
sentEvents = new AtomicLong();
droppedEvents = new AtomicLong();
eventsLogTimer = new Timer();
TimerTask eventsLogTimerTask = new TimerTask() {
@Override
public void run() {
if (droppedEvents.longValue() > 0l) {
LOG.info("[logicalName: " + logicalName + ", host: " + remoteAddr.getHostName() + ", port: " + remoteAddr.getPort() + "] Sent " + sentEvents.longValue() + " events in the past minute.");
LOG.info("[logicalName: " + logicalName + ", host: " + remoteAddr.getHostName() + ", port: " + remoteAddr.getPort() + "] Dropped " + droppedEvents.longValue() + " events in the past minute due to full TCP write buffer.");
droppedEvents.set(0l);
}
if (sentEvents.longValue() > 0l) {
sentEvents.set(0l);
}
}
};
// schedule the task to run starting now and then every hour...
Calendar start = Calendar.getInstance();
start.add(Calendar.MINUTE, 1);
start.set(Calendar.SECOND, 0);
start.set(Calendar.MILLISECOND, 0);
eventsLogTimer.scheduleAtFixedRate(eventsLogTimerTask, start.getTime(), 1000 * 60);
}
/**
* Creates the default options map for the Netty ClientBootstrap.
*
* @param connectTimeoutMillis connection timeout in milliseconds, or null
* if no timeout is desired.
* @return the map of Netty bootstrap options.
*/
private static Map<String, Object> buildDefaultBootstrapOptions(
Long connectTimeoutMillis) {
Map<String, Object> options = new HashMap<String, Object>(2);
options.put(NETTY_TCP_NODELAY_OPTION, DEFAULT_TCP_NODELAY_VALUE);
options.put(NETTY_CONNECT_TIMEOUT_OPTION,
connectTimeoutMillis == null ? DEFAULT_CONNECTION_TIMEOUT_MILLIS
: connectTimeoutMillis);
options.put("writeBufferLowWaterMark", 64 * 1024);
options.put("writeBufferHighWaterMark", 10 * 64 * 1024);
options.put("sendBufferSize", 1048576);
options.put("receiveBufferSize", 1048576);
options.put("keepAlive", true);
return options;
}
/**
* Tests whether the given channel is ready for writing.
*
* @return true if the channel is open and ready; false otherwise.
*/
private static boolean isChannelReady(Channel channel) {
return (channel != null)
&& channel.isOpen() && channel.isBound() && channel.isConnected();
}
/**
* Gets the Netty channel. If the channel is not connected, first attempts
* to connect. NOTE: The stateLock read lock *must* be acquired before
* calling this method.
*
* @return the Netty channel
* @throws IOException if an error occurs connecting the channel.
*/
private Channel getChannel() throws IOException {
if (!isChannelReady(channel)) {
// Need to reconnect
// Upgrade to write lock
stateLock.readLock().unlock();
stateLock.writeLock().lock();
try {
if (!isChannelReady(channel)) {
synchronized (channelFutureLock) {
if (!stopping) {
LOG.debug("Connecting to " + remoteAddr + " [" + this.getLogicalName() + "]");
channelFuture = bootstrap.connect(remoteAddr);
}
}
if (channelFuture != null) {
channelFuture.awaitUninterruptibly(connectTimeoutMillis);
synchronized (channelFutureLock) {
if (!channelFuture.isSuccess()) {
throw new IOException("Error connecting to " + remoteAddr + " [" + this.getLogicalName() + "]",
channelFuture.getCause());
}
channel = channelFuture.getChannel();
channelFuture = null;
}
}
}
} finally {
// Downgrade to read lock:
stateLock.readLock().lock();
stateLock.writeLock().unlock();
}
}
return channel;
}
/**
* Closes the connection to the remote peer if connected.
*/
private void disconnect() {
disconnect(false, false, null);
}
/**
* Closes the connection to the remote peer if connected.
*
* @param awaitCompletion if true, will block until the close has completed.
* @param cancelPendingRequests if true, will drain the requests map and
* send an IOException to all Callbacks.
* @param cause if non-null and cancelPendingRequests is true, this
* Throwable will be passed to all Callbacks.
*/
private void disconnect(boolean awaitCompletion, boolean cancelPendingRequests,
Throwable cause) {
Channel channelToClose = null;
Map<Integer, Callback<List<ByteBuffer>>> requestsToCancel = null;
boolean stateReadLockHeld = stateLock.getReadHoldCount() != 0;
synchronized (channelFutureLock) {
if (stopping && channelFuture != null) {
channelFuture.cancel();
}
}
if (stateReadLockHeld) {
stateLock.readLock().unlock();
}
stateLock.writeLock().lock();
try {
if (channel != null) {
if (cause != null) {
LOG.debug("Disconnecting from " + remoteAddr + " [" + this.getLogicalName() + "]", cause);
} else {
LOG.debug("Disconnecting from " + remoteAddr + " [" + this.getLogicalName() + "]");
}
channelToClose = channel;
channel = null;
remote = null;
if (cancelPendingRequests) {
// Remove all pending requests (will be canceled after relinquishing
// write lock).
requestsToCancel =
new ConcurrentHashMap<Integer, Callback<List<ByteBuffer>>>(requests);
requests.clear();
}
}
} finally {
if (stateReadLockHeld) {
stateLock.readLock().lock();
}
stateLock.writeLock().unlock();
}
// Cancel any pending requests by sending errors to the callbacks:
if ((requestsToCancel != null) && !requestsToCancel.isEmpty()) {
LOG.debug("Removing " + requestsToCancel.size() + " pending request(s).");
for (Callback<List<ByteBuffer>> request : requestsToCancel.values()) {
request.handleError(
cause != null ? cause
: new IOException(getClass().getSimpleName() + " closed"));
}
}
// Close the channel:
if (channelToClose != null) {
ChannelFuture closeFuture = channelToClose.close();
if (awaitCompletion && (closeFuture != null)) {
closeFuture.awaitUninterruptibly(connectTimeoutMillis);
}
}
}
/**
* Netty channels are thread-safe, so there is no need to acquire locks.
* This method is a no-op.
*/
@Override
public void lockChannel() {
}
/**
* Netty channels are thread-safe, so there is no need to acquire locks.
* This method is a no-op.
*/
@Override
public void unlockChannel() {
}
public void close() {
try {
// Close the connection:
stopping = true;
disconnect(true, true, null);
}
finally {
ChannelGroupFuture channelGroupFuture = allChannels.close();
channelGroupFuture.awaitUninterruptibly();
channelFactory.releaseExternalResources();
eventsLogTimer.cancel();
eventsLogTimer.purge();
}
}
@Override
public String getRemoteName() throws IOException {
stateLock.readLock().lock();
try {
return getChannel().getRemoteAddress().toString();
} finally {
stateLock.readLock().unlock();
}
}
/**
* Override as non-synchronized method because the method is thread safe.
*/
@Override
public List<ByteBuffer> transceive(List<ByteBuffer> request)
throws IOException {
try {
CallFuture<List<ByteBuffer>> transceiverFuture = new CallFuture<List<ByteBuffer>>();
transceive(request, transceiverFuture);
return transceiverFuture.get();
} catch (InterruptedException e) {
LOG.debug("failed to get the response", e);
return null;
} catch (ExecutionException e) {
LOG.debug("failed to get the response", e);
return null;
}
}
@Override
public void transceive(List<ByteBuffer> request,
Callback<List<ByteBuffer>> callback) throws IOException {
stateLock.readLock().lock();
try {
int serial = serialGenerator.incrementAndGet();
NettyDataPack dataPack = new NettyDataPack(serial, request);
requests.put(serial, callback);
writeDataPack(dataPack);
} finally {
stateLock.readLock().unlock();
}
}
@Override
public void writeBuffers(List<ByteBuffer> buffers) throws IOException {
stateLock.readLock().lock();
try {
writeDataPack(
new NettyDataPack(serialGenerator.incrementAndGet(), buffers));
} finally {
stateLock.readLock().unlock();
}
}
/**
* Writes a NettyDataPack, reconnecting to the remote peer if necessary.
* NOTE: The stateLock read lock *must* be acquired before calling this
* method.
*
* @param dataPack the data pack to write.
* @throws IOException if an error occurs connecting to the remote peer.
*/
private void writeDataPack(NettyDataPack dataPack) throws IOException {
if (getChannel().isWritable()) {
getChannel().write(dataPack);
sentEvents.incrementAndGet();
} else {
droppedEvents.incrementAndGet();
}
}
@Override
public List<ByteBuffer> readBuffers() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public Protocol getRemote() {
stateLock.readLock().lock();
try {
return remote;
} finally {
stateLock.readLock().unlock();
}
}
@Override
public boolean isConnected() {
stateLock.readLock().lock();
try {
return remote != null;
} finally {
stateLock.readLock().unlock();
}
}
@Override
public void setRemote(Protocol protocol) {
stateLock.writeLock().lock();
try {
this.remote = protocol;
} finally {
stateLock.writeLock().unlock();
}
}
/**
* @return the logicalName
*/
public String getLogicalName() {
return logicalName;
}
/**
* Avro client handler for the Netty transport
*/
class NettyClientAvroHandler extends SimpleChannelUpstreamHandler {
private final String logicalName;
public NettyClientAvroHandler(String logicalName) {
this.logicalName = logicalName;
}
@Override
public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e)
throws Exception {
if (e instanceof ChannelStateEvent) {
LOG.debug(e.toString());
ChannelStateEvent cse = (ChannelStateEvent) e;
if ((cse.getState() == ChannelState.OPEN) && (Boolean.FALSE.equals(cse.getValue()))) {
// Server closed connection; disconnect client side
LOG.debug("Remote peer " + remoteAddr + " [" + this.logicalName + "]" + " closed connection.");
disconnect(false, true, null);
}
}
super.handleUpstream(ctx, e);
}
@Override
public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e)
throws Exception {
allChannels.add(e.getChannel());
super.channelOpen(ctx, e);
}
@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
LOG.debug("Channel closed called on " + remoteAddr + " [" + this.logicalName + "]");
allChannels.remove(e.getChannel());
super.channelClosed(ctx, e);
}
@Override
public void messageReceived(ChannelHandlerContext ctx, final MessageEvent e) {
NettyDataPack dataPack = (NettyDataPack) e.getMessage();
Callback<List<ByteBuffer>> callback = requests.get(dataPack.getSerial());
if (callback == null) {
throw new RuntimeException("Missing previous call info");
}
try {
callback.handleResult(dataPack.getDatas());
} finally {
requests.remove(dataPack.getSerial());
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
LOG.debug("Exception caught on " + remoteAddr + " [" + this.logicalName + "]: " + e.getCause());
disconnect(false, true, e.getCause());
}
}
/**
* Creates threads with unique names based on a specified name prefix.
*/
public static class NettyTransceiverThreadFactory implements ThreadFactory {
private final AtomicInteger threadId = new AtomicInteger(0);
private final String prefix;
/**
* Creates a NettyTransceiverThreadFactory that creates threads with the
* specified name.
*
* @param prefix the name prefix to use for all threads created by this
* ThreadFactory. A unique ID will be appended to this prefix to form
* the final thread name.
*/
public NettyTransceiverThreadFactory(String prefix) {
this.prefix = prefix;
}
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setName(prefix + " " + threadId.incrementAndGet());
return thread;
}
}
}
| |
package io.github.aggumati.frame.executor;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import id.co.vico.appframe.model.JsonResponse;
import id.co.vico.appframe.model.isys.WebScreen;
import id.co.vico.appframe.service.IService;
import id.co.vico.appframe.service.impl.AbstractService;
import id.co.vico.appframe.util.ClassUtil;
import id.co.vico.appframe.util.CommonUtil;
import id.co.vico.appframe.util.StringUtil;
import io.github.aggumati.frame.ClassLoaded;
import io.github.aggumati.frame.ScreenGenerator;
import io.github.aggumati.frame.TemplateLoader;
import io.github.aggumati.frame.formtype.FrameFieldCheck;
import io.github.aggumati.frame.formtype.FrameFieldDate;
import io.github.aggumati.frame.formtype.FrameFieldDateTime;
import io.github.aggumati.frame.formtype.FrameFieldDropdown;
import io.github.aggumati.frame.formtype.FrameFieldEmail;
import io.github.aggumati.frame.formtype.FrameFieldFile;
import io.github.aggumati.frame.formtype.FrameFieldList;
import io.github.aggumati.frame.formtype.FrameFieldObject;
import io.github.aggumati.frame.formtype.FrameFieldPassword;
import io.github.aggumati.frame.formtype.FrameFieldRadio;
import io.github.aggumati.frame.formtype.FrameFieldTable;
import io.github.aggumati.frame.formtype.FrameFieldText;
import io.github.aggumati.frame.formtype.ItemCheck;
import io.github.aggumati.frame.formtype.ItemDropdown;
import io.github.aggumati.frame.formtype.ItemList;
import io.github.aggumati.frame.formtype.ItemRadio;
import io.github.aggumati.frame.list.FrameListColumnCheck;
import io.github.aggumati.frame.list.FrameListColumnDate;
import io.github.aggumati.frame.list.FrameListColumnDatetime;
import io.github.aggumati.frame.list.FrameListColumnDropdown;
import io.github.aggumati.frame.list.FrameListColumnFile;
import io.github.aggumati.frame.list.FrameListColumnText;
import io.github.aggumati.frame.model.AnnotationGenerator;
import io.github.aggumati.frame.model.FieldGenerator;
import io.github.aggumati.frame.model.FormGenerator;
import io.github.aggumati.frame.model.MethodGenerator;
import io.github.aggumati.frame.model.Scafollding;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;
import com.sun.codemodel.ClassType;
import com.sun.codemodel.JAnnotationUse;
import com.sun.codemodel.JDefinedClass;
import com.sun.codemodel.JExpr;
import com.sun.codemodel.JMethod;
import com.sun.codemodel.JMod;
public class FormNewExecutor implements ScreenExecutor {
private String serviceClassName;
private boolean hasFileField;
/**
* need custom.js; date field, date time field;
*/
private boolean hasCustomField;
@Override
public void execute(ScreenGenerator screenGenerator) throws Exception {
WebScreen webScreen = screenGenerator.getWebScreen();
JDefinedClass definedClass = screenGenerator.getDefinedClass();
final String methodName = "form" + StringUtil.toCamelCase(webScreen.getUrl());
final String actionMethodName = "save" + StringUtil.toCamelCase(webScreen.getUrl());
final String pageUrl = "page" + StringUtil.toCamelCase(webScreen.getUrl());
final String service = StringUtil.lowerFirst(screenGenerator.getScafollding().getServiceClassName());
generateService(screenGenerator);
FieldGenerator fieldGen = new FieldGenerator(JMod.PRIVATE,pageUrl, "String" , "pages/" + webScreen.getUrl());
if (!screenGenerator.getClassLoaded().getListFields().contains(fieldGen))definedClass.field(fieldGen.getModifier(), fieldGen.getTypeClass(), pageUrl, JExpr.lit("pages/" + webScreen.getUrl()));
fieldGen = new FieldGenerator(JMod.PRIVATE,service, serviceClassName , null);
if (!screenGenerator.getClassLoaded().getListFields().contains(fieldGen))
definedClass.field(fieldGen.getModifier(), fieldGen.getTypeClass(), service).annotate(Autowired.class);
MethodGenerator tmp = new MethodGenerator();
tmp.setMethodName(methodName);
if (!screenGenerator.getClassLoaded().getListMethod().contains(tmp)) {
JMethod methodForm = definedClass.method(JMod.PUBLIC,org.springframework.web.servlet.ModelAndView.class, methodName);
methodForm.param(org.springframework.ui.ModelMap.class, "model");
methodForm.param(javax.servlet.http.HttpServletRequest.class, "request");
methodForm.param(java.security.Principal.class, "principal");
methodForm.param(javax.servlet.http.HttpSession.class, "httpSession");
methodForm.annotate(org.springframework.web.bind.annotation.RequestMapping.class).param("value", "/" + webScreen.getUrl().toLowerCase());
final String name = "openpage.java";
final Map<String, Object> params = new HashMap<String, Object>();
params.put("pageUrl", pageUrl);
methodForm.body().directStatement(TemplateLoader.loadJavaTemplate(name, params));
}
tmp.setMethodName(actionMethodName);
String urlTableData = "/" + actionMethodName + ".do";
if (!screenGenerator.getClassLoaded().getListMethod().contains(tmp)) {
JMethod methodListData = definedClass.method(JMod.PUBLIC,id.co.vico.appframe.model.JsonResponse.class, actionMethodName);
methodListData.param(Class.forName(screenGenerator.getScafollding().getModelClass()), "dataForm").annotate(org.springframework.web.bind.annotation.ModelAttribute.class).param("value", "dataForm");
methodListData.param(BindingResult.class, "bindingResult");
methodListData.annotate(org.springframework.web.bind.annotation.RequestMapping.class).param("value", urlTableData);
methodListData.annotate(org.springframework.web.bind.annotation.ResponseBody.class);
final String name = "insertDataCtrlBody.java";
final Map<String, Object> params = new HashMap<String, Object>();
params.put("service", service);
params.put("model", screenGenerator.getScafollding().getModelClassName());
methodListData.body().directStatement(TemplateLoader.loadJavaTemplate(name, params));
}
Configuration cfg = new Configuration();
String listTemplate = "src/main/resources/template-gen/form_template.ftl";
String listOutput = Scafollding.pagesFolder + File.separator + webScreen.getUrl() + ".jsp";
// Load the template
Template template = cfg.getTemplate(listTemplate);
Map<String, Object> data = new HashMap<String, Object>();
data.put("url", urlTableData);
data.put("form_name", webScreen.getScreenName());
List<FormGenerator> columnHtml = getColumnHtml(null, screenGenerator.getScafollding().getModelClass());
data.put("columnHtml", columnHtml);
data.put("hasFileField", hasFileField);
data.put("hasCustomField", hasCustomField);
Writer out = new OutputStreamWriter(new FileOutputStream(listOutput));
template.process(data, out);
out.flush();
}
public List<FormGenerator> getColumnHtml(String prefix, String fullClassName) throws Exception {
List<FormGenerator> columnHtml = new ArrayList<FormGenerator>();
Class<?> cls = Class.forName(fullClassName);
List<Field> privateFields = new ArrayList<Field>();
Field[] allFields = cls.getDeclaredFields();
for (int idx = 0; idx < allFields.length; idx++) {
Field fieldTmp = allFields[idx];
String type = null;
FormGenerator formGen = new FormGenerator();
if (fieldTmp.isAnnotationPresent(FrameFieldText.class)) {
type = "text";
} else if (fieldTmp.isAnnotationPresent(FrameFieldPassword.class)) {
type = "password";
} else if (fieldTmp.isAnnotationPresent(FrameFieldEmail.class)) {
type = "email";
// check data type
} else if (fieldTmp.isAnnotationPresent(FrameFieldDate.class)) {
type = "date";
// check data type
if (!fieldTmp.getType().equals(Date.class)) {
throw new Exception(fieldTmp.getName() + " must be a java.util.Date type");
}
hasCustomField = true;
} else if (fieldTmp.isAnnotationPresent(FrameFieldDateTime.class)) {
type = "datetime";
if (!fieldTmp.getType().equals(Date.class)) {
throw new Exception(fieldTmp.getName() + " must be a java.util.Date type");
}
hasCustomField = true;
} else if (fieldTmp.isAnnotationPresent(FrameFieldFile.class)) {
type = "file";
if (!fieldTmp.getType().equals(MultipartFile.class)) {
throw new Exception(fieldTmp.getName() + " must be a org.springframework.web.multipart.MultipartFile type");
}
hasFileField = true;
} else if (fieldTmp.isAnnotationPresent(FrameFieldRadio.class)) {
type = "radio";
if (!fieldTmp.getType().equals(String.class)) {
throw new Exception(fieldTmp.getName() + " must be a java.lang.String type");
}
FrameFieldRadio radioField = fieldTmp.getAnnotation(FrameFieldRadio.class);
for (int i = 0; i < radioField.value().length; i++) {
ItemRadio item = radioField.value()[i];
formGen.addKeyVal(item.key(), item.val());
}
} else if (fieldTmp.isAnnotationPresent(FrameFieldCheck.class)) {
type = "check";
FrameFieldCheck checkField = fieldTmp.getAnnotation(FrameFieldCheck.class);
for (int i = 0; i < checkField.value().length; i++) {
ItemCheck item = checkField.value()[i];
formGen.addKeyVal(item.key(), item.val());
}
} else if (fieldTmp.isAnnotationPresent(FrameFieldDropdown.class)) {
type = "dropdown";
if (!fieldTmp.getType().equals(String.class)) {
throw new Exception(fieldTmp.getName() + " must be a java.lang.String type");
}
FrameFieldDropdown dropdownField = fieldTmp.getAnnotation(FrameFieldDropdown.class);
for (int i = 0; i < dropdownField.value().length; i++) {
ItemDropdown item = dropdownField.value()[i];
formGen.addKeyVal(item.key(), item.val());
}
} else if (fieldTmp.isAnnotationPresent(FrameFieldList.class)) {
type = "list";
if (!fieldTmp.getType().equals(List.class)) {
throw new Exception(fieldTmp.getName() + " must be a java.util.List<String> type");
}
FrameFieldList listField = fieldTmp.getAnnotation(FrameFieldList.class);
for (int i = 0; i < listField.value().length; i++) {
ItemList item = listField.value()[i];
formGen.addKeyVal(item.key(), item.val());
}
} else if (fieldTmp.isAnnotationPresent(FrameFieldObject.class)) {
columnHtml.addAll(getColumnHtml(fieldTmp.getName(), fieldTmp.getType().getName()));
} else if (fieldTmp.isAnnotationPresent(FrameFieldTable.class)) {
type = "table";
if (!fieldTmp.getType().equals(List.class)) {
throw new Exception(fieldTmp.getName() + " must be a java.util.List type");
}
FrameFieldTable listField = fieldTmp.getAnnotation(FrameFieldTable.class);
formGen.setSizeList(listField.page());
Type genericFieldType = fieldTmp.getGenericType();
Class<?> fieldArgClass = null;
if(genericFieldType instanceof ParameterizedType){
ParameterizedType aType = (ParameterizedType) genericFieldType;
Type[] fieldArgTypes = aType.getActualTypeArguments();
for(Type fieldArgType : fieldArgTypes){
fieldArgClass = (Class<?>) fieldArgType;
}
}
if (fieldArgClass == null) {
throw new Exception("Plese use correct class field type");
}
formGen.setTable(getInnerTableForm(fieldTmp.getName(), fieldArgClass.getName()));
}
if (CommonUtil.isNotNullOrEmpty(type)) {
if (CommonUtil.isNotNullOrEmpty(prefix)) {
formGen.setName(
StringUtil.splitCamelCase(StringUtil.lowerFirst( prefix)) + "." +
StringUtil.splitCamelCase(StringUtil.lowerFirst( fieldTmp.getName())));
if (CommonUtil.isNullOrEmpty(formGen.getLabel()))
formGen.setLabel((prefix + " - " + StringUtil.splitCamelCaseWithSpace(fieldTmp.getName())).toUpperCase());
} else {
formGen.setName(StringUtil.splitCamelCase(StringUtil.lowerFirst( fieldTmp.getName())));
if (CommonUtil.isNullOrEmpty(formGen.getLabel()))
formGen.setLabel(StringUtil.splitCamelCaseWithSpace(fieldTmp.getName()).toUpperCase());
}
formGen.setType(type);
columnHtml.add(formGen);
privateFields.add(fieldTmp);
}
}
return columnHtml;
}
private List<FormGenerator> getInnerTableForm(String prefix, String fullClassName) throws Exception {
List<FormGenerator> columnHtml = new ArrayList<FormGenerator>();
Class<?> cls = Class.forName(fullClassName);
List<Field> privateFields = new ArrayList<Field>();
Field[] allFields = cls.getDeclaredFields();
for (int idx = 0; idx < allFields.length; idx++) {
Field fieldTmp = allFields[idx];
String type = null;
FormGenerator formGen = new FormGenerator();
if (fieldTmp.isAnnotationPresent(FrameListColumnText.class)) {
type = "tabletext";
} else if (fieldTmp.isAnnotationPresent(FrameListColumnDate.class)) {
type = "tabledate";
if (!fieldTmp.getType().equals(Date.class)) {
throw new Exception(fieldTmp.getName() + " must be a java.util.Date type");
}
hasCustomField = true;
} else if (fieldTmp.isAnnotationPresent(FrameListColumnDatetime.class)) {
type = "tabledatetime";
if (!fieldTmp.getType().equals(Date.class)) {
throw new Exception(fieldTmp.getName() + " must be a java.util.Date type");
}
hasCustomField = true;
} else if (fieldTmp.isAnnotationPresent(FrameListColumnFile.class)) {
type = "tablefile";
if (!fieldTmp.getType().equals(MultipartFile.class)) {
throw new Exception(fieldTmp.getName() + " must be a org.springframework.web.multipart.MultipartFile type");
}
hasFileField = true;
} else if (fieldTmp.isAnnotationPresent(FrameListColumnCheck.class)) {
type = "tablecheck";
FrameListColumnCheck tablecheck = fieldTmp.getAnnotation(FrameListColumnCheck.class);
formGen.setValue(tablecheck.value());
} else if (fieldTmp.isAnnotationPresent(FrameListColumnDropdown.class)) {
type = "tabledropdown";
if (!fieldTmp.getType().equals(String.class)) {
throw new Exception(fieldTmp.getName() + " must be a java.lang.String type");
}
FrameListColumnDropdown dropdownField = fieldTmp.getAnnotation(FrameListColumnDropdown.class);
for (int i = 0; i < dropdownField.value().length; i++) {
ItemDropdown item = dropdownField.value()[i];
formGen.addKeyVal(item.key(), item.val());
}
}
if (CommonUtil.isNotNullOrEmpty(type)) {
if (CommonUtil.isNotNullOrEmpty(prefix)) {
formGen.setName(
StringUtil.splitCamelCase(StringUtil.lowerFirst( prefix)) + "." +
StringUtil.splitCamelCase(StringUtil.lowerFirst( fieldTmp.getName())));
} else {
formGen.setName(StringUtil.splitCamelCase(StringUtil.lowerFirst( fieldTmp.getName())));
}
if (CommonUtil.isNullOrEmpty(formGen.getLabel()))
formGen.setLabel(StringUtil.splitCamelCaseWithSpace(fieldTmp.getName()).toUpperCase());
formGen.setType(type);
columnHtml.add(formGen);
privateFields.add(fieldTmp);
}
}
return columnHtml;
}
private void generateService(ScreenGenerator screenGenerator) throws ClassNotFoundException, IOException, TemplateException {
serviceClassName = Scafollding.packageGroup + "." + screenGenerator.getScafollding().getContext() + ".service." + screenGenerator.getScafollding().getServiceClassName();
final String serviceFileName = String.format("%s\\%s.java", Scafollding.javaFolder, ClassUtil.classToFile(serviceClassName));
// create service interface
ClassLoaded classLoaded = new ClassLoaded(serviceFileName, serviceClassName, ClassType.INTERFACE);
JDefinedClass serviceDefinedClass = classLoaded.openClass();
serviceDefinedClass._extends(IService.class);
MethodGenerator tmp = new MethodGenerator();
final String methodInsert = "insert"+StringUtil.capitalizeFirst(screenGenerator.getScafollding().getModelClassName());
tmp.setMethodName(methodInsert);
if (!classLoaded.getListMethod().contains(tmp)) {
JMethod methodList = serviceDefinedClass.method(JMod.PUBLIC,JsonResponse.class, methodInsert);
methodList.param(screenGenerator.getScafollding().getModel(), "model");
}
serviceDefinedClass.owner().build(new File(Scafollding.javaFolder));
// Compile source file.
ClassUtil.compileClass(serviceFileName);
// create service impl
final String serviceImplClassName = Scafollding.packageGroup + "." + screenGenerator.getScafollding().getContext() + ".service.impl." + screenGenerator.getScafollding().getServiceImplClassName();
final String serviceImplFileName = String.format("%s\\%s.java", Scafollding.javaFolder, ClassUtil.classToFile(serviceImplClassName));
ClassLoaded classLoadedImpl = new ClassLoaded(serviceImplFileName, serviceImplClassName);
JDefinedClass serviceImplDefinedClass = classLoadedImpl.openClass();
final String mapperName = screenGenerator.getScafollding().getMapperClassName();
if (CommonUtil.isNotNullOrEmpty(mapperName)) {
FieldGenerator fieldGen = new FieldGenerator(JMod.PRIVATE,StringUtil.lowerFirst(mapperName), null, null);
if (!classLoadedImpl.getListFields().contains(fieldGen))serviceImplDefinedClass.field(JMod.PRIVATE, screenGenerator.getScafollding().getMapper(), StringUtil.lowerFirst(mapperName)).annotate(Autowired.class);
}
serviceImplDefinedClass._implements(Class.forName(screenGenerator.getScafollding().getServiceClass()));
serviceImplDefinedClass._extends(AbstractService.class);
AnnotationGenerator gen = new AnnotationGenerator();
gen.setName("Service");
if (!classLoadedImpl.getListAnnotatios().contains(gen))
serviceImplDefinedClass.annotate(Service.class);
tmp.setMethodName(methodInsert);
if (!classLoaded.getListMethod().contains(tmp)) {
JMethod methodList = serviceImplDefinedClass.method(JMod.PUBLIC,JsonResponse.class, methodInsert);
methodList.param(screenGenerator.getScafollding().getModel(), "model");
JAnnotationUse annotate = methodList.annotate(Transactional.class);
annotate.param("rollbackFor", Exception.class);
if (CommonUtil.isNotNullOrEmpty(mapperName)) {
final String name = "insertData.java";
Map<String, Object> params = new HashMap<String, Object>();
params.put("mapperClass", StringUtil.lowerFirst(mapperName));
methodList.body().directStatement(TemplateLoader.loadJavaTemplate(name, params));
} else {
final String name = "insertDataNoMapper.java";
methodList.body().directStatement(TemplateLoader.loadJavaTemplate(name));
}
}
serviceImplDefinedClass.owner().build(new File(Scafollding.javaFolder));
ClassUtil.compileClass(serviceImplFileName);
}
public String getServiceClassName() {
return serviceClassName;
}
public boolean isHasFileField() {
return hasFileField;
}
public boolean isHasCustomField() {
return hasCustomField;
}
}
| |
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.schemaorg.core;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multimap;
import com.google.schemaorg.SchemaOrgType;
import com.google.schemaorg.SchemaOrgTypeImpl;
import com.google.schemaorg.ValueType;
import com.google.schemaorg.core.datatype.Date;
import com.google.schemaorg.core.datatype.DateTime;
import com.google.schemaorg.core.datatype.Integer;
import com.google.schemaorg.core.datatype.Number;
import com.google.schemaorg.core.datatype.Text;
import com.google.schemaorg.core.datatype.URL;
import com.google.schemaorg.goog.GoogConstants;
import com.google.schemaorg.goog.PopularityScoreSpecification;
/** Implementation of {@link SoftwareSourceCode}. */
public class SoftwareSourceCodeImpl extends CreativeWorkImpl implements SoftwareSourceCode {
private static final ImmutableSet<String> PROPERTY_SET = initializePropertySet();
private static ImmutableSet<String> initializePropertySet() {
ImmutableSet.Builder<String> builder = ImmutableSet.builder();
builder.add(CoreConstants.PROPERTY_ABOUT);
builder.add(CoreConstants.PROPERTY_ACCESSIBILITY_API);
builder.add(CoreConstants.PROPERTY_ACCESSIBILITY_CONTROL);
builder.add(CoreConstants.PROPERTY_ACCESSIBILITY_FEATURE);
builder.add(CoreConstants.PROPERTY_ACCESSIBILITY_HAZARD);
builder.add(CoreConstants.PROPERTY_ACCOUNTABLE_PERSON);
builder.add(CoreConstants.PROPERTY_ADDITIONAL_TYPE);
builder.add(CoreConstants.PROPERTY_AGGREGATE_RATING);
builder.add(CoreConstants.PROPERTY_ALTERNATE_NAME);
builder.add(CoreConstants.PROPERTY_ALTERNATIVE_HEADLINE);
builder.add(CoreConstants.PROPERTY_ASSOCIATED_MEDIA);
builder.add(CoreConstants.PROPERTY_AUDIENCE);
builder.add(CoreConstants.PROPERTY_AUDIO);
builder.add(CoreConstants.PROPERTY_AUTHOR);
builder.add(CoreConstants.PROPERTY_AWARD);
builder.add(CoreConstants.PROPERTY_AWARDS);
builder.add(CoreConstants.PROPERTY_CHARACTER);
builder.add(CoreConstants.PROPERTY_CITATION);
builder.add(CoreConstants.PROPERTY_CODE_REPOSITORY);
builder.add(CoreConstants.PROPERTY_CODE_SAMPLE_TYPE);
builder.add(CoreConstants.PROPERTY_COMMENT);
builder.add(CoreConstants.PROPERTY_COMMENT_COUNT);
builder.add(CoreConstants.PROPERTY_CONTENT_LOCATION);
builder.add(CoreConstants.PROPERTY_CONTENT_RATING);
builder.add(CoreConstants.PROPERTY_CONTRIBUTOR);
builder.add(CoreConstants.PROPERTY_COPYRIGHT_HOLDER);
builder.add(CoreConstants.PROPERTY_COPYRIGHT_YEAR);
builder.add(CoreConstants.PROPERTY_CREATOR);
builder.add(CoreConstants.PROPERTY_DATE_CREATED);
builder.add(CoreConstants.PROPERTY_DATE_MODIFIED);
builder.add(CoreConstants.PROPERTY_DATE_PUBLISHED);
builder.add(CoreConstants.PROPERTY_DESCRIPTION);
builder.add(CoreConstants.PROPERTY_DISCUSSION_URL);
builder.add(CoreConstants.PROPERTY_EDITOR);
builder.add(CoreConstants.PROPERTY_EDUCATIONAL_ALIGNMENT);
builder.add(CoreConstants.PROPERTY_EDUCATIONAL_USE);
builder.add(CoreConstants.PROPERTY_ENCODING);
builder.add(CoreConstants.PROPERTY_ENCODINGS);
builder.add(CoreConstants.PROPERTY_EXAMPLE_OF_WORK);
builder.add(CoreConstants.PROPERTY_FILE_FORMAT);
builder.add(CoreConstants.PROPERTY_GENRE);
builder.add(CoreConstants.PROPERTY_HAS_PART);
builder.add(CoreConstants.PROPERTY_HEADLINE);
builder.add(CoreConstants.PROPERTY_IMAGE);
builder.add(CoreConstants.PROPERTY_IN_LANGUAGE);
builder.add(CoreConstants.PROPERTY_INTERACTION_STATISTIC);
builder.add(CoreConstants.PROPERTY_INTERACTIVITY_TYPE);
builder.add(CoreConstants.PROPERTY_IS_BASED_ON_URL);
builder.add(CoreConstants.PROPERTY_IS_FAMILY_FRIENDLY);
builder.add(CoreConstants.PROPERTY_IS_PART_OF);
builder.add(CoreConstants.PROPERTY_KEYWORDS);
builder.add(CoreConstants.PROPERTY_LEARNING_RESOURCE_TYPE);
builder.add(CoreConstants.PROPERTY_LICENSE);
builder.add(CoreConstants.PROPERTY_LOCATION_CREATED);
builder.add(CoreConstants.PROPERTY_MAIN_ENTITY);
builder.add(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE);
builder.add(CoreConstants.PROPERTY_MENTIONS);
builder.add(CoreConstants.PROPERTY_NAME);
builder.add(CoreConstants.PROPERTY_OFFERS);
builder.add(CoreConstants.PROPERTY_POSITION);
builder.add(CoreConstants.PROPERTY_POTENTIAL_ACTION);
builder.add(CoreConstants.PROPERTY_PRODUCER);
builder.add(CoreConstants.PROPERTY_PROGRAMMING_LANGUAGE);
builder.add(CoreConstants.PROPERTY_PROVIDER);
builder.add(CoreConstants.PROPERTY_PUBLICATION);
builder.add(CoreConstants.PROPERTY_PUBLISHER);
builder.add(CoreConstants.PROPERTY_PUBLISHING_PRINCIPLES);
builder.add(CoreConstants.PROPERTY_RECORDED_AT);
builder.add(CoreConstants.PROPERTY_RELEASED_EVENT);
builder.add(CoreConstants.PROPERTY_REVIEW);
builder.add(CoreConstants.PROPERTY_REVIEWS);
builder.add(CoreConstants.PROPERTY_RUNTIME);
builder.add(CoreConstants.PROPERTY_RUNTIME_PLATFORM);
builder.add(CoreConstants.PROPERTY_SAME_AS);
builder.add(CoreConstants.PROPERTY_SAMPLE_TYPE);
builder.add(CoreConstants.PROPERTY_SCHEMA_VERSION);
builder.add(CoreConstants.PROPERTY_SOURCE_ORGANIZATION);
builder.add(CoreConstants.PROPERTY_TARGET_PRODUCT);
builder.add(CoreConstants.PROPERTY_TEXT);
builder.add(CoreConstants.PROPERTY_THUMBNAIL_URL);
builder.add(CoreConstants.PROPERTY_TIME_REQUIRED);
builder.add(CoreConstants.PROPERTY_TRANSLATOR);
builder.add(CoreConstants.PROPERTY_TYPICAL_AGE_RANGE);
builder.add(CoreConstants.PROPERTY_URL);
builder.add(CoreConstants.PROPERTY_VERSION);
builder.add(CoreConstants.PROPERTY_VIDEO);
builder.add(CoreConstants.PROPERTY_WORK_EXAMPLE);
builder.add(GoogConstants.PROPERTY_DETAILED_DESCRIPTION);
builder.add(GoogConstants.PROPERTY_POPULARITY_SCORE);
return builder.build();
}
static final class BuilderImpl extends SchemaOrgTypeImpl.BuilderImpl<SoftwareSourceCode.Builder>
implements SoftwareSourceCode.Builder {
@Override
public SoftwareSourceCode.Builder addAbout(Thing value) {
return addProperty(CoreConstants.PROPERTY_ABOUT, value);
}
@Override
public SoftwareSourceCode.Builder addAbout(Thing.Builder value) {
return addProperty(CoreConstants.PROPERTY_ABOUT, value.build());
}
@Override
public SoftwareSourceCode.Builder addAbout(String value) {
return addProperty(CoreConstants.PROPERTY_ABOUT, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addAccessibilityAPI(Text value) {
return addProperty(CoreConstants.PROPERTY_ACCESSIBILITY_API, value);
}
@Override
public SoftwareSourceCode.Builder addAccessibilityAPI(String value) {
return addProperty(CoreConstants.PROPERTY_ACCESSIBILITY_API, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addAccessibilityControl(Text value) {
return addProperty(CoreConstants.PROPERTY_ACCESSIBILITY_CONTROL, value);
}
@Override
public SoftwareSourceCode.Builder addAccessibilityControl(String value) {
return addProperty(CoreConstants.PROPERTY_ACCESSIBILITY_CONTROL, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addAccessibilityFeature(Text value) {
return addProperty(CoreConstants.PROPERTY_ACCESSIBILITY_FEATURE, value);
}
@Override
public SoftwareSourceCode.Builder addAccessibilityFeature(String value) {
return addProperty(CoreConstants.PROPERTY_ACCESSIBILITY_FEATURE, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addAccessibilityHazard(Text value) {
return addProperty(CoreConstants.PROPERTY_ACCESSIBILITY_HAZARD, value);
}
@Override
public SoftwareSourceCode.Builder addAccessibilityHazard(String value) {
return addProperty(CoreConstants.PROPERTY_ACCESSIBILITY_HAZARD, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addAccountablePerson(Person value) {
return addProperty(CoreConstants.PROPERTY_ACCOUNTABLE_PERSON, value);
}
@Override
public SoftwareSourceCode.Builder addAccountablePerson(Person.Builder value) {
return addProperty(CoreConstants.PROPERTY_ACCOUNTABLE_PERSON, value.build());
}
@Override
public SoftwareSourceCode.Builder addAccountablePerson(String value) {
return addProperty(CoreConstants.PROPERTY_ACCOUNTABLE_PERSON, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addAdditionalType(URL value) {
return addProperty(CoreConstants.PROPERTY_ADDITIONAL_TYPE, value);
}
@Override
public SoftwareSourceCode.Builder addAdditionalType(String value) {
return addProperty(CoreConstants.PROPERTY_ADDITIONAL_TYPE, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addAggregateRating(AggregateRating value) {
return addProperty(CoreConstants.PROPERTY_AGGREGATE_RATING, value);
}
@Override
public SoftwareSourceCode.Builder addAggregateRating(AggregateRating.Builder value) {
return addProperty(CoreConstants.PROPERTY_AGGREGATE_RATING, value.build());
}
@Override
public SoftwareSourceCode.Builder addAggregateRating(String value) {
return addProperty(CoreConstants.PROPERTY_AGGREGATE_RATING, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addAlternateName(Text value) {
return addProperty(CoreConstants.PROPERTY_ALTERNATE_NAME, value);
}
@Override
public SoftwareSourceCode.Builder addAlternateName(String value) {
return addProperty(CoreConstants.PROPERTY_ALTERNATE_NAME, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addAlternativeHeadline(Text value) {
return addProperty(CoreConstants.PROPERTY_ALTERNATIVE_HEADLINE, value);
}
@Override
public SoftwareSourceCode.Builder addAlternativeHeadline(String value) {
return addProperty(CoreConstants.PROPERTY_ALTERNATIVE_HEADLINE, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addAssociatedMedia(MediaObject value) {
return addProperty(CoreConstants.PROPERTY_ASSOCIATED_MEDIA, value);
}
@Override
public SoftwareSourceCode.Builder addAssociatedMedia(MediaObject.Builder value) {
return addProperty(CoreConstants.PROPERTY_ASSOCIATED_MEDIA, value.build());
}
@Override
public SoftwareSourceCode.Builder addAssociatedMedia(String value) {
return addProperty(CoreConstants.PROPERTY_ASSOCIATED_MEDIA, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addAudience(Audience value) {
return addProperty(CoreConstants.PROPERTY_AUDIENCE, value);
}
@Override
public SoftwareSourceCode.Builder addAudience(Audience.Builder value) {
return addProperty(CoreConstants.PROPERTY_AUDIENCE, value.build());
}
@Override
public SoftwareSourceCode.Builder addAudience(String value) {
return addProperty(CoreConstants.PROPERTY_AUDIENCE, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addAudio(AudioObject value) {
return addProperty(CoreConstants.PROPERTY_AUDIO, value);
}
@Override
public SoftwareSourceCode.Builder addAudio(AudioObject.Builder value) {
return addProperty(CoreConstants.PROPERTY_AUDIO, value.build());
}
@Override
public SoftwareSourceCode.Builder addAudio(String value) {
return addProperty(CoreConstants.PROPERTY_AUDIO, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addAuthor(Organization value) {
return addProperty(CoreConstants.PROPERTY_AUTHOR, value);
}
@Override
public SoftwareSourceCode.Builder addAuthor(Organization.Builder value) {
return addProperty(CoreConstants.PROPERTY_AUTHOR, value.build());
}
@Override
public SoftwareSourceCode.Builder addAuthor(Person value) {
return addProperty(CoreConstants.PROPERTY_AUTHOR, value);
}
@Override
public SoftwareSourceCode.Builder addAuthor(Person.Builder value) {
return addProperty(CoreConstants.PROPERTY_AUTHOR, value.build());
}
@Override
public SoftwareSourceCode.Builder addAuthor(String value) {
return addProperty(CoreConstants.PROPERTY_AUTHOR, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addAward(Text value) {
return addProperty(CoreConstants.PROPERTY_AWARD, value);
}
@Override
public SoftwareSourceCode.Builder addAward(String value) {
return addProperty(CoreConstants.PROPERTY_AWARD, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addAwards(Text value) {
return addProperty(CoreConstants.PROPERTY_AWARDS, value);
}
@Override
public SoftwareSourceCode.Builder addAwards(String value) {
return addProperty(CoreConstants.PROPERTY_AWARDS, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addCharacter(Person value) {
return addProperty(CoreConstants.PROPERTY_CHARACTER, value);
}
@Override
public SoftwareSourceCode.Builder addCharacter(Person.Builder value) {
return addProperty(CoreConstants.PROPERTY_CHARACTER, value.build());
}
@Override
public SoftwareSourceCode.Builder addCharacter(String value) {
return addProperty(CoreConstants.PROPERTY_CHARACTER, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addCitation(CreativeWork value) {
return addProperty(CoreConstants.PROPERTY_CITATION, value);
}
@Override
public SoftwareSourceCode.Builder addCitation(CreativeWork.Builder value) {
return addProperty(CoreConstants.PROPERTY_CITATION, value.build());
}
@Override
public SoftwareSourceCode.Builder addCitation(Text value) {
return addProperty(CoreConstants.PROPERTY_CITATION, value);
}
@Override
public SoftwareSourceCode.Builder addCitation(String value) {
return addProperty(CoreConstants.PROPERTY_CITATION, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addCodeRepository(URL value) {
return addProperty(CoreConstants.PROPERTY_CODE_REPOSITORY, value);
}
@Override
public SoftwareSourceCode.Builder addCodeRepository(String value) {
return addProperty(CoreConstants.PROPERTY_CODE_REPOSITORY, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addCodeSampleType(Text value) {
return addProperty(CoreConstants.PROPERTY_CODE_SAMPLE_TYPE, value);
}
@Override
public SoftwareSourceCode.Builder addCodeSampleType(String value) {
return addProperty(CoreConstants.PROPERTY_CODE_SAMPLE_TYPE, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addComment(Comment value) {
return addProperty(CoreConstants.PROPERTY_COMMENT, value);
}
@Override
public SoftwareSourceCode.Builder addComment(Comment.Builder value) {
return addProperty(CoreConstants.PROPERTY_COMMENT, value.build());
}
@Override
public SoftwareSourceCode.Builder addComment(String value) {
return addProperty(CoreConstants.PROPERTY_COMMENT, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addCommentCount(Integer value) {
return addProperty(CoreConstants.PROPERTY_COMMENT_COUNT, value);
}
@Override
public SoftwareSourceCode.Builder addCommentCount(String value) {
return addProperty(CoreConstants.PROPERTY_COMMENT_COUNT, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addContentLocation(Place value) {
return addProperty(CoreConstants.PROPERTY_CONTENT_LOCATION, value);
}
@Override
public SoftwareSourceCode.Builder addContentLocation(Place.Builder value) {
return addProperty(CoreConstants.PROPERTY_CONTENT_LOCATION, value.build());
}
@Override
public SoftwareSourceCode.Builder addContentLocation(String value) {
return addProperty(CoreConstants.PROPERTY_CONTENT_LOCATION, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addContentRating(Text value) {
return addProperty(CoreConstants.PROPERTY_CONTENT_RATING, value);
}
@Override
public SoftwareSourceCode.Builder addContentRating(String value) {
return addProperty(CoreConstants.PROPERTY_CONTENT_RATING, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addContributor(Organization value) {
return addProperty(CoreConstants.PROPERTY_CONTRIBUTOR, value);
}
@Override
public SoftwareSourceCode.Builder addContributor(Organization.Builder value) {
return addProperty(CoreConstants.PROPERTY_CONTRIBUTOR, value.build());
}
@Override
public SoftwareSourceCode.Builder addContributor(Person value) {
return addProperty(CoreConstants.PROPERTY_CONTRIBUTOR, value);
}
@Override
public SoftwareSourceCode.Builder addContributor(Person.Builder value) {
return addProperty(CoreConstants.PROPERTY_CONTRIBUTOR, value.build());
}
@Override
public SoftwareSourceCode.Builder addContributor(String value) {
return addProperty(CoreConstants.PROPERTY_CONTRIBUTOR, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addCopyrightHolder(Organization value) {
return addProperty(CoreConstants.PROPERTY_COPYRIGHT_HOLDER, value);
}
@Override
public SoftwareSourceCode.Builder addCopyrightHolder(Organization.Builder value) {
return addProperty(CoreConstants.PROPERTY_COPYRIGHT_HOLDER, value.build());
}
@Override
public SoftwareSourceCode.Builder addCopyrightHolder(Person value) {
return addProperty(CoreConstants.PROPERTY_COPYRIGHT_HOLDER, value);
}
@Override
public SoftwareSourceCode.Builder addCopyrightHolder(Person.Builder value) {
return addProperty(CoreConstants.PROPERTY_COPYRIGHT_HOLDER, value.build());
}
@Override
public SoftwareSourceCode.Builder addCopyrightHolder(String value) {
return addProperty(CoreConstants.PROPERTY_COPYRIGHT_HOLDER, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addCopyrightYear(Number value) {
return addProperty(CoreConstants.PROPERTY_COPYRIGHT_YEAR, value);
}
@Override
public SoftwareSourceCode.Builder addCopyrightYear(String value) {
return addProperty(CoreConstants.PROPERTY_COPYRIGHT_YEAR, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addCreator(Organization value) {
return addProperty(CoreConstants.PROPERTY_CREATOR, value);
}
@Override
public SoftwareSourceCode.Builder addCreator(Organization.Builder value) {
return addProperty(CoreConstants.PROPERTY_CREATOR, value.build());
}
@Override
public SoftwareSourceCode.Builder addCreator(Person value) {
return addProperty(CoreConstants.PROPERTY_CREATOR, value);
}
@Override
public SoftwareSourceCode.Builder addCreator(Person.Builder value) {
return addProperty(CoreConstants.PROPERTY_CREATOR, value.build());
}
@Override
public SoftwareSourceCode.Builder addCreator(String value) {
return addProperty(CoreConstants.PROPERTY_CREATOR, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addDateCreated(Date value) {
return addProperty(CoreConstants.PROPERTY_DATE_CREATED, value);
}
@Override
public SoftwareSourceCode.Builder addDateCreated(DateTime value) {
return addProperty(CoreConstants.PROPERTY_DATE_CREATED, value);
}
@Override
public SoftwareSourceCode.Builder addDateCreated(String value) {
return addProperty(CoreConstants.PROPERTY_DATE_CREATED, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addDateModified(Date value) {
return addProperty(CoreConstants.PROPERTY_DATE_MODIFIED, value);
}
@Override
public SoftwareSourceCode.Builder addDateModified(DateTime value) {
return addProperty(CoreConstants.PROPERTY_DATE_MODIFIED, value);
}
@Override
public SoftwareSourceCode.Builder addDateModified(String value) {
return addProperty(CoreConstants.PROPERTY_DATE_MODIFIED, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addDatePublished(Date value) {
return addProperty(CoreConstants.PROPERTY_DATE_PUBLISHED, value);
}
@Override
public SoftwareSourceCode.Builder addDatePublished(String value) {
return addProperty(CoreConstants.PROPERTY_DATE_PUBLISHED, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addDescription(Text value) {
return addProperty(CoreConstants.PROPERTY_DESCRIPTION, value);
}
@Override
public SoftwareSourceCode.Builder addDescription(String value) {
return addProperty(CoreConstants.PROPERTY_DESCRIPTION, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addDiscussionUrl(URL value) {
return addProperty(CoreConstants.PROPERTY_DISCUSSION_URL, value);
}
@Override
public SoftwareSourceCode.Builder addDiscussionUrl(String value) {
return addProperty(CoreConstants.PROPERTY_DISCUSSION_URL, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addEditor(Person value) {
return addProperty(CoreConstants.PROPERTY_EDITOR, value);
}
@Override
public SoftwareSourceCode.Builder addEditor(Person.Builder value) {
return addProperty(CoreConstants.PROPERTY_EDITOR, value.build());
}
@Override
public SoftwareSourceCode.Builder addEditor(String value) {
return addProperty(CoreConstants.PROPERTY_EDITOR, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addEducationalAlignment(AlignmentObject value) {
return addProperty(CoreConstants.PROPERTY_EDUCATIONAL_ALIGNMENT, value);
}
@Override
public SoftwareSourceCode.Builder addEducationalAlignment(AlignmentObject.Builder value) {
return addProperty(CoreConstants.PROPERTY_EDUCATIONAL_ALIGNMENT, value.build());
}
@Override
public SoftwareSourceCode.Builder addEducationalAlignment(String value) {
return addProperty(CoreConstants.PROPERTY_EDUCATIONAL_ALIGNMENT, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addEducationalUse(Text value) {
return addProperty(CoreConstants.PROPERTY_EDUCATIONAL_USE, value);
}
@Override
public SoftwareSourceCode.Builder addEducationalUse(String value) {
return addProperty(CoreConstants.PROPERTY_EDUCATIONAL_USE, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addEncoding(MediaObject value) {
return addProperty(CoreConstants.PROPERTY_ENCODING, value);
}
@Override
public SoftwareSourceCode.Builder addEncoding(MediaObject.Builder value) {
return addProperty(CoreConstants.PROPERTY_ENCODING, value.build());
}
@Override
public SoftwareSourceCode.Builder addEncoding(String value) {
return addProperty(CoreConstants.PROPERTY_ENCODING, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addEncodings(MediaObject value) {
return addProperty(CoreConstants.PROPERTY_ENCODINGS, value);
}
@Override
public SoftwareSourceCode.Builder addEncodings(MediaObject.Builder value) {
return addProperty(CoreConstants.PROPERTY_ENCODINGS, value.build());
}
@Override
public SoftwareSourceCode.Builder addEncodings(String value) {
return addProperty(CoreConstants.PROPERTY_ENCODINGS, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addExampleOfWork(CreativeWork value) {
return addProperty(CoreConstants.PROPERTY_EXAMPLE_OF_WORK, value);
}
@Override
public SoftwareSourceCode.Builder addExampleOfWork(CreativeWork.Builder value) {
return addProperty(CoreConstants.PROPERTY_EXAMPLE_OF_WORK, value.build());
}
@Override
public SoftwareSourceCode.Builder addExampleOfWork(String value) {
return addProperty(CoreConstants.PROPERTY_EXAMPLE_OF_WORK, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addFileFormat(Text value) {
return addProperty(CoreConstants.PROPERTY_FILE_FORMAT, value);
}
@Override
public SoftwareSourceCode.Builder addFileFormat(String value) {
return addProperty(CoreConstants.PROPERTY_FILE_FORMAT, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addGenre(Text value) {
return addProperty(CoreConstants.PROPERTY_GENRE, value);
}
@Override
public SoftwareSourceCode.Builder addGenre(URL value) {
return addProperty(CoreConstants.PROPERTY_GENRE, value);
}
@Override
public SoftwareSourceCode.Builder addGenre(String value) {
return addProperty(CoreConstants.PROPERTY_GENRE, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addHasPart(CreativeWork value) {
return addProperty(CoreConstants.PROPERTY_HAS_PART, value);
}
@Override
public SoftwareSourceCode.Builder addHasPart(CreativeWork.Builder value) {
return addProperty(CoreConstants.PROPERTY_HAS_PART, value.build());
}
@Override
public SoftwareSourceCode.Builder addHasPart(String value) {
return addProperty(CoreConstants.PROPERTY_HAS_PART, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addHeadline(Text value) {
return addProperty(CoreConstants.PROPERTY_HEADLINE, value);
}
@Override
public SoftwareSourceCode.Builder addHeadline(String value) {
return addProperty(CoreConstants.PROPERTY_HEADLINE, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addImage(ImageObject value) {
return addProperty(CoreConstants.PROPERTY_IMAGE, value);
}
@Override
public SoftwareSourceCode.Builder addImage(ImageObject.Builder value) {
return addProperty(CoreConstants.PROPERTY_IMAGE, value.build());
}
@Override
public SoftwareSourceCode.Builder addImage(URL value) {
return addProperty(CoreConstants.PROPERTY_IMAGE, value);
}
@Override
public SoftwareSourceCode.Builder addImage(String value) {
return addProperty(CoreConstants.PROPERTY_IMAGE, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addInLanguage(Language value) {
return addProperty(CoreConstants.PROPERTY_IN_LANGUAGE, value);
}
@Override
public SoftwareSourceCode.Builder addInLanguage(Language.Builder value) {
return addProperty(CoreConstants.PROPERTY_IN_LANGUAGE, value.build());
}
@Override
public SoftwareSourceCode.Builder addInLanguage(Text value) {
return addProperty(CoreConstants.PROPERTY_IN_LANGUAGE, value);
}
@Override
public SoftwareSourceCode.Builder addInLanguage(String value) {
return addProperty(CoreConstants.PROPERTY_IN_LANGUAGE, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addInteractionStatistic(InteractionCounter value) {
return addProperty(CoreConstants.PROPERTY_INTERACTION_STATISTIC, value);
}
@Override
public SoftwareSourceCode.Builder addInteractionStatistic(InteractionCounter.Builder value) {
return addProperty(CoreConstants.PROPERTY_INTERACTION_STATISTIC, value.build());
}
@Override
public SoftwareSourceCode.Builder addInteractionStatistic(String value) {
return addProperty(CoreConstants.PROPERTY_INTERACTION_STATISTIC, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addInteractivityType(Text value) {
return addProperty(CoreConstants.PROPERTY_INTERACTIVITY_TYPE, value);
}
@Override
public SoftwareSourceCode.Builder addInteractivityType(String value) {
return addProperty(CoreConstants.PROPERTY_INTERACTIVITY_TYPE, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addIsBasedOnUrl(URL value) {
return addProperty(CoreConstants.PROPERTY_IS_BASED_ON_URL, value);
}
@Override
public SoftwareSourceCode.Builder addIsBasedOnUrl(String value) {
return addProperty(CoreConstants.PROPERTY_IS_BASED_ON_URL, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addIsFamilyFriendly(Boolean value) {
return addProperty(CoreConstants.PROPERTY_IS_FAMILY_FRIENDLY, value);
}
@Override
public SoftwareSourceCode.Builder addIsFamilyFriendly(String value) {
return addProperty(CoreConstants.PROPERTY_IS_FAMILY_FRIENDLY, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addIsPartOf(CreativeWork value) {
return addProperty(CoreConstants.PROPERTY_IS_PART_OF, value);
}
@Override
public SoftwareSourceCode.Builder addIsPartOf(CreativeWork.Builder value) {
return addProperty(CoreConstants.PROPERTY_IS_PART_OF, value.build());
}
@Override
public SoftwareSourceCode.Builder addIsPartOf(String value) {
return addProperty(CoreConstants.PROPERTY_IS_PART_OF, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addKeywords(Text value) {
return addProperty(CoreConstants.PROPERTY_KEYWORDS, value);
}
@Override
public SoftwareSourceCode.Builder addKeywords(String value) {
return addProperty(CoreConstants.PROPERTY_KEYWORDS, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addLearningResourceType(Text value) {
return addProperty(CoreConstants.PROPERTY_LEARNING_RESOURCE_TYPE, value);
}
@Override
public SoftwareSourceCode.Builder addLearningResourceType(String value) {
return addProperty(CoreConstants.PROPERTY_LEARNING_RESOURCE_TYPE, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addLicense(CreativeWork value) {
return addProperty(CoreConstants.PROPERTY_LICENSE, value);
}
@Override
public SoftwareSourceCode.Builder addLicense(CreativeWork.Builder value) {
return addProperty(CoreConstants.PROPERTY_LICENSE, value.build());
}
@Override
public SoftwareSourceCode.Builder addLicense(URL value) {
return addProperty(CoreConstants.PROPERTY_LICENSE, value);
}
@Override
public SoftwareSourceCode.Builder addLicense(String value) {
return addProperty(CoreConstants.PROPERTY_LICENSE, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addLocationCreated(Place value) {
return addProperty(CoreConstants.PROPERTY_LOCATION_CREATED, value);
}
@Override
public SoftwareSourceCode.Builder addLocationCreated(Place.Builder value) {
return addProperty(CoreConstants.PROPERTY_LOCATION_CREATED, value.build());
}
@Override
public SoftwareSourceCode.Builder addLocationCreated(String value) {
return addProperty(CoreConstants.PROPERTY_LOCATION_CREATED, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addMainEntity(Thing value) {
return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY, value);
}
@Override
public SoftwareSourceCode.Builder addMainEntity(Thing.Builder value) {
return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY, value.build());
}
@Override
public SoftwareSourceCode.Builder addMainEntity(String value) {
return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addMainEntityOfPage(CreativeWork value) {
return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE, value);
}
@Override
public SoftwareSourceCode.Builder addMainEntityOfPage(CreativeWork.Builder value) {
return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE, value.build());
}
@Override
public SoftwareSourceCode.Builder addMainEntityOfPage(URL value) {
return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE, value);
}
@Override
public SoftwareSourceCode.Builder addMainEntityOfPage(String value) {
return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addMentions(Thing value) {
return addProperty(CoreConstants.PROPERTY_MENTIONS, value);
}
@Override
public SoftwareSourceCode.Builder addMentions(Thing.Builder value) {
return addProperty(CoreConstants.PROPERTY_MENTIONS, value.build());
}
@Override
public SoftwareSourceCode.Builder addMentions(String value) {
return addProperty(CoreConstants.PROPERTY_MENTIONS, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addName(Text value) {
return addProperty(CoreConstants.PROPERTY_NAME, value);
}
@Override
public SoftwareSourceCode.Builder addName(String value) {
return addProperty(CoreConstants.PROPERTY_NAME, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addOffers(Offer value) {
return addProperty(CoreConstants.PROPERTY_OFFERS, value);
}
@Override
public SoftwareSourceCode.Builder addOffers(Offer.Builder value) {
return addProperty(CoreConstants.PROPERTY_OFFERS, value.build());
}
@Override
public SoftwareSourceCode.Builder addOffers(String value) {
return addProperty(CoreConstants.PROPERTY_OFFERS, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addPosition(Integer value) {
return addProperty(CoreConstants.PROPERTY_POSITION, value);
}
@Override
public SoftwareSourceCode.Builder addPosition(Text value) {
return addProperty(CoreConstants.PROPERTY_POSITION, value);
}
@Override
public SoftwareSourceCode.Builder addPosition(String value) {
return addProperty(CoreConstants.PROPERTY_POSITION, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addPotentialAction(Action value) {
return addProperty(CoreConstants.PROPERTY_POTENTIAL_ACTION, value);
}
@Override
public SoftwareSourceCode.Builder addPotentialAction(Action.Builder value) {
return addProperty(CoreConstants.PROPERTY_POTENTIAL_ACTION, value.build());
}
@Override
public SoftwareSourceCode.Builder addPotentialAction(String value) {
return addProperty(CoreConstants.PROPERTY_POTENTIAL_ACTION, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addProducer(Organization value) {
return addProperty(CoreConstants.PROPERTY_PRODUCER, value);
}
@Override
public SoftwareSourceCode.Builder addProducer(Organization.Builder value) {
return addProperty(CoreConstants.PROPERTY_PRODUCER, value.build());
}
@Override
public SoftwareSourceCode.Builder addProducer(Person value) {
return addProperty(CoreConstants.PROPERTY_PRODUCER, value);
}
@Override
public SoftwareSourceCode.Builder addProducer(Person.Builder value) {
return addProperty(CoreConstants.PROPERTY_PRODUCER, value.build());
}
@Override
public SoftwareSourceCode.Builder addProducer(String value) {
return addProperty(CoreConstants.PROPERTY_PRODUCER, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addProgrammingLanguage(Language value) {
return addProperty(CoreConstants.PROPERTY_PROGRAMMING_LANGUAGE, value);
}
@Override
public SoftwareSourceCode.Builder addProgrammingLanguage(Language.Builder value) {
return addProperty(CoreConstants.PROPERTY_PROGRAMMING_LANGUAGE, value.build());
}
@Override
public SoftwareSourceCode.Builder addProgrammingLanguage(String value) {
return addProperty(CoreConstants.PROPERTY_PROGRAMMING_LANGUAGE, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addProvider(Organization value) {
return addProperty(CoreConstants.PROPERTY_PROVIDER, value);
}
@Override
public SoftwareSourceCode.Builder addProvider(Organization.Builder value) {
return addProperty(CoreConstants.PROPERTY_PROVIDER, value.build());
}
@Override
public SoftwareSourceCode.Builder addProvider(Person value) {
return addProperty(CoreConstants.PROPERTY_PROVIDER, value);
}
@Override
public SoftwareSourceCode.Builder addProvider(Person.Builder value) {
return addProperty(CoreConstants.PROPERTY_PROVIDER, value.build());
}
@Override
public SoftwareSourceCode.Builder addProvider(String value) {
return addProperty(CoreConstants.PROPERTY_PROVIDER, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addPublication(PublicationEvent value) {
return addProperty(CoreConstants.PROPERTY_PUBLICATION, value);
}
@Override
public SoftwareSourceCode.Builder addPublication(PublicationEvent.Builder value) {
return addProperty(CoreConstants.PROPERTY_PUBLICATION, value.build());
}
@Override
public SoftwareSourceCode.Builder addPublication(String value) {
return addProperty(CoreConstants.PROPERTY_PUBLICATION, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addPublisher(Organization value) {
return addProperty(CoreConstants.PROPERTY_PUBLISHER, value);
}
@Override
public SoftwareSourceCode.Builder addPublisher(Organization.Builder value) {
return addProperty(CoreConstants.PROPERTY_PUBLISHER, value.build());
}
@Override
public SoftwareSourceCode.Builder addPublisher(Person value) {
return addProperty(CoreConstants.PROPERTY_PUBLISHER, value);
}
@Override
public SoftwareSourceCode.Builder addPublisher(Person.Builder value) {
return addProperty(CoreConstants.PROPERTY_PUBLISHER, value.build());
}
@Override
public SoftwareSourceCode.Builder addPublisher(String value) {
return addProperty(CoreConstants.PROPERTY_PUBLISHER, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addPublishingPrinciples(URL value) {
return addProperty(CoreConstants.PROPERTY_PUBLISHING_PRINCIPLES, value);
}
@Override
public SoftwareSourceCode.Builder addPublishingPrinciples(String value) {
return addProperty(CoreConstants.PROPERTY_PUBLISHING_PRINCIPLES, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addRecordedAt(Event value) {
return addProperty(CoreConstants.PROPERTY_RECORDED_AT, value);
}
@Override
public SoftwareSourceCode.Builder addRecordedAt(Event.Builder value) {
return addProperty(CoreConstants.PROPERTY_RECORDED_AT, value.build());
}
@Override
public SoftwareSourceCode.Builder addRecordedAt(String value) {
return addProperty(CoreConstants.PROPERTY_RECORDED_AT, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addReleasedEvent(PublicationEvent value) {
return addProperty(CoreConstants.PROPERTY_RELEASED_EVENT, value);
}
@Override
public SoftwareSourceCode.Builder addReleasedEvent(PublicationEvent.Builder value) {
return addProperty(CoreConstants.PROPERTY_RELEASED_EVENT, value.build());
}
@Override
public SoftwareSourceCode.Builder addReleasedEvent(String value) {
return addProperty(CoreConstants.PROPERTY_RELEASED_EVENT, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addReview(Review value) {
return addProperty(CoreConstants.PROPERTY_REVIEW, value);
}
@Override
public SoftwareSourceCode.Builder addReview(Review.Builder value) {
return addProperty(CoreConstants.PROPERTY_REVIEW, value.build());
}
@Override
public SoftwareSourceCode.Builder addReview(String value) {
return addProperty(CoreConstants.PROPERTY_REVIEW, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addReviews(Review value) {
return addProperty(CoreConstants.PROPERTY_REVIEWS, value);
}
@Override
public SoftwareSourceCode.Builder addReviews(Review.Builder value) {
return addProperty(CoreConstants.PROPERTY_REVIEWS, value.build());
}
@Override
public SoftwareSourceCode.Builder addReviews(String value) {
return addProperty(CoreConstants.PROPERTY_REVIEWS, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addRuntime(Text value) {
return addProperty(CoreConstants.PROPERTY_RUNTIME, value);
}
@Override
public SoftwareSourceCode.Builder addRuntime(String value) {
return addProperty(CoreConstants.PROPERTY_RUNTIME, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addRuntimePlatform(Text value) {
return addProperty(CoreConstants.PROPERTY_RUNTIME_PLATFORM, value);
}
@Override
public SoftwareSourceCode.Builder addRuntimePlatform(String value) {
return addProperty(CoreConstants.PROPERTY_RUNTIME_PLATFORM, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addSameAs(URL value) {
return addProperty(CoreConstants.PROPERTY_SAME_AS, value);
}
@Override
public SoftwareSourceCode.Builder addSameAs(String value) {
return addProperty(CoreConstants.PROPERTY_SAME_AS, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addSampleType(Text value) {
return addProperty(CoreConstants.PROPERTY_SAMPLE_TYPE, value);
}
@Override
public SoftwareSourceCode.Builder addSampleType(String value) {
return addProperty(CoreConstants.PROPERTY_SAMPLE_TYPE, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addSchemaVersion(Text value) {
return addProperty(CoreConstants.PROPERTY_SCHEMA_VERSION, value);
}
@Override
public SoftwareSourceCode.Builder addSchemaVersion(URL value) {
return addProperty(CoreConstants.PROPERTY_SCHEMA_VERSION, value);
}
@Override
public SoftwareSourceCode.Builder addSchemaVersion(String value) {
return addProperty(CoreConstants.PROPERTY_SCHEMA_VERSION, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addSourceOrganization(Organization value) {
return addProperty(CoreConstants.PROPERTY_SOURCE_ORGANIZATION, value);
}
@Override
public SoftwareSourceCode.Builder addSourceOrganization(Organization.Builder value) {
return addProperty(CoreConstants.PROPERTY_SOURCE_ORGANIZATION, value.build());
}
@Override
public SoftwareSourceCode.Builder addSourceOrganization(String value) {
return addProperty(CoreConstants.PROPERTY_SOURCE_ORGANIZATION, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addTargetProduct(SoftwareApplication value) {
return addProperty(CoreConstants.PROPERTY_TARGET_PRODUCT, value);
}
@Override
public SoftwareSourceCode.Builder addTargetProduct(SoftwareApplication.Builder value) {
return addProperty(CoreConstants.PROPERTY_TARGET_PRODUCT, value.build());
}
@Override
public SoftwareSourceCode.Builder addTargetProduct(String value) {
return addProperty(CoreConstants.PROPERTY_TARGET_PRODUCT, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addText(Text value) {
return addProperty(CoreConstants.PROPERTY_TEXT, value);
}
@Override
public SoftwareSourceCode.Builder addText(String value) {
return addProperty(CoreConstants.PROPERTY_TEXT, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addThumbnailUrl(URL value) {
return addProperty(CoreConstants.PROPERTY_THUMBNAIL_URL, value);
}
@Override
public SoftwareSourceCode.Builder addThumbnailUrl(String value) {
return addProperty(CoreConstants.PROPERTY_THUMBNAIL_URL, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addTimeRequired(Duration value) {
return addProperty(CoreConstants.PROPERTY_TIME_REQUIRED, value);
}
@Override
public SoftwareSourceCode.Builder addTimeRequired(Duration.Builder value) {
return addProperty(CoreConstants.PROPERTY_TIME_REQUIRED, value.build());
}
@Override
public SoftwareSourceCode.Builder addTimeRequired(String value) {
return addProperty(CoreConstants.PROPERTY_TIME_REQUIRED, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addTranslator(Organization value) {
return addProperty(CoreConstants.PROPERTY_TRANSLATOR, value);
}
@Override
public SoftwareSourceCode.Builder addTranslator(Organization.Builder value) {
return addProperty(CoreConstants.PROPERTY_TRANSLATOR, value.build());
}
@Override
public SoftwareSourceCode.Builder addTranslator(Person value) {
return addProperty(CoreConstants.PROPERTY_TRANSLATOR, value);
}
@Override
public SoftwareSourceCode.Builder addTranslator(Person.Builder value) {
return addProperty(CoreConstants.PROPERTY_TRANSLATOR, value.build());
}
@Override
public SoftwareSourceCode.Builder addTranslator(String value) {
return addProperty(CoreConstants.PROPERTY_TRANSLATOR, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addTypicalAgeRange(Text value) {
return addProperty(CoreConstants.PROPERTY_TYPICAL_AGE_RANGE, value);
}
@Override
public SoftwareSourceCode.Builder addTypicalAgeRange(String value) {
return addProperty(CoreConstants.PROPERTY_TYPICAL_AGE_RANGE, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addUrl(URL value) {
return addProperty(CoreConstants.PROPERTY_URL, value);
}
@Override
public SoftwareSourceCode.Builder addUrl(String value) {
return addProperty(CoreConstants.PROPERTY_URL, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addVersion(Number value) {
return addProperty(CoreConstants.PROPERTY_VERSION, value);
}
@Override
public SoftwareSourceCode.Builder addVersion(String value) {
return addProperty(CoreConstants.PROPERTY_VERSION, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addVideo(VideoObject value) {
return addProperty(CoreConstants.PROPERTY_VIDEO, value);
}
@Override
public SoftwareSourceCode.Builder addVideo(VideoObject.Builder value) {
return addProperty(CoreConstants.PROPERTY_VIDEO, value.build());
}
@Override
public SoftwareSourceCode.Builder addVideo(String value) {
return addProperty(CoreConstants.PROPERTY_VIDEO, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addWorkExample(CreativeWork value) {
return addProperty(CoreConstants.PROPERTY_WORK_EXAMPLE, value);
}
@Override
public SoftwareSourceCode.Builder addWorkExample(CreativeWork.Builder value) {
return addProperty(CoreConstants.PROPERTY_WORK_EXAMPLE, value.build());
}
@Override
public SoftwareSourceCode.Builder addWorkExample(String value) {
return addProperty(CoreConstants.PROPERTY_WORK_EXAMPLE, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addDetailedDescription(Article value) {
return addProperty(GoogConstants.PROPERTY_DETAILED_DESCRIPTION, value);
}
@Override
public SoftwareSourceCode.Builder addDetailedDescription(Article.Builder value) {
return addProperty(GoogConstants.PROPERTY_DETAILED_DESCRIPTION, value.build());
}
@Override
public SoftwareSourceCode.Builder addDetailedDescription(String value) {
return addProperty(GoogConstants.PROPERTY_DETAILED_DESCRIPTION, Text.of(value));
}
@Override
public SoftwareSourceCode.Builder addPopularityScore(PopularityScoreSpecification value) {
return addProperty(GoogConstants.PROPERTY_POPULARITY_SCORE, value);
}
@Override
public SoftwareSourceCode.Builder addPopularityScore(
PopularityScoreSpecification.Builder value) {
return addProperty(GoogConstants.PROPERTY_POPULARITY_SCORE, value.build());
}
@Override
public SoftwareSourceCode.Builder addPopularityScore(String value) {
return addProperty(GoogConstants.PROPERTY_POPULARITY_SCORE, Text.of(value));
}
@Override
public SoftwareSourceCode build() {
return new SoftwareSourceCodeImpl(properties, reverseMap);
}
}
public SoftwareSourceCodeImpl(
Multimap<String, ValueType> properties, Multimap<String, Thing> reverseMap) {
super(properties, reverseMap);
}
@Override
public String getFullTypeName() {
return CoreConstants.TYPE_SOFTWARE_SOURCE_CODE;
}
@Override
public boolean includesProperty(String property) {
return PROPERTY_SET.contains(CoreConstants.NAMESPACE + property)
|| PROPERTY_SET.contains(GoogConstants.NAMESPACE + property)
|| PROPERTY_SET.contains(property);
}
@Override
public ImmutableList<SchemaOrgType> getCodeRepositoryList() {
return getProperty(CoreConstants.PROPERTY_CODE_REPOSITORY);
}
@Override
public ImmutableList<SchemaOrgType> getCodeSampleTypeList() {
return getProperty(CoreConstants.PROPERTY_CODE_SAMPLE_TYPE);
}
@Override
public ImmutableList<SchemaOrgType> getProgrammingLanguageList() {
return getProperty(CoreConstants.PROPERTY_PROGRAMMING_LANGUAGE);
}
@Override
public ImmutableList<SchemaOrgType> getRuntimeList() {
return getProperty(CoreConstants.PROPERTY_RUNTIME);
}
@Override
public ImmutableList<SchemaOrgType> getRuntimePlatformList() {
return getProperty(CoreConstants.PROPERTY_RUNTIME_PLATFORM);
}
@Override
public ImmutableList<SchemaOrgType> getSampleTypeList() {
return getProperty(CoreConstants.PROPERTY_SAMPLE_TYPE);
}
@Override
public ImmutableList<SchemaOrgType> getTargetProductList() {
return getProperty(CoreConstants.PROPERTY_TARGET_PRODUCT);
}
}
| |
package org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts;
import java.util.Collections;
import java.util.List;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.Label;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.transaction.RunnableWithResult;
import org.eclipse.gef.AccessibleEditPart;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.Request;
import org.eclipse.gef.requests.DirectEditRequest;
import org.eclipse.gef.tools.DirectEditManager;
import org.eclipse.gmf.runtime.common.ui.services.parser.IParser;
import org.eclipse.gmf.runtime.common.ui.services.parser.IParserEditStatus;
import org.eclipse.gmf.runtime.common.ui.services.parser.ParserEditStatus;
import org.eclipse.gmf.runtime.common.ui.services.parser.ParserOptions;
import org.eclipse.gmf.runtime.diagram.ui.editparts.CompartmentEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.ITextAwareEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.LabelDirectEditPolicy;
import org.eclipse.gmf.runtime.diagram.ui.l10n.DiagramColorRegistry;
import org.eclipse.gmf.runtime.diagram.ui.label.ILabelDelegate;
import org.eclipse.gmf.runtime.diagram.ui.label.WrappingLabelDelegate;
import org.eclipse.gmf.runtime.diagram.ui.requests.RequestConstants;
import org.eclipse.gmf.runtime.diagram.ui.tools.TextDirectEditManager;
import org.eclipse.gmf.runtime.draw2d.ui.figures.WrappingLabel;
import org.eclipse.gmf.runtime.emf.core.util.EObjectAdapter;
import org.eclipse.gmf.runtime.emf.ui.services.parser.ISemanticParser;
import org.eclipse.gmf.runtime.notation.FontStyle;
import org.eclipse.gmf.runtime.notation.NotationPackage;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.gmf.tooling.runtime.directedit.TextDirectEditManager2;
import org.eclipse.gmf.tooling.runtime.draw2d.labels.SimpleLabelDelegate;
import org.eclipse.gmf.tooling.runtime.edit.policies.DefaultNodeLabelDragPolicy;
import org.eclipse.gmf.tooling.runtime.edit.policies.labels.IRefreshableFeedbackEditPolicy;
import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
import org.eclipse.jface.viewers.ICellEditorValidator;
import org.eclipse.swt.SWT;
import org.eclipse.swt.accessibility.AccessibleEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.Image;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.MediatorFigureSelectionListener;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.policies.EsbTextSelectionEditPolicy;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.part.EsbVisualIDRegistry;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.providers.EsbElementTypes;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.providers.EsbParserProvider;
/**
* @generated
*/
public class LoopBackMediatorDescriptionEditPart extends CompartmentEditPart
implements ITextAwareEditPart {
/**
* @generated
*/
public static final int VISUAL_ID = 5208;
/**
* @generated
*/
private DirectEditManager manager;
/**
* @generated
*/
private IParser parser;
/**
* @generated
*/
private List<?> parserElements;
/**
* @generated
*/
private String defaultText;
/**
* @generated
*/
private ILabelDelegate labelDelegate;
/**
* @generated
*/
public LoopBackMediatorDescriptionEditPart(View view) {
super(view);
}
/**
* @generated
*/
protected void createDefaultEditPolicies() {
super.createDefaultEditPolicies();
installEditPolicy(EditPolicy.SELECTION_FEEDBACK_ROLE,
new EsbTextSelectionEditPolicy());
installEditPolicy(EditPolicy.DIRECT_EDIT_ROLE,
new LabelDirectEditPolicy());
installEditPolicy(EditPolicy.PRIMARY_DRAG_ROLE,
new DefaultNodeLabelDragPolicy());
}
/**
* @generated
*/
protected String getLabelTextHelper(IFigure figure) {
if (figure instanceof WrappingLabel) {
return ((WrappingLabel) figure).getText();
} else if (figure instanceof Label) {
return ((Label) figure).getText();
} else {
return getLabelDelegate().getText();
}
}
/**
* @generated
*/
protected void setLabelTextHelper(IFigure figure, String text) {
if (figure instanceof WrappingLabel) {
((WrappingLabel) figure).setText(text);
} else if (figure instanceof Label) {
((Label) figure).setText(text);
} else {
getLabelDelegate().setText(text);
}
}
/**
* @generated
*/
protected Image getLabelIconHelper(IFigure figure) {
if (figure instanceof WrappingLabel) {
return ((WrappingLabel) figure).getIcon();
} else if (figure instanceof Label) {
return ((Label) figure).getIcon();
} else {
return getLabelDelegate().getIcon(0);
}
}
/**
* @generated
*/
protected void setLabelIconHelper(IFigure figure, Image icon) {
if (figure instanceof WrappingLabel) {
((WrappingLabel) figure).setIcon(icon);
return;
} else if (figure instanceof Label) {
((Label) figure).setIcon(icon);
return;
} else {
getLabelDelegate().setIcon(icon, 0);
}
}
/**
* @generated NOT
*/
public void setLabel(WrappingLabel figure) {
figure.addMouseListener(new MediatorFigureSelectionListener(this
.getParent()));
unregisterVisuals();
setFigure(figure);
defaultText = getLabelTextHelper(figure);
registerVisuals();
refreshVisuals();
}
/**
* @generated
*/
@SuppressWarnings("rawtypes")
protected List getModelChildren() {
return Collections.EMPTY_LIST;
}
/**
* @generated
*/
public IGraphicalEditPart getChildBySemanticHint(String semanticHint) {
return null;
}
/**
* @generated
*/
protected EObject getParserElement() {
return resolveSemanticElement();
}
/**
* @generated
*/
protected Image getLabelIcon() {
return null;
}
/**
* @generated
*/
protected String getLabelText() {
String text = null;
EObject parserElement = getParserElement();
if (parserElement != null && getParser() != null) {
text = getParser().getPrintString(
new EObjectAdapter(parserElement),
getParserOptions().intValue());
}
if (text == null || text.length() == 0) {
text = defaultText;
}
return text;
}
/**
* @generated
*/
public void setLabelText(String text) {
setLabelTextHelper(getFigure(), text);
refreshSelectionFeedback();
}
/**
* @generated
*/
public String getEditText() {
if (getParserElement() == null || getParser() == null) {
return ""; //$NON-NLS-1$
}
return getParser().getEditString(
new EObjectAdapter(getParserElement()),
getParserOptions().intValue());
}
/**
* @generated
*/
protected boolean isEditable() {
return getParser() != null;
}
/**
* @generated
*/
public ICellEditorValidator getEditTextValidator() {
return new ICellEditorValidator() {
public String isValid(final Object value) {
if (value instanceof String) {
final EObject element = getParserElement();
final IParser parser = getParser();
try {
IParserEditStatus valid = (IParserEditStatus) getEditingDomain()
.runExclusive(
new RunnableWithResult.Impl<IParserEditStatus>() {
public void run() {
setResult(parser
.isValidEditString(
new EObjectAdapter(
element),
(String) value));
}
});
return valid.getCode() == ParserEditStatus.EDITABLE ? null
: valid.getMessage();
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
// shouldn't get here
return null;
}
};
}
/**
* @generated
*/
public IContentAssistProcessor getCompletionProcessor() {
if (getParserElement() == null || getParser() == null) {
return null;
}
return getParser().getCompletionProcessor(
new EObjectAdapter(getParserElement()));
}
/**
* @generated
*/
public ParserOptions getParserOptions() {
return ParserOptions.NONE;
}
/**
* @generated
*/
public IParser getParser() {
if (parser == null) {
parser = EsbParserProvider
.getParser(
EsbElementTypes.LoopBackMediator_3736,
getParserElement(),
EsbVisualIDRegistry
.getType(org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.LoopBackMediatorDescriptionEditPart.VISUAL_ID));
}
return parser;
}
/**
* @generated
*/
protected DirectEditManager getManager() {
if (manager == null) {
setManager(new TextDirectEditManager2(this, null,
EsbEditPartFactory.getTextCellEditorLocator(this)));
}
return manager;
}
/**
* @generated
*/
protected void setManager(DirectEditManager manager) {
this.manager = manager;
}
/**
* @generated
*/
protected void performDirectEdit() {
getManager().show();
}
/**
* @generated
*/
protected void performDirectEdit(Point eventLocation) {
if (getManager().getClass() == TextDirectEditManager2.class) {
((TextDirectEditManager2) getManager()).show(eventLocation
.getSWTPoint());
}
}
/**
* @generated
*/
private void performDirectEdit(char initialCharacter) {
if (getManager() instanceof TextDirectEditManager) {
((TextDirectEditManager) getManager()).show(initialCharacter);
} else //
if (getManager() instanceof TextDirectEditManager2) {
((TextDirectEditManager2) getManager()).show(initialCharacter);
} else //
{
performDirectEdit();
}
}
/**
* @generated
*/
protected void performDirectEditRequest(Request request) {
final Request theRequest = request;
try {
getEditingDomain().runExclusive(new Runnable() {
public void run() {
if (isActive() && isEditable()) {
if (theRequest
.getExtendedData()
.get(RequestConstants.REQ_DIRECTEDIT_EXTENDEDDATA_INITIAL_CHAR) instanceof Character) {
Character initialChar = (Character) theRequest
.getExtendedData()
.get(RequestConstants.REQ_DIRECTEDIT_EXTENDEDDATA_INITIAL_CHAR);
performDirectEdit(initialChar.charValue());
} else if ((theRequest instanceof DirectEditRequest)
&& (getEditText().equals(getLabelText()))) {
DirectEditRequest editRequest = (DirectEditRequest) theRequest;
performDirectEdit(editRequest.getLocation());
} else {
performDirectEdit();
}
}
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* @generated
*/
protected void refreshVisuals() {
super.refreshVisuals();
refreshLabel();
refreshFont();
refreshFontColor();
refreshUnderline();
refreshStrikeThrough();
}
/**
* @generated
*/
protected void refreshLabel() {
setLabelTextHelper(getFigure(), getLabelText());
setLabelIconHelper(getFigure(), getLabelIcon());
refreshSelectionFeedback();
}
/**
* @generated
*/
protected void refreshUnderline() {
FontStyle style = (FontStyle) getFontStyleOwnerView().getStyle(
NotationPackage.eINSTANCE.getFontStyle());
if (style != null && getFigure() instanceof WrappingLabel) {
((WrappingLabel) getFigure()).setTextUnderline(style.isUnderline());
}
}
/**
* @generated
*/
protected void refreshStrikeThrough() {
FontStyle style = (FontStyle) getFontStyleOwnerView().getStyle(
NotationPackage.eINSTANCE.getFontStyle());
if (style != null && getFigure() instanceof WrappingLabel) {
((WrappingLabel) getFigure()).setTextStrikeThrough(style
.isStrikeThrough());
}
}
/**
* @generated
*/
protected void refreshFont() {
FontStyle style = (FontStyle) getFontStyleOwnerView().getStyle(
NotationPackage.eINSTANCE.getFontStyle());
if (style != null) {
FontData fontData = new FontData(style.getFontName(),
style.getFontHeight(), (style.isBold() ? SWT.BOLD
: SWT.NORMAL)
| (style.isItalic() ? SWT.ITALIC : SWT.NORMAL));
setFont(fontData);
}
}
/**
* @generated
*/
private void refreshSelectionFeedback() {
requestEditPolicyFeedbackRefresh(EditPolicy.PRIMARY_DRAG_ROLE);
requestEditPolicyFeedbackRefresh(EditPolicy.SELECTION_FEEDBACK_ROLE);
}
/**
* @generated
*/
private void requestEditPolicyFeedbackRefresh(String editPolicyKey) {
Object editPolicy = getEditPolicy(editPolicyKey);
if (editPolicy instanceof IRefreshableFeedbackEditPolicy) {
((IRefreshableFeedbackEditPolicy) editPolicy).refreshFeedback();
}
}
/**
* @generated
*/
protected void setFontColor(Color color) {
getFigure().setForegroundColor(color);
}
/**
* @generated
*/
protected void addSemanticListeners() {
if (getParser() instanceof ISemanticParser) {
EObject element = resolveSemanticElement();
parserElements = ((ISemanticParser) getParser())
.getSemanticElementsBeingParsed(element);
for (int i = 0; i < parserElements.size(); i++) {
addListenerFilter(
"SemanticModel" + i, this, (EObject) parserElements.get(i)); //$NON-NLS-1$
}
} else {
super.addSemanticListeners();
}
}
/**
* @generated
*/
protected void removeSemanticListeners() {
if (parserElements != null) {
for (int i = 0; i < parserElements.size(); i++) {
removeListenerFilter("SemanticModel" + i); //$NON-NLS-1$
}
} else {
super.removeSemanticListeners();
}
}
/**
* @generated
*/
protected AccessibleEditPart getAccessibleEditPart() {
if (accessibleEP == null) {
accessibleEP = new AccessibleGraphicalEditPart() {
public void getName(AccessibleEvent e) {
e.result = getLabelTextHelper(getFigure());
}
};
}
return accessibleEP;
}
/**
* @generated
*/
private View getFontStyleOwnerView() {
return getPrimaryView();
}
/**
* @generated
*/
private ILabelDelegate getLabelDelegate() {
if (labelDelegate == null) {
IFigure label = getFigure();
if (label instanceof WrappingLabel) {
labelDelegate = new WrappingLabelDelegate((WrappingLabel) label);
} else {
labelDelegate = new SimpleLabelDelegate((Label) label);
}
}
return labelDelegate;
}
/**
* @generated
*/
@Override
public Object getAdapter(Class key) {
if (ILabelDelegate.class.equals(key)) {
return getLabelDelegate();
}
return super.getAdapter(key);
}
/**
* @generated
*/
protected void addNotationalListeners() {
super.addNotationalListeners();
addListenerFilter("PrimaryView", this, getPrimaryView()); //$NON-NLS-1$
}
/**
* @generated
*/
protected void removeNotationalListeners() {
super.removeNotationalListeners();
removeListenerFilter("PrimaryView"); //$NON-NLS-1$
}
/**
* @generated
*/
protected void handleNotificationEvent(Notification event) {
Object feature = event.getFeature();
if (NotationPackage.eINSTANCE.getFontStyle_FontColor().equals(feature)) {
Integer c = (Integer) event.getNewValue();
setFontColor(DiagramColorRegistry.getInstance().getColor(c));
} else if (NotationPackage.eINSTANCE.getFontStyle_Underline().equals(
feature)) {
refreshUnderline();
} else if (NotationPackage.eINSTANCE.getFontStyle_StrikeThrough()
.equals(feature)) {
refreshStrikeThrough();
} else if (NotationPackage.eINSTANCE.getFontStyle_FontHeight().equals(
feature)
|| NotationPackage.eINSTANCE.getFontStyle_FontName().equals(
feature)
|| NotationPackage.eINSTANCE.getFontStyle_Bold()
.equals(feature)
|| NotationPackage.eINSTANCE.getFontStyle_Italic().equals(
feature)) {
refreshFont();
} else {
if (getParser() != null
&& getParser().isAffectingEvent(event,
getParserOptions().intValue())) {
refreshLabel();
}
if (getParser() instanceof ISemanticParser) {
ISemanticParser modelParser = (ISemanticParser) getParser();
if (modelParser.areSemanticElementsAffected(null, event)) {
removeSemanticListeners();
if (resolveSemanticElement() != null) {
addSemanticListeners();
}
refreshLabel();
}
}
}
super.handleNotificationEvent(event);
}
/**
* @generated
*/
protected IFigure createFigure() {
// Parent should assign one using setLabel() method
return null;
}
}
| |
package com.pragbits.stash.components;
import com.atlassian.event.api.EventListener;
import com.atlassian.stash.commit.CommitService;
import com.atlassian.stash.content.Changeset;
import com.atlassian.stash.content.ChangesetsBetweenRequest;
import com.atlassian.stash.event.RepositoryPushEvent;
import com.atlassian.stash.nav.NavBuilder;
import com.atlassian.stash.repository.RefChange;
import com.atlassian.stash.repository.RefChangeType;
import com.atlassian.stash.repository.Repository;
import com.atlassian.stash.util.Page;
import com.atlassian.stash.util.PageRequest;
import com.atlassian.stash.util.PageUtils;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.pragbits.stash.ColorCode;
import com.pragbits.stash.SlackGlobalSettingsService;
import com.pragbits.stash.SlackSettings;
import com.pragbits.stash.SlackSettingsService;
import com.pragbits.stash.tools.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class RepositoryPushActivityListener {
static final String KEY_GLOBAL_SETTING_HOOK_URL = "stash2slack.globalsettings.hookurl";
static final String KEY_GLOBAL_SLACK_CHANNEL_NAME = "stash2slack.globalsettings.channelname";
private static final Logger log = LoggerFactory.getLogger(RepositoryPushActivityListener.class);
private final SlackGlobalSettingsService slackGlobalSettingsService;
private final SlackSettingsService slackSettingsService;
private final CommitService commitService;
private final NavBuilder navBuilder;
private final SlackNotifier slackNotifier;
private final Gson gson = new Gson();
public RepositoryPushActivityListener(SlackGlobalSettingsService slackGlobalSettingsService,
SlackSettingsService slackSettingsService,
CommitService commitService,
NavBuilder navBuilder,
SlackNotifier slackNotifier) {
this.slackGlobalSettingsService = slackGlobalSettingsService;
this.slackSettingsService = slackSettingsService;
this.commitService = commitService;
this.navBuilder = navBuilder;
this.slackNotifier = slackNotifier;
}
@EventListener
public void NotifySlackChannel(RepositoryPushEvent event) {
// find out if notification is enabled for this repo
Repository repository = event.getRepository();
SlackSettings slackSettings = slackSettingsService.getSlackSettings(repository);
String globalHookUrl = slackGlobalSettingsService.getWebHookUrl(KEY_GLOBAL_SETTING_HOOK_URL);
SettingsSelector settingsSelector = new SettingsSelector(slackSettingsService, slackGlobalSettingsService, repository);
SlackSettings resolvedSlackSettings = settingsSelector.getResolvedSlackSettings();
if (resolvedSlackSettings.isSlackNotificationsEnabledForPush()) {
String localHookUrl = slackSettings.getSlackWebHookUrl();
WebHookSelector hookSelector = new WebHookSelector(globalHookUrl, localHookUrl);
ChannelSelector channelSelector = new ChannelSelector(slackGlobalSettingsService.getChannelName(KEY_GLOBAL_SLACK_CHANNEL_NAME), slackSettings.getSlackChannelName());
if (!hookSelector.isHookValid()) {
log.error("There is no valid configured Web hook url! Reason: " + hookSelector.getProblem());
return;
}
if (repository.isFork() && !resolvedSlackSettings.isSlackNotificationsEnabledForPersonal()) {
// simply return silently when we don't want forks to get notifications unless they're explicitly enabled
return;
}
String repoName = repository.getSlug();
String projectName = repository.getProject().getKey();
String repoPath = projectName + "/" + event.getRepository().getName();
for (RefChange refChange : event.getRefChanges()) {
String text;
String ref = refChange.getRefId();
NavBuilder.Repo repoUrlBuilder = navBuilder
.project(projectName)
.repo(repoName);
String url = repoUrlBuilder
.commits()
.until(refChange.getRefId())
.buildAbsolute();
List<Changeset> myChanges = new LinkedList<Changeset>();
boolean isNewRef = refChange.getFromHash().equalsIgnoreCase("0000000000000000000000000000000000000000");
boolean isDeleted = refChange.getToHash().equalsIgnoreCase("0000000000000000000000000000000000000000")
&& refChange.getType() == RefChangeType.DELETE;
if (isDeleted || isNewRef) {
return;
}
if (isDeleted) {
// issue#4: if type is "DELETE" and toHash is all zero then this is a branch delete
if (ref.indexOf("refs/tags") >= 0) {
text = String.format("Tag `%s` deleted from repository <%s|`%s`>.",
ref.replace("refs/tags/", ""),
repoUrlBuilder.buildAbsolute(),
repoPath);
} else {
text = String.format("Branch `%s` deleted from repository <%s|`%s`>.",
ref.replace("refs/heads/", ""),
repoUrlBuilder.buildAbsolute(),
repoPath);
}
} else if (isNewRef) {
// issue#3 if fromHash is all zero (meaning the beginning of everything, probably), then this push is probably
// a new branch or tag, and we want only to display the latest commit, not the entire history
Changeset latestChangeSet = commitService.getChangeset(repository, refChange.getToHash());
myChanges.add(latestChangeSet);
if (ref.indexOf("refs/tags") >= 0) {
text = String.format("Tag <%s|`%s`> pushed on <%s|`%s`>. See <%s|commit list>.",
url,
ref.replace("refs/tags/", ""),
repoUrlBuilder.buildAbsolute(),
repoPath,
url
);
} else {
text = String.format("Branch <%s|`%s`> pushed on <%s|`%s`>. See <%s|commit list>.",
url,
ref.replace("refs/heads/", ""),
repoUrlBuilder.buildAbsolute(),
repoPath,
url);
}
} else {
ChangesetsBetweenRequest request = new ChangesetsBetweenRequest.Builder(repository)
.exclude(refChange.getFromHash())
.include(refChange.getToHash())
.build();
Page<Changeset> changeSets = commitService.getChangesetsBetween(
request, PageUtils.newRequest(0, PageRequest.MAX_PAGE_LIMIT));
myChanges.addAll(Lists.newArrayList(changeSets.getValues()));
int commitCount = myChanges.size();
String commitStr = commitCount == 1 ? "commit" : "commits";
String branch = ref.replace("refs/heads/", "");
if (!branch.equals("master")) {
continue;
}
text = String.format("Push on <%s|`%s`> branch <%s|`%s`> by `%s <%s>` (%d %s). See <%s|commit list>.",
repoUrlBuilder.buildAbsolute(),
repoPath,
url,
branch,
event.getUser() != null ? event.getUser().getDisplayName() : "unknown user",
event.getUser() != null ? event.getUser().getEmailAddress() : "unknown email",
commitCount, commitStr,
url);
}
// Figure out what type of change this is:
SlackPayload payload = new SlackPayload();
payload.setText(text);
payload.setMrkdwn(true);
switch (resolvedSlackSettings.getNotificationLevel()) {
case COMPACT:
compactCommitLog(event, refChange, payload, repoUrlBuilder, myChanges);
break;
case VERBOSE:
verboseCommitLog(event, refChange, payload, repoUrlBuilder, text, myChanges);
break;
case MINIMAL:
default:
break;
}
// slackSettings.getSlackChannelName might be:
// - empty
// - comma separated list of channel names, eg: #mych1, #mych2, #mych3
if (channelSelector.getSelectedChannel().isEmpty()) {
slackNotifier.SendSlackNotification(hookSelector.getSelectedHook(), gson.toJson(payload));
} else {
// send message to multiple channels
List<String> channels = Arrays.asList(channelSelector.getSelectedChannel().split("\\s*,\\s*"));
for (String channel: channels) {
payload.setChannel(channel.trim());
slackNotifier.SendSlackNotification(hookSelector.getSelectedHook(), gson.toJson(payload));
}
}
}
}
}
private void compactCommitLog(RepositoryPushEvent event, RefChange refChange, SlackPayload payload, NavBuilder.Repo urlBuilder, List<Changeset> myChanges) {
if (myChanges.size() == 0) {
// If there are no commits, no reason to add anything
}
SlackAttachment commits = new SlackAttachment();
commits.setColor(ColorCode.GRAY.getCode());
// Since the branch is now in the main commit line, title is not needed
//commits.setTitle(String.format("[%s:%s]", event.getRepository().getName(), refChange.getRefId().replace("refs/heads", "")));
StringBuilder attachmentFallback = new StringBuilder();
StringBuilder commitListBlock = new StringBuilder();
for (Changeset ch : myChanges) {
String commitUrl = urlBuilder.changeset(ch.getId()).buildAbsolute();
String firstCommitMessageLine = ch.getMessage().split("\n")[0];
// Note that we changed this to put everything in one attachment because otherwise it
// doesn't get collapsed in slack (the see more... doesn't appear)
commitListBlock.append(String.format("<%s|`%s`>: %s - _%s_\n",
commitUrl, ch.getDisplayId(), firstCommitMessageLine, ch.getAuthor().getName()));
attachmentFallback.append(String.format("%s: %s\n", ch.getDisplayId(), firstCommitMessageLine));
}
commits.setText(commitListBlock.toString());
commits.setFallback(attachmentFallback.toString());
payload.addAttachment(commits);
}
private void verboseCommitLog(RepositoryPushEvent event, RefChange refChange, SlackPayload payload, NavBuilder.Repo urlBuilder, String text, List<Changeset> myChanges) {
for (Changeset ch : myChanges) {
SlackAttachment attachment = new SlackAttachment();
attachment.setFallback(text);
attachment.setColor(ColorCode.GRAY.getCode());
SlackAttachmentField field = new SlackAttachmentField();
attachment.setTitle(String.format("[%s:%s] - %s", event.getRepository().getName(), refChange.getRefId().replace("refs/heads", ""), ch.getId()));
attachment.setTitle_link(urlBuilder.changeset(ch.getId()).buildAbsolute());
field.setTitle("comment");
field.setValue(ch.getMessage());
field.setShort(false);
attachment.addField(field);
payload.addAttachment(attachment);
}
}
}
| |
/**
* Copyright 2013 Darryl Pogue
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cordova.plugins;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.FragmentTransaction;
import android.content.res.AssetManager;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.Window;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.DroidGap;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
class Actionable
{
private static AssetManager sAssetMgr;
private String mTitle;
private Boolean mDisabled;
private int mFlags;
private Drawable mIcon;
private Boolean mSelected;
private String mCallbackId;
private int mOrder = 0;
public static Actionable fromJSON(JSONObject jsobj)
{
try
{
Actionable action = new Actionable();
action.mTitle = jsobj.getString("label");
action.mDisabled = jsobj.optBoolean("disabled", false);
action.mSelected = jsobj.optBoolean("selected", false);
action.mCallbackId = jsobj.optString("callback");
String iconname = jsobj.optString("icon", null);
if (iconname != null) {
try
{
String tmp_uri = "www/" + iconname;
InputStream image = sAssetMgr.open(tmp_uri);
action.mIcon = Drawable.createFromStream(image, iconname);
}
catch (IOException e)
{
}
}
return action;
}
catch (JSONException e)
{
Log.v("Cambie", Log.getStackTraceString(e));
return null;
}
}
public static void setAssetManager(AssetManager mgr)
{
sAssetMgr = mgr;
}
public String getCallbackId()
{
return mCallbackId;
}
public int getFlags()
{
return this.mFlags;
}
public Drawable getIcon()
{
return this.mIcon;
}
public int getOrder()
{
return this.mOrder;
}
public String getTitle()
{
return this.mTitle;
}
public Boolean isDisabled()
{
return this.mDisabled;
}
public Boolean isSelected()
{
return this.mSelected;
}
public void setFlags(int flags)
{
this.mFlags = flags;
}
public void setOrder(int order)
{
this.mOrder = order;
}
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public class Cambie extends CordovaPlugin implements TabListener
{
/**
* The DroidGap Activity instance.
*/
private DroidGap mDroidGap;
/**
* The AssetManager for accessing images in the www folder.
*/
private AssetManager mAssets;
/**
* The ActionBar we are dealing with.
*/
private ActionBar mBar;
/**
* The Options Menu for the app.
*/
private Menu mMenu;
/**
* The menu items and action items shown in the ActionBar.
*/
private HashMap<String, Actionable> mMenuItems;
private enum NavType {
NONE("none"),
BACK("back"),
MENU("menu"),
CLOSE("close");
private String mKey;
public static NavType parse(String key)
{
if (key != null)
{
for (NavType nt : NavType.values())
{
if (nt.mKey.equalsIgnoreCase(key))
{
return nt;
}
}
}
throw new IllegalArgumentException("Invalid Navigation Type");
}
private NavType(String key)
{
mKey = key;
}
public String ToString()
{
return mKey;
}
}
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView)
{
super.initialize(cordova, webView);
Log.v("Cambie", "Initializing");
mDroidGap = (DroidGap)cordova.getActivity();
mBar = mDroidGap.getActionBar();
/* Hide the ActionBar until "init" is called from JS */
mDroidGap.runOnUiThread(new Runnable() {
@Override
public void run() {
mBar.hide();
}
});
mAssets = mDroidGap.getAssets();
mMenuItems = new HashMap<String, Actionable>();
Actionable.setAssetManager(mAssets);
}
// --- TabListener Interface Methods ------------------------------------------
/**
* Run the tab callback when the tab is selected.
*/
public void onTabSelected(Tab tab, FragmentTransaction ft)
{
String callbackId = (String)tab.getTag();
if (callbackId == null) {
return;
}
PluginResult res = new PluginResult(PluginResult.Status.OK);
res.setKeepCallback(true);
this.webView.sendPluginResult(res, callbackId);
}
/**
* Run the tab callback when the tab is re-selected.
*/
public void onTabReselected(Tab tab, FragmentTransaction ft)
{
String callbackId = (String)tab.getTag();
if (callbackId == null) {
return;
}
PluginResult res = new PluginResult(PluginResult.Status.OK);
res.setKeepCallback(true);
this.webView.sendPluginResult(res, callbackId);
}
/** Do nothing when the tab is unselected. */
public void onTabUnselected(Tab tab, FragmentTransaction ft) { }
// --- Cordova Plugin Interface Methods ---------------------------------------
@Override
public boolean execute(String action, JSONArray args, CallbackContext callback)
{
try
{
if (action.equals("init"))
{
// Nothing to do for init work on Android
callback.success();
return true;
}
else if (action.equals("update"))
{
JSONObject jsobj;
Boolean force = false;
if (args.length() > 0) {
jsobj = args.getJSONObject(0);
if (args.length() > 1) {
force = args.getBoolean(1);
}
}
else
{
jsobj = new JSONObject();
}
/* Check for the title string. */
String title = jsobj.optString("title");
if (!title.isEmpty() || force) {
this.updateTitle(title);
}
String nav = jsobj.optString("nav", "none");
NavType nt = NavType.parse(nav);
this.updateNavType(nt);
if (force)
{
mMenuItems.clear();
}
JSONArray acts = jsobj.optJSONArray("actions");
if (acts != null)
{
this.updateButtons(acts);
}
JSONArray menu = jsobj.optJSONArray("menu");
if (menu != null)
{
this.updateMenu(menu);
}
JSONArray tabs = jsobj.optJSONArray("tabs");
if (tabs != null)
{
this.updateTabs(tabs);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
{
mDroidGap.runOnUiThread(new Runnable() {
@Override
public void run() {
mDroidGap.invalidateOptionsMenu();
}
});
}
callback.success();
return true;
}
else if (action.equals("hide"))
{
mDroidGap.runOnUiThread(new Runnable() {
@Override
public void run() {
mBar.hide();
}
});
callback.success();
return true;
}
else if (action.equals("show"))
{
mDroidGap.runOnUiThread(new Runnable() {
@Override
public void run() {
mBar.show();
}
});
callback.success();
return true;
}
else
{
Log.v("Cambie", "Tried to call " + action);
callback.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION));
return false;
}
}
catch (JSONException e)
{
Log.v("Cambie", Log.getStackTraceString(e));
e.printStackTrace();
callback.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
return false;
}
}
@Override
public Object onMessage(String id, Object data)
{
if (id.equals("onCreateOptionsMenu") || id.equals("onPrepareOptionsMenu"))
{
mMenu = (Menu)data;
mMenu.clear();
this.buildMenu();
}
else if (id.equals("onOptionsItemSelected"))
{
MenuItem mi = (MenuItem)data;
if (mMenuItems.containsKey(mi.getTitle()))
{
Actionable act = mMenuItems.get(mi.getTitle());
PluginResult res = new PluginResult(PluginResult.Status.OK);
res.setKeepCallback(true);
this.webView.sendPluginResult(res, act.getCallbackId());
}
else
{
Log.v("Cambie", "Selected unknown menu item: " + mi.getTitle());
}
}
return null;
}
// --- Private Plugin Methods -------------------------------------------------
private void updateTitle(final String title)
{
mDroidGap.runOnUiThread(new Runnable() {
@Override
public void run() {
mBar.setTitle(title);
}
});
}
private void updateNavType(final NavType nav)
{
final Boolean enabled = (nav != NavType.NONE);
mDroidGap.runOnUiThread(new Runnable() {
@Override
public void run() {
mBar.setDisplayHomeAsUpEnabled(enabled);
}
});
}
private void updateButtons(final JSONArray buttons)
{
for (int i = 0; i < buttons.length(); i++)
{
try
{
JSONObject btn = buttons.getJSONObject(i);
Actionable action = Actionable.fromJSON(btn);
action.setFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
mMenuItems.put(action.getTitle(), action);
}
catch (Exception e)
{
Log.v("Cambie", Log.getStackTraceString(e));
}
}
}
private void updateMenu(final JSONArray menu)
{
for (int i = 0; i < menu.length(); i++)
{
try
{
JSONObject mi = menu.getJSONObject(i);
Actionable action = Actionable.fromJSON(mi);
action.setOrder(i);
mMenuItems.put(action.getTitle(), action);
}
catch (Exception e)
{
Log.v("Cambie", Log.getStackTraceString(e));
}
}
}
private void updateTabs(final JSONArray tabs)
{
for (int i = 0; i < tabs.length(); i++)
{
try
{
JSONObject mi = tabs.getJSONObject(i);
final Actionable action = Actionable.fromJSON(mi);
final TabListener self = this;
mDroidGap.runOnUiThread(new Runnable() {
@Override
public void run() {
Tab t = mBar.newTab();
t.setText(action.getTitle());
t.setTabListener(self);
t.setTag(action.getCallbackId());
if (action.getIcon() != null) {
t.setIcon(action.getIcon());
}
mBar.addTab(t);
if (action.isSelected())
{
mBar.selectTab(t);
}
}
});
}
catch (Exception e)
{
Log.v("Cambie", Log.getStackTraceString(e));
}
}
if (tabs.length() > 0)
{
mDroidGap.runOnUiThread(new Runnable() {
@Override
public void run() {
mBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
}
});
}
}
public void buildMenu()
{
for (Actionable act : mMenuItems.values())
{
MenuItem mi = mMenu.add(Menu.NONE, Menu.NONE, act.getOrder(), act.getTitle());
mi.setTitleCondensed(act.getTitle());
mi.setShowAsAction(act.getFlags());
if (act.isDisabled())
{
mi.setEnabled(false);
}
if (act.getIcon() != null)
{
mi.setIcon(act.getIcon());
}
}
}
}
| |
/*
* Copyright 2015 HE5ED.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.he5ed.lib.cloudprovider.apis;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import com.he5ed.lib.cloudprovider.CloudProvider;
import com.he5ed.lib.cloudprovider.R;
import com.he5ed.lib.cloudprovider.auth.Authenticator;
import com.he5ed.lib.cloudprovider.exceptions.RequestFailException;
import com.he5ed.lib.cloudprovider.models.CFile;
import com.he5ed.lib.cloudprovider.models.CFolder;
import com.he5ed.lib.cloudprovider.models.User;
import com.he5ed.lib.cloudprovider.utils.FilesUtils;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import okio.BufferedSink;
/**
* Microsoft OneDrive cloud service API implementation
*
* @hide
*/
public class OneDriveApi extends BaseApi {
// API server constant values
public static final String AUTH_URL = "https://login.live.com/oauth20_authorize.srf";
public static final String TOKEN_URL = "https://login.live.com/oauth20_token.srf";
public static final String REVOKE_URL = "https://login.live.com/oauth20_logout.srf";
public static final String LIVE_API_URL = "https://apis.live.net/v5.0";
public static final String API_BASE_URL = "https://api.onedrive.com/v1.0";
public static final String ROOT_ID = "root";
public static final String ROOT_PATH = "/drive/root:";
/**
* Must override with the correct values
*/
public static String CLIENT_ID = null;
public static String CLIENT_SECRET = null;
public static String REDIRECT_URL = null;
// enable API
public static boolean ENABLE_API = false;
// class constant values
public static final String NAME = "Microsoft OneDrive";
public static final int ICON_RESOURCE = R.drawable.ic_onedrive_color_24dp;
public static final String TAG = "OneDriveApi";
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
/**
* Build authorization url base on type of cloud service
*
* @return Uri
*/
public static Uri buildAuthUri(String stateString) {
Uri uri = Uri.parse(AUTH_URL);
return uri.buildUpon()
.appendQueryParameter("response_type", "code")
.appendQueryParameter("client_id", CLIENT_ID)
.appendQueryParameter("redirect_uri", REDIRECT_URL)
.appendQueryParameter("state", stateString)
.appendQueryParameter("scope", "wl.emails wl.offline_access onedrive.readwrite")
.build();
}
/**
* Get parameters to be passed to Volley request to get access token
*
* @param authCode code from authorization process
* @return RequestBody
*/
public static RequestBody getAccessTokenBody(String authCode) {
return new FormEncodingBuilder()
.addEncoded("grant_type", "authorization_code")
.addEncoded("code", authCode)
.addEncoded("client_id", CLIENT_ID)
.addEncoded("client_secret", CLIENT_SECRET)
.addEncoded("redirect_uri", REDIRECT_URL)
.build();
}
/**
* Build form body to be passed to access token
*
* @param refreshToken code from authorization process
* @return RequestBody
*/
public static RequestBody getRefreshTokenBody(String refreshToken) {
return new FormEncodingBuilder()
.addEncoded("grant_type", "refresh_token")
.addEncoded("refresh_token", refreshToken)
.addEncoded("client_id", CLIENT_ID)
.addEncoded("client_secret", CLIENT_SECRET)
.addEncoded("redirect_uri", REDIRECT_URL)
.build();
}
/**
* Extract access token from the JSONObject
*
* @param jsonObject JSONObject that contain access token
* @return Map
* @throws JSONException
*/
public static Map<String, String> extractAccessToken(JSONObject jsonObject) throws JSONException {
Map<String, String> map = new HashMap<>();
map.put(Authenticator.KEY_ACCESS_TOKEN, jsonObject.getString("access_token"));
map.put(Authenticator.KEY_EXPIRY, String.valueOf(jsonObject.getLong("expires_in")));
map.put(Authenticator.KEY_REFRESH_TOKEN, jsonObject.getString("refresh_token"));
return map;
}
/**
* Get current user information uri
*
* @return Uri
*/
public static Uri getUserInfoUri() {
Uri uri = Uri.parse(LIVE_API_URL);
return uri.buildUpon().appendEncodedPath("me").build();
}
/**
* Create request to get user information
*
* @param accessToken access token for authorization
* @return Request
*/
public static Request getUserInfoRequest(String accessToken) {
return new Request.Builder()
.url(getUserInfoUri().toString())
.addHeader("Authorization", String.format("Bearer %s", accessToken))
.build();
}
/**
* Extract user information from the JSONObject
*
* @param jsonObject JSONObject that contain user information
* @return User
* @throws JSONException
*/
public static User extractUser(JSONObject jsonObject) throws JSONException {
User user = new User();
user.id = jsonObject.getString("id");
user.name = jsonObject.getString("name");
user.displayName = jsonObject.getString("name");
JSONObject emails = jsonObject.getJSONObject("emails");
user.email = emails.getString("account");
return user;
}
/**
* Build folder from JSONObject
*
* @param jsonObject from http response
* @return CFolder
*/
public static CFolder buildFolder(JSONObject jsonObject) {
Map<String, Object> map = new HashMap<>();
try {
map.put(CFolder.ID, jsonObject.getString("id"));
map.put(CFolder.NAME, jsonObject.getString("name"));
map.put(CFolder.DATE_FORMAT, "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
if (jsonObject.has("createdDateTime"))
map.put(CFolder.CREATED, jsonObject.getString("createdDateTime"));
if (jsonObject.has("lastModifiedDateTime"))
map.put(CFolder.MODIFIED, jsonObject.getString("lastModifiedDateTime"));
} catch (JSONException e) {
e.printStackTrace();
return null;
}
return new CFolder(map);
}
/**
* Build file from JSONObject
*
* @param jsonObject from http response
* @return CFolder
*/
public static CFile buildFile(JSONObject jsonObject) {
Map<String, Object> map = new HashMap<>();
try {
map.put(CFolder.ID, jsonObject.getString("id"));
map.put(CFolder.NAME, jsonObject.getString("name"));
map.put(CFolder.DATE_FORMAT, "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
if (jsonObject.has("createdDateTime"))
map.put(CFolder.CREATED, jsonObject.getString("createdDateTime"));
if (jsonObject.has("lastModifiedDateTime"))
map.put(CFolder.MODIFIED, jsonObject.getString("lastModifiedDateTime"));
} catch (JSONException e) {
e.printStackTrace();
return null;
}
return new CFile(map);
}
private Context mContext;
private CloudProvider mCloudProvider;
private Account mAccount;
private BaseApi.OnPrepareListener mPrepareListener;
private OkHttpClient mHttpClient;
private String mAccessToken;
/**
* Constructor for OneDrive API
*
* @param account to be used must be OneDrive cloud type
*/
public OneDriveApi(Context context, Account account) {
mContext = context;
mAccount = account;
mCloudProvider = CloudProvider.getInstance(mContext);
mHttpClient = new OkHttpClient();
}
@Override
public synchronized void prepareApi(BaseApi.OnPrepareListener prepareListener) {
mPrepareListener = prepareListener;
AccountManager.get(mContext).getAuthToken(mAccount, CloudProvider.AUTH_TYPE, false,
new AccountManagerCallback<Bundle>() {
@Override
public void run(AccountManagerFuture<Bundle> future) {
try {
mAccessToken = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
validateAccessToken();
} catch (OperationCanceledException e) {
e.printStackTrace();
Log.e(TAG, e.getMessage());
if (mPrepareListener != null)
mPrepareListener.onPrepareFail(e);
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, e.getMessage());
if (mPrepareListener != null)
mPrepareListener.onPrepareFail(e);
} catch (AuthenticatorException e) {
e.printStackTrace();
Log.e(TAG, e.getMessage());
if (mPrepareListener != null)
mPrepareListener.onPrepareFail(e);
}
}
}, null);
}
/**
* Ensure that the access token is still valid
* Access token can be expired or revoked by user
* Try to refresh the access token if it is expired
*/
private void validateAccessToken() {
Request request = getUserInfoRequest(mAccessToken);
mHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
e.printStackTrace();
if (mPrepareListener != null)
mPrepareListener.onPrepareFail(e);
Log.e(TAG, e.getMessage());
}
@Override
public void onResponse(Response response) throws IOException {
if (response.isSuccessful() && response.code() == 200) {
if (mPrepareListener != null)
mPrepareListener.onPrepareSuccessful();
} else {
switch (response.code()) {
case 401:
// unauthorized
refreshAccessToken();
break;
default:
break;
}
Log.e(TAG, response.code() + ": " + response.body().string());
}
}
});
}
/**
* Try to get a fresh access token using the refresh token
*/
private void refreshAccessToken() {
final String refreshToken = mCloudProvider.getUserData(mAccount, Authenticator.KEY_REFRESH_TOKEN);
if (!TextUtils.isEmpty(refreshToken)) {
Request request = new Request.Builder()
.url(TOKEN_URL)
.post(getRefreshTokenBody(refreshToken))
.build();
mHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
e.printStackTrace();
Log.e(TAG, e.getMessage());
resetAccount();
}
@Override
public void onResponse(Response response) throws IOException {
if (response.isSuccessful()) {
// convert string into json
try {
JSONObject jsonObject = new JSONObject(response.body().string());
Map<String, String> tokenInfo = extractAccessToken(jsonObject);
mCloudProvider.updateAccount(mAccount, tokenInfo);
mAccessToken = tokenInfo.get(Authenticator.KEY_ACCESS_TOKEN);
// validate again
validateAccessToken();
} catch (JSONException e) {
e.printStackTrace();
Log.e(TAG, e.getMessage());
}
} else {
Log.e(TAG, response.code() + ": " + response.body().string());
resetAccount();
}
}
});
} else {
resetAccount();
}
}
/**
* Remove the staled account and add a new one
*/
private void resetAccount() {
logout(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
}
@Override
public void onResponse(Response response) throws IOException {
}
});
// use Authenticator to update account
mCloudProvider.removeAccount(mAccount);
mCloudProvider.addAccount(getClass().getCanonicalName(), (Activity) mContext);
}
@Override
public void logout(@NonNull Callback callback) {
RequestBody body = new FormEncodingBuilder()
.add("client_id", CLIENT_ID)
.add("client_secret", CLIENT_SECRET)
.add("token", mAccessToken)
.build();
Request request = new Request.Builder()
.url(REVOKE_URL)
.post(body)
.build();
mHttpClient.newCall(request).enqueue(callback);
}
@Override
public synchronized List<Object> exploreFolder(@NonNull CFolder folder, int offset) throws RequestFailException {
if (TextUtils.isEmpty(mAccessToken)) {
throw new RequestFailException("Access token not available");
}
List<Object> list = new ArrayList<>();
Request request = new Request.Builder()
.url(API_BASE_URL + "/drive/items/" + folder.getId() + "/children")
.header("Authorization", String.format("Bearer %s", mAccessToken))
.get()
.build();
try {
Response response = mHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
JSONObject jsonObject = new JSONObject(response.body().string());
JSONArray entries = jsonObject.getJSONArray("value");
if (entries.length() > 0) {
list.addAll(createFilteredItemsList(entries, null));
} else {
// return null if no item found
return null;
}
// pagination available
if (jsonObject.has("@odata.nextLink")) {
list.addAll(exploreFolderContinue(jsonObject.getString("@odata.nextLink")));
}
return list;
} else {
throw new RequestFailException(response.message(), response.code());
}
} catch (JSONException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
}
}
/**
* Get continue folder items
*
* @param url for the next page of items
* @return List that contains CFile and CFolder
* @throws RequestFailException that content various error types
*/
public synchronized List<Object> exploreFolderContinue(String url) throws RequestFailException {
if (TextUtils.isEmpty(mAccessToken)) {
throw new RequestFailException("Access token not available");
}
List<Object> list = new ArrayList<>();
Request request = new Request.Builder()
.url(url)
.header("Authorization", String.format("Bearer %s", mAccessToken))
.get()
.build();
try {
Response response = mHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
JSONObject jsonObject = new JSONObject(response.body().string());
JSONArray entries = jsonObject.getJSONArray("data");
if (entries.length() > 0) {
list.addAll(createFilteredItemsList(entries, null));
} else {
// return null if no item found
return null;
}
// pagination available
if (jsonObject.has("@odata.nextLink")) {
list.addAll(exploreFolderContinue(jsonObject.getString("@odata.nextLink")));
}
return list;
} else {
throw new RequestFailException(response.message(), response.code());
}
} catch (JSONException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
}
}
@Override
public CFolder getRoot() {
// create root folder manually
CFolder root = new CFolder(null);
root.setId(ROOT_ID);
root.setPath(ROOT_PATH);
root.setName(mContext.getString(R.string.home_folder_title));
root.setRoot(true);
return root;
}
@Override
public CFolder getFolderInfo(@NonNull String folderId) throws RequestFailException {
if (TextUtils.isEmpty(mAccessToken)) {
throw new RequestFailException("Access token not available");
}
if (TextUtils.isEmpty(folderId)) return null;
Request request = new Request.Builder()
.url(API_BASE_URL + "/drive/items/" + folderId)
.header("Authorization", String.format("Bearer %s", mAccessToken))
.get()
.build();
try {
Response response = mHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
// new file created
JSONObject jsonObject = new JSONObject(response.body().string());
return buildFolder(jsonObject);
} else {
throw new RequestFailException(response.message(), response.code());
}
} catch (JSONException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
}
}
@Override
public CFolder createFolder(@NonNull String name, @Nullable CFolder parent) throws RequestFailException {
if (TextUtils.isEmpty(mAccessToken)) {
throw new RequestFailException("Access token not available");
}
// create parameter as json
final JSONObject params= new JSONObject();
try {
params.put("name", name);
params.put("folder", new JSONObject());
params.put("@name.conflictBehavior", "fail");
} catch (JSONException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
}
RequestBody body = new RequestBody() {
@Override
public MediaType contentType() {
return JSON;
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
sink.writeUtf8(params.toString());
}
};
Request request = new Request.Builder()
.url(API_BASE_URL + "/drive/items/" +
(parent != null ? parent.getId() : getRoot().getId()) + "/children")
.header("Authorization", String.format("Bearer %s", mAccessToken))
.post(body)
.build();
try {
Response response = mHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
JSONObject jsonObject = new JSONObject(response.body().string());
return buildFolder(jsonObject);
} else {
throw new RequestFailException(response.message(), response.code());
}
} catch (JSONException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
}
}
@Override
public CFolder renameFolder(@NonNull CFolder folder, String name) throws RequestFailException {
if (TextUtils.isEmpty(mAccessToken)) {
throw new RequestFailException("Access token not available");
}
// exit if root or same name
if (folder.isRoot() || folder.getName().equals(name)) return folder;
// create parameter as json
final JSONObject params= new JSONObject();
try {
params.put("name", name);
} catch (JSONException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
}
RequestBody body = new RequestBody() {
@Override
public MediaType contentType() {
return JSON;
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
sink.writeUtf8(params.toString());
}
};
Request request = new Request.Builder()
.url(API_BASE_URL + "/drive/items/" + folder.getId())
.header("Authorization", String.format("Bearer %s", mAccessToken))
.patch(body)
.build();
try {
Response response = mHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
// return folder object
return buildFolder(new JSONObject(response.body().string()));
} else {
throw new RequestFailException(response.message(), response.code());
}
} catch (JSONException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
}
}
@Override
public CFolder moveFolder(@NonNull CFolder folder, @Nullable CFolder parent) throws RequestFailException {
if (TextUtils.isEmpty(mAccessToken)) {
throw new RequestFailException("Access token not available");
}
// exit if root or same name
if (folder.isRoot() || parent != null && folder.getId().equals(parent.getId())) return folder;
// create parameter as json
final JSONObject params= new JSONObject();
try {
params.put("parentReference", new JSONObject()
.put("id", parent != null ? parent.getId() : getRoot().getId()));
} catch (JSONException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
}
RequestBody body = new RequestBody() {
@Override
public MediaType contentType() {
return JSON;
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
sink.writeUtf8(params.toString());
}
};
Request request = new Request.Builder()
.url(API_BASE_URL + "/drive/items/" + folder.getId())
.header("Authorization", String.format("Bearer %s", mAccessToken))
.patch(body)
.build();
try {
Response response = mHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
// return folder object
return buildFolder(new JSONObject(response.body().string()));
} else {
throw new RequestFailException(response.message(), response.code());
}
} catch (JSONException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
}
}
@Override
public void deleteFolder(@NonNull CFolder folder) throws RequestFailException {
if (TextUtils.isEmpty(mAccessToken)) {
throw new RequestFailException("Access token not available");
}
Request request = new Request.Builder()
.url(API_BASE_URL + "/drive/items/" + folder.getId())
.header("Authorization", String.format("Bearer %s", mAccessToken))
.delete()
.build();
try {
Response response = mHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
Log.d(TAG, "CFolder with the id: " + folder.getName() + " deleted");
} else {
throw new RequestFailException(response.message(), response.code());
}
} catch (IOException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
}
}
@Override
public CFile getFileInfo(@NonNull String fileId) throws RequestFailException {
if (TextUtils.isEmpty(mAccessToken)) {
throw new RequestFailException("Access token not available");
}
if (TextUtils.isEmpty(fileId)) return null;
Request request = new Request.Builder()
.url(API_BASE_URL + "/drive/items/" + fileId)
.header("Authorization", String.format("Bearer %s", mAccessToken))
.get()
.build();
try {
Response response = mHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
// new file created
JSONObject jsonObject = new JSONObject(response.body().string());
return buildFile(jsonObject);
} else {
throw new RequestFailException(response.message(), response.code());
}
} catch (JSONException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
}
}
@Override
public CFile uploadFile(@NonNull final File file, @Nullable CFolder parent) throws RequestFailException {
if (TextUtils.isEmpty(mAccessToken)) {
throw new RequestFailException("Access token not available");
}
Uri uri = Uri.parse(API_BASE_URL);
String url = uri.buildUpon()
.appendEncodedPath("drive/items/" +
(parent != null ? parent.getId() : getRoot().getId()) + "/children/" +
file.getName() + "/content")
.appendQueryParameter("@name.conflictBehavior", "fail")
.build()
.toString();
RequestBody fileBody = new RequestBody() {
@Override
public MediaType contentType() {
return null;
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
// copy file into RequestBody
FilesUtils.copyFile(new FileInputStream(file), sink.outputStream());
}
};
Request request = new Request.Builder()
.url(url)
.header("Authorization", String.format("Bearer %s", mAccessToken))
.put(fileBody)
.build();
try {
Response response = mHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
// new file created
JSONObject jsonObject = new JSONObject(response.body().string());
return buildFile(jsonObject);
} else {
throw new RequestFailException(response.message(), response.code());
}
} catch (JSONException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
}
}
@Override
public CFile updateFile(@NonNull CFile file, final File content) throws RequestFailException {
if (TextUtils.isEmpty(mAccessToken)) {
throw new RequestFailException("Access token not available");
}
Uri uri = Uri.parse(API_BASE_URL);
String url = uri.buildUpon()
.appendEncodedPath("drive/items/" + file.getId() + "/content")
.appendQueryParameter("@name.conflictBehavior", "replace")
.build()
.toString();
RequestBody fileBody = new RequestBody() {
@Override
public MediaType contentType() {
return null;
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
// copy file into RequestBody
FilesUtils.copyFile(new FileInputStream(content), sink.outputStream());
}
};
Request request = new Request.Builder()
.url(url)
.header("Authorization", String.format("Bearer %s", mAccessToken))
.put(fileBody)
.build();
try {
Response response = mHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
// new file created
JSONObject jsonObject = new JSONObject(response.body().string());
return buildFile(jsonObject);
} else {
throw new RequestFailException(response.message(), response.code());
}
} catch (JSONException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
}
}
@Override
public CFile renameFile(@NonNull CFile file, String name) throws RequestFailException {
if (TextUtils.isEmpty(mAccessToken)) {
throw new RequestFailException("Access token not available");
}
// exist if same filename
if (file.getName().equals(name)) return file;
// create parameter as json
final JSONObject params= new JSONObject();
try {
params.put("name", name);
} catch (JSONException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
}
RequestBody body = new RequestBody() {
@Override
public MediaType contentType() {
return JSON;
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
sink.writeUtf8(params.toString());
}
};
Request request = new Request.Builder()
.url(API_BASE_URL + "/drive/items/" + file.getId())
.header("Authorization", String.format("Bearer %s", mAccessToken))
.patch(body)
.build();
try {
Response response = mHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
// return file object
return buildFile(new JSONObject(response.body().string()));
} else {
throw new RequestFailException(response.message(), response.code());
}
} catch (JSONException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
}
}
@Override
public CFile moveFile(@NonNull CFile file, @Nullable CFolder folder) throws RequestFailException {
if (TextUtils.isEmpty(mAccessToken)) {
throw new RequestFailException("Access token not available");
}
// create parameter as json
final JSONObject params= new JSONObject();
try {
params.put("parentReference", new JSONObject()
.put("id", folder != null ? folder.getId() : getRoot().getId()));
} catch (JSONException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
}
RequestBody body = new RequestBody() {
@Override
public MediaType contentType() {
return JSON;
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
sink.writeUtf8(params.toString());
}
};
Request request = new Request.Builder()
.url(API_BASE_URL + "/drive/items/" + file.getId())
.header("Authorization", String.format("Bearer %s", mAccessToken))
.patch(body)
.build();
try {
Response response = mHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
// return file object
return buildFile(new JSONObject(response.body().string()));
} else {
throw new RequestFailException(response.message(), response.code());
}
} catch (JSONException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
}
}
@Override
public File downloadFile(@NonNull CFile file, String filename) throws RequestFailException {
if (TextUtils.isEmpty(mAccessToken)) {
throw new RequestFailException("Access token not available");
}
// assign filename
if (TextUtils.isEmpty(filename)) filename = file.getName();
Request request = new Request.Builder()
.url(API_BASE_URL + "/drive/items/" + file.getId() + "/content")
.header("Authorization", String.format("Bearer %s", mAccessToken))
.get()
.build();
try {
Response response = mHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
switch (response.code()) {
case 200:
// redirect to url
return downloadFile(response.request(), filename);
case 302:
// redirect to url
return downloadFile(response.request(), filename);
}
} else {
throw new RequestFailException(response.message(), response.code());
}
} catch (IOException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
}
return null;
}
/**
* Download file from redirect request
*
* @param request for redirect
* @return File
* @throws RequestFailException
*/
public synchronized File downloadFile(@NonNull Request request, String filename) throws RequestFailException {
try {
File file = new File(mContext.getFilesDir(),
TextUtils.isEmpty(filename) ? "Untitled" : filename);
Response response = mHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
FilesUtils.copyFile(response.body().byteStream(), new FileOutputStream(file));
} else {
throw new RequestFailException(response.message(), response.code());
}
return file;
} catch (IOException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
}
}
@Override
public void deleteFile(@NonNull CFile file) throws RequestFailException {
if (TextUtils.isEmpty(mAccessToken)) {
throw new RequestFailException("Access token not available");
}
Request request = new Request.Builder()
.url(API_BASE_URL + "/drive/items/" + file.getId())
.header("Authorization", String.format("Bearer %s", mAccessToken))
.delete()
.build();
try {
Response response = mHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
Log.d(TAG, "File with the id: " + file.getName() + " deleted");
} else {
throw new RequestFailException(response.message(), response.code());
}
} catch (IOException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
}
}
@Override
public List<CFile> searchFile(@NonNull String keyword, CFolder folder) throws RequestFailException {
// check cast for search result
List<CFile> output = new ArrayList<>();
for (Object item : search(keyword, folder)) {
if (CFile.class.isAssignableFrom(item.getClass()))
output.add(CFile.class.cast(item));
}
return output;
}
@Override
public List<CFolder> searchFolder(@NonNull String keyword, CFolder folder) throws RequestFailException {
// check cast for search result
List<CFolder> output = new ArrayList<>();
for (Object item : search(keyword, folder)) {
if (CFolder.class.isAssignableFrom(item.getClass()))
output.add(CFolder.class.cast(item));
}
return output;
}
@Override
public List<Object> search(@NonNull String keyword, CFolder folder) throws RequestFailException {
if (TextUtils.isEmpty(mAccessToken)) {
throw new RequestFailException("Access token not available");
}
List<Object> list = new ArrayList<>();
Uri uri = Uri.parse(API_BASE_URL);
String url = uri.buildUpon()
.appendEncodedPath("drive/items/" + folder.getId() + "/view.search")
.appendQueryParameter("q", keyword)
.build()
.toString();
Request request = new Request.Builder()
.url(url)
.header("Authorization", String.format("Bearer %s", mAccessToken))
.get()
.build();
try {
Response response = mHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
JSONObject jsonObject = new JSONObject(response.body().string());
JSONArray entries = jsonObject.getJSONArray("value");
if (entries.length() > 0) {
list.addAll(createFilteredItemsList(entries, folder));
} else {
// return null if no item found
return null;
}
// pagination available
if (jsonObject.has("@odata.nextLink")) {
list.addAll(searchContinue(jsonObject.getString("@odata.nextLink"), folder));
}
return list;
} else {
throw new RequestFailException(response.message(), response.code());
}
} catch (JSONException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
}
}
/**
* Get continue search items
*
* @param url for the next page of items
* @param folder where the search is looking at
* @return List that contains CFile and CFolder
* @throws RequestFailException that content various error types
*/
public synchronized List<Object> searchContinue(String url, CFolder folder) throws RequestFailException {
if (TextUtils.isEmpty(mAccessToken)) {
throw new RequestFailException("Access token not available");
}
List<Object> list = new ArrayList<>();
Request request = new Request.Builder()
.url(url)
.header("Authorization", String.format("Bearer %s", mAccessToken))
.get()
.build();
try {
Response response = mHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
JSONObject jsonObject = new JSONObject(response.body().string());
JSONArray entries = jsonObject.getJSONArray("data");
if (entries.length() > 0) {
list.addAll(createFilteredItemsList(entries, folder));
} else {
// return null if no item found
return null;
}
// pagination available
if (jsonObject.has("@odata.nextLink")) {
list.addAll(searchContinue(jsonObject.getString("@odata.nextLink"), folder));
}
return list;
} else {
throw new RequestFailException(response.message(), response.code());
}
} catch (JSONException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
}
}
@Override
public File getThumbnail(@NonNull CFile file) throws RequestFailException {
if (TextUtils.isEmpty(mAccessToken)) {
throw new RequestFailException("Access token not available");
}
Request request = new Request.Builder()
.url(API_BASE_URL + "/drive/items/" + file.getId() + "/thumbnails/0/medium/content")
.header("Authorization", String.format("Bearer %s", mAccessToken))
.get()
.build();
try {
Response response = mHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
switch (response.code()) {
case 200:
// redirect to url
return downloadFile(response.request(), file.getId() + ".jpg");
case 302:
// redirect to url
return downloadFile(response.request(), file.getId() + ".jpg");
}
} else {
throw new RequestFailException(response.message(), response.code());
}
} catch (IOException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
}
return null;
}
/**
* Create files or folders from the JSONArray search result
*
* @param jsonArray that contain files and folders information
* @param parent folder that contain the items returned
* @return list that contains CFile and CFolder that belong to the parent folder
* @throws RequestFailException
*/
private List<Object> createFilteredItemsList(JSONArray jsonArray, CFolder parent) throws RequestFailException {
if (jsonArray == null || jsonArray.length() == 0) return null;
List<Object> list = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// filter parent
JSONObject parentReference = jsonObject.getJSONObject("parentReference");
if (parent != null &&
!parentReference.getString("id").equals(parent.getId()) &&
!parentReference.getString("path").equals(parent.getPath()))
continue;
if (jsonObject.has("file")) {
list.add(buildFile(jsonObject));
} else if (jsonObject.has("folder")) {
list.add(buildFolder(jsonObject));
} else {
Log.e(TAG, "Unknown type found");
}
} catch (JSONException e) {
e.printStackTrace();
throw new RequestFailException(e.getMessage());
}
}
return list;
}
}
| |
/*
* 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.ode.utils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamSource;
import net.sf.saxon.om.Name11Checker;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ode.utils.sax.LoggingErrorHandler;
import org.apache.xerces.dom.DOMOutputImpl;
import org.apache.xerces.impl.Constants;
import org.apache.xml.serialize.DOMSerializerImpl;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* Utility class for dealing with the Document Object Model (DOM).
*/
public class DOMUtils {
private static Log __log = LogFactory.getLog(DOMUtils.class);
/** The namespaceURI represented by the prefix <code>xmlns</code>. */
public static final String NS_URI_XMLNS = "http://www.w3.org/2000/xmlns/";
private static ThreadLocal<Transformer> __txers = new ThreadLocal();
private static ThreadLocal<DocumentBuilder> __builders = new ThreadLocal();
private static TransformerFactory _transformerFactory = TransformerFactory.newInstance();
private static DocumentBuilderFactory __documentBuilderFactory ;
static {
initDocumentBuilderFactory();
}
/**
* Initialize the document-builder factory.
*/
private static void initDocumentBuilderFactory() {
DocumentBuilderFactory f = XMLParserUtils.getDocumentBuilderFactory();
f.setNamespaceAware(true);
__documentBuilderFactory = f;
}
/**
* Returns the value of an attribute of an element. Returns null if the
* attribute is not found (whereas Element.getAttribute returns "" if an
* attrib is not found).
*
* @param el Element whose attrib is looked for
* @param attrName name of attribute to look for
*
* @return the attribute value
*/
static public String getAttribute(Element el, String attrName) {
String sRet = null;
Attr attr = el.getAttributeNode(attrName);
if (attr != null) {
sRet = attr.getValue();
}
return sRet;
}
/**
* @deprecated relies on XMLSerializer which is a deprecated Xerces class, use domToString instead
*/
static public String prettyPrint(Element e) throws IOException {
OutputFormat format = new OutputFormat(e.getOwnerDocument());
format.setLineWidth(65);
format.setIndenting(true);
format.setIndent(2);
StringWriter out = new StringWriter();
XMLSerializer serializer = new XMLSerializer(out, format);
serializer.serialize(e);
return out.toString();
}
/**
* Returns the value of an attribute of an element. Returns null if the
* attribute is not found (whereas Element.getAttributeNS returns "" if an
* attrib is not found).
*
* @param el Element whose attrib is looked for
* @param namespaceURI namespace URI of attribute to look for
* @param localPart local part of attribute to look for
*
* @return the attribute value
*/
static public String getAttributeNS(Element el, String namespaceURI,
String localPart) {
String sRet = null;
Attr attr = el.getAttributeNodeNS(namespaceURI, localPart);
if (attr != null) {
sRet = attr.getValue();
}
return sRet;
}
/**
* Concat all the text and cdata node children of this elem and return the
* resulting text.
*
* @param parentEl the element whose cdata/text node values are to be
* combined.
*
* @return the concatanated string.
*/
static public String getChildCharacterData(Element parentEl) {
if (parentEl == null) { return null; }
Node tempNode = parentEl.getFirstChild();
StringBuffer strBuf = new StringBuffer();
CharacterData charData;
while (tempNode != null) {
switch (tempNode.getNodeType()) {
case Node.TEXT_NODE:
case Node.CDATA_SECTION_NODE:
charData = (CharacterData) tempNode;
strBuf.append(charData.getData());
break;
}
tempNode = tempNode.getNextSibling();
}
return strBuf.toString();
}
/**
* DOCUMENTME
*
* @param el DOCUMENTME
* @param id DOCUMENTME
*
* @return DOCUMENTME
*/
public static Element getElementByID(Element el, String id) {
if (el == null) { return null; }
String thisId = el.getAttribute("id");
if (id.equals(thisId)) { return el; }
NodeList list = el.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
if (node instanceof Element) {
Element ret = getElementByID((Element) node, id);
if (ret != null) { return ret; }
}
}
return null;
}
/**
* Return the first child element of the given element. Null if no children
* are found.
*
* @param elem Element whose child is to be returned
*
* @return the first child element.
*/
public static Element getFirstChildElement(Element elem) {
return (Element) findChildByType(elem, Node.ELEMENT_NODE);
}
/**
* Given a prefix and a node, return the namespace URI that the prefix has
* been associated with. This method is useful in resolving the namespace
* URI of attribute values which are being interpreted as QNames. If prefix
* is null, this method will return the default namespace.
*
* @param context the starting node (looks up recursively from here)
* @param prefix the prefix to find an xmlns:prefix=uri for
*
* @return the namespace URI or null if not found
*/
public static String getNamespaceURIFromPrefix(Node context, String prefix) {
short nodeType = context.getNodeType();
Node tempNode = null;
switch (nodeType) {
case Node.ATTRIBUTE_NODE: {
tempNode = ((Attr) context).getOwnerElement();
break;
}
case Node.ELEMENT_NODE: {
tempNode = context;
break;
}
default: {
tempNode = context.getParentNode();
break;
}
}
while ((tempNode != null) && (tempNode.getNodeType() == Node.ELEMENT_NODE)) {
Element tempEl = (Element) tempNode;
String namespaceURI = (prefix == null) ? getAttribute(tempEl, "xmlns")
: getAttributeNS(tempEl, NS_URI_XMLNS, prefix);
if (namespaceURI != null) {
return namespaceURI;
}
tempNode = tempEl.getParentNode();
}
return null;
}
/**
* Return the next sibling element of the given element. Null if no more
* sibling elements are found.
*
* @param elem Element whose sibling element is to be returned
*
* @return the next sibling element.
*/
public static Element getNextSiblingElement(Element elem) {
for (Node n = elem.getNextSibling(); n != null; n = n.getNextSibling()) {
if (n.getNodeType() == Node.ELEMENT_NODE) { return (Element) n; }
}
return null;
}
/**
* DOCUMENTME
*
* @param el DOCUMENTME
* @param attrName DOCUMENTME
*
* @return DOCUMENTME
*
* @throws IllegalArgumentException DOCUMENTME
*/
public static QName getQualifiedAttributeValue(Element el, String attrName)
throws IllegalArgumentException {
String attrValue = DOMUtils.getAttribute(el, attrName);
if (attrValue != null) {
int index = attrValue.indexOf(':');
String attrValuePrefix = (index != -1) ? attrValue.substring(0, index)
: null;
String attrValueLocalPart = attrValue.substring(index + 1);
String attrValueNamespaceURI = DOMUtils.getNamespaceURIFromPrefix(el,
attrValuePrefix);
if (attrValueNamespaceURI != null) {
return new QName(attrValueNamespaceURI, attrValueLocalPart);
}
throw new IllegalArgumentException("Unable to determine "
+ "namespace of '"
+ ((attrValuePrefix != null) ? (attrValuePrefix + ":") : "")
+ attrValueLocalPart + "'.");
}
return null;
}
/**
* Count number of children of a certain type of the given element.
*
* @param elem the element whose kids are to be counted
* @param nodeType DOCUMENTME
*
* @return the number of matching kids.
*/
public static int countKids(Element elem, short nodeType) {
int nkids = 0;
for (Node n = elem.getFirstChild(); n != null; n = n.getNextSibling()) {
if (n.getNodeType() == nodeType) {
nkids++;
}
}
return nkids;
}
/**
* This method traverses the DOM and grabs namespace declarations
* on parent elements with the intent of preserving them for children. <em>Note
* that the DOM level 3 document method {@link Element#getAttribute(java.lang.String)}
* is not desirable in this case, as it does not respect namespace prefix
* bindings that may affect attribute values. (Namespaces in DOM are
* uncategorically a mess, especially in the context of XML Schema.)</em>
* @param el the starting element
* @return a {@link Map} containing prefix bindings.
*/
public static Map<String, String> getParentNamespaces(Element el) {
HashMap<String,String> pref = new HashMap<String,String>();
Map<String,String> mine = getMyNamespaces(el);
Node n = el.getParentNode();
while (n != null && n.getNodeType() != Node.DOCUMENT_NODE) {
if (n instanceof Element) {
Element l = (Element) n;
NamedNodeMap nnm = l.getAttributes();
int len = nnm.getLength();
for (int i = 0; i < len; ++i) {
Attr a = (Attr) nnm.item(i);
if (isNSAttribute(a)) {
String key = getNSPrefixFromNSAttr(a);
String uri = a.getValue();
// prefer prefix bindings that are lower down in the tree.
if (pref.containsKey(key) || mine.containsKey(key)) continue;
pref.put(key, uri);
}
}
}
n = n.getParentNode();
}
return pref;
}
/**
* Construct a {@link NSContext} instance for the supplied element.
* @param el the <code>Element</code> to gather the namespace context for
* @return the <code>NSContext</code>
*/
public static NSContext getMyNSContext(Element el) {
NSContext ns = new NSContext();
ns.register(getParentNamespaces(el));
ns.register(getMyNamespaces(el));
return ns;
}
public static Map<String,String> getMyNamespaces(Element el) {
HashMap<String,String> mine = new HashMap<String,String>();
NamedNodeMap nnm = el.getAttributes();
int len = nnm.getLength();
for (int i=0; i < len; ++i) {
Attr a = (Attr) nnm.item(i);
if (isNSAttribute(a)) {
mine.put(getNSPrefixFromNSAttr(a),a.getValue());
}
}
return mine;
}
/**
* Test whether an attribute contains a namespace declaration.
* @param a an {@link Attr} to test.
* @return <code>true</code> if the {@link Attr} is a namespace declaration
*/
public static boolean isNSAttribute(Attr a) {
assert a != null;
String s = a.getNamespaceURI();
return (s != null && s.equals(NS_URI_XMLNS));
}
/**
* Fetch the non-null namespace prefix from a {@link Attr} that declares
* a namespace. (The DOM APIs will return <code>null</code> for a non-prefixed
* declaration.
* @param a the {@link Attr} with the declaration (must be non-<code>null</code).
* @return the namespace prefix or <code>""</code> if none was
* declared, e.g., <code>xmlns="foo"</code>.
*/
public static String getNSPrefixFromNSAttr(Attr a) {
assert a != null;
assert isNSAttribute(a);
if (a.getPrefix() == null) {
return "";
}
return a.getName().substring(a.getPrefix().length()+1);
}
/**
* Convert a DOM node to a stringified XML representation.
*/
static public String domToString(Node node) {
if (node == null) {
throw new IllegalArgumentException("Cannot stringify null Node!");
}
String value = null;
short nodeType = node.getNodeType();
if (nodeType == Node.ELEMENT_NODE || nodeType == Node.DOCUMENT_NODE) {
// serializer doesn't handle Node type well, only Element
DOMSerializerImpl ser = new DOMSerializerImpl();
ser.setParameter(Constants.DOM_NAMESPACES, Boolean.TRUE);
ser.setParameter(Constants.DOM_WELLFORMED, Boolean.FALSE );
ser.setParameter(Constants.DOM_VALIDATE, Boolean.FALSE);
// create a proper XML encoding header based on the input document;
// default to UTF-8 if the parent document's encoding is not accessible
String usedEncoding = "UTF-8";
Document parent = node.getOwnerDocument();
if (parent != null) {
String parentEncoding = parent.getXmlEncoding();
if (parentEncoding != null) {
usedEncoding = parentEncoding;
}
}
// the receiver of the DOM
DOMOutputImpl out = new DOMOutputImpl();
out.setEncoding(usedEncoding);
// we write into a String
StringWriter writer = new StringWriter(4096);
out.setCharacterStream(writer);
// out, ye characters!
ser.write(node, out);
writer.flush();
// finally get the String
value = writer.toString();
} else {
value = node.getNodeValue();
}
return value;
}
public static void serialize(Element elmt, OutputStream ostr) {
String usedEncoding = "UTF-8";
Document parent = elmt.getOwnerDocument();
if (parent != null) {
String parentEncoding = parent.getXmlEncoding();
if (parentEncoding != null) {
usedEncoding = parentEncoding;
}
}
DOMOutputImpl out = new DOMOutputImpl();
out.setEncoding(usedEncoding);
DOMSerializerImpl ser = new DOMSerializerImpl();
out.setByteStream(ostr);
ser.write(elmt, out);
}
/**
* Convert a DOM node to a stringified XML representation.
*/
static public String domToStringLevel2(Node node) {
if (node == null) {
throw new IllegalArgumentException("Cannot stringify null Node!");
}
String value = null;
short nodeType = node.getNodeType();
if (nodeType == Node.ELEMENT_NODE || nodeType == Node.DOCUMENT_NODE) {
// serializer doesn't handle Node type well, only Element
DOMSerializerImpl ser = new DOMSerializerImpl();
ser.setParameter(Constants.DOM_NAMESPACES, Boolean.TRUE);
ser.setParameter(Constants.DOM_WELLFORMED, Boolean.FALSE );
ser.setParameter(Constants.DOM_VALIDATE, Boolean.FALSE);
// the receiver of the DOM
DOMOutputImpl out = new DOMOutputImpl();
out.setEncoding("UTF-8");
// we write into a String
StringWriter writer = new StringWriter(4096);
out.setCharacterStream(writer);
// out, ye characters!
ser.write(node, out);
writer.flush();
// finally get the String
value = writer.toString();
} else {
value = node.getNodeValue();
}
return value;
}
/**
* Return the first child element of the given element which has the given
* attribute with the given value.
*
* @param elem the element whose children are to be searched
* @param attrName the attrib that must be present
* @param attrValue the desired value of the attribute
*
* @return the first matching child element.
*/
public static Element findChildElementWithAttribute(Element elem,
String attrName, String attrValue) {
for (Node n = elem.getFirstChild(); n != null; n = n.getNextSibling()) {
if (n.getNodeType() == Node.ELEMENT_NODE) {
if (attrValue.equals(DOMUtils.getAttribute((Element) n, attrName))) { return (Element) n; }
}
}
return null;
}
/**
* Parse a String into a DOM.
*
* @param s DOCUMENTME
*
* @return DOCUMENTME
*
* @throws SAXException DOCUMENTME
* @throws IOException DOCUMENTME
*/
static public Element stringToDOM(String s) throws SAXException, IOException {
return parse(new InputSource(new StringReader(s))).getDocumentElement();
}
/**
* Perform a naive check to see if a document is a WSDL document
* based on the root element name and namespace URI.
* @param d the {@link Document} to check
* @return <code>true</code> if the root element appears correct
*/
public static boolean isWsdlDocument(Document d) {
Element e = d.getDocumentElement();
String uri = e.getNamespaceURI();
String localName = e.getLocalName();
if (uri == null || localName == null) { return false; }
return uri.equals(WSDL_NS) && localName.equals(WSDL_ROOT_ELEMENT);
}
/**
* Perform a naive check to see if a document is an XML schema document
* based on the root element name and namespace URI.
* @param d the {@link Document} to check
* @return <code>true</code> if the root element appears correct
*/
public static boolean isXmlSchemaDocument(Document d) {
Element e = d.getDocumentElement();
String uri = e.getNamespaceURI();
String localName = e.getLocalName();
if (uri == null || localName == null) { return false; }
return uri.equals(XSD_NS) && localName.equals(XSD_ROOT_ELEMENT);
}
public static final String WSDL_NS = "http://schemas.xmlsoap.org/wsdl/";
public static final String WSDL_ROOT_ELEMENT = "definitions";
public static final String XSD_NS = "http://www.w3.org/2001/XMLSchema";
public static final String XSD_ROOT_ELEMENT = "schema";
/**
* @param el
*/
public static void pancakeNamespaces(Element el) {
Map ns = getParentNamespaces(el);
Document d = el.getOwnerDocument();
assert d != null;
Iterator it = ns.keySet().iterator();
while (it.hasNext()) {
String key = (String) it.next();
String uri = (String) ns.get(key);
Attr a = d.createAttributeNS(NS_URI_XMLNS,
(key.length() != 0)?("xmlns:" + key):("xmlns"));
a.setValue(uri);
el.setAttributeNodeNS(a);
}
}
public static Document newDocument() {
DocumentBuilder db = getBuilder();
return db.newDocument();
}
/**
* Parse an XML stream using the pooled document builder.
* @param inputStream input stream
* @return parsed XML document
*/
public static Document parse(InputStream inputStream) throws SAXException, IOException {
return parse(new InputSource(inputStream));
}
/**
* Parse an XML document located using an {@link InputSource} using the
* pooled document builder.
*/
public static Document parse(InputSource inputSource) throws SAXException,IOException{
DocumentBuilder db = getBuilder();
return db.parse(inputSource);
}
/**
* Parse an XML document located using an {@link InputSource} using the
* pooled document builder.
*/
public static Document sourceToDOM(Source inputSource) throws IOException {
try {
/*
// Requires JDK 1.6+
if (inputSource instanceof StAXSource) {
StAXSource stax = (StAXSource) inputSource;
//if (stax.getXMLEventReader() != null || sax.getXMLStreamReader() != null) {
if (sax.getXMLStreamReader() != null) {
return parse(stax.getXMLStreamReader());
}
}
*/
if (inputSource instanceof SAXSource) {
InputSource sax = ((SAXSource) inputSource).getInputSource();
if (sax.getCharacterStream() != null || sax.getByteStream() != null) {
return parse( ((SAXSource) inputSource).getInputSource() );
}
}
if (inputSource instanceof DOMSource) {
Node node = ((DOMSource) inputSource).getNode();
if (node != null) {
return toDOMDocument(node);
}
}
if (inputSource instanceof StreamSource) {
StreamSource stream = (StreamSource) inputSource;
if (stream.getReader() != null || stream.getInputStream() != null) {
return toDocumentFromStream( (StreamSource) inputSource);
}
}
DOMResult domresult = new DOMResult(newDocument());
Transformer txer = getTransformer();
txer.transform(inputSource, domresult);
return (Document) domresult.getNode();
} catch (SAXException e) {
throwIOException(e);
} catch (TransformerException e) {
throwIOException(e);
}
throw new IllegalArgumentException("Cannot parse XML source: " + inputSource.getClass());
}
/**
* Check that an element is empty, i.e., it contains no non-whitespace text or
* elements as children.
* @param el the element
* @return <code>true</code> if the element is empty, <code>false</code> if not.
*/
public static boolean isEmptyElement(Element el) {
NodeList nl = el.getChildNodes();
int len = nl.getLength();
for (int i=0; i < len; ++i) {
switch (nl.item(i).getNodeType()) {
case Node.CDATA_SECTION_NODE:
case Node.TEXT_NODE:
String s = nl.item(i).getNodeValue();
if (s != null && s.trim().length() > 0) {
return false;
}
break;
case Node.ELEMENT_NODE:
return false;
}
}
return true;
}
public static QName getNodeQName(Node el) {
String localName = el.getLocalName();
String namespaceUri = el.getNamespaceURI();
if (localName == null) {
String nodeName = el.getNodeName();
int colonIndex = nodeName.indexOf(":");
if (colonIndex > 0) {
localName = nodeName.substring(0, colonIndex);
namespaceUri = nodeName.substring(colonIndex + 1);
} else {
localName = nodeName;
namespaceUri = null;
}
}
return new QName(namespaceUri, localName);
}
public static QName getNodeQName(String qualifiedName) {
int index = qualifiedName.indexOf(":");
if (index >= 0) {
return new QName(qualifiedName.substring(0, index), qualifiedName.substring(index + 1));
} else {
return new QName(qualifiedName);
}
}
/**
* Remove the child nodes under another node.
* @param target the <code>Node</code> to remove the children from.
*/
public static void removeChildren(Node target) {
while (target.hasChildNodes()) {
target.removeChild(target.getFirstChild());
}
}
/**
* Drop the attributes from an element, except possibly an <code>xmlns</code>
* attribute that declares its namespace.
* @param target the element whose attributes will be removed.
* @param flag preserve namespace declaration
*/
public static void removeAttributes(Element target, boolean flag) {
if (!target.hasAttributes()) {
return;
}
String prefix = target.getPrefix();
NamedNodeMap nnm = target.getAttributes();
Attr toPutBack = null;
if (flag) {
if (prefix== null) {
toPutBack = target.getAttributeNodeNS(NS_URI_XMLNS,"xmlns");
} else {
toPutBack = target.getAttributeNodeNS(NS_URI_XMLNS,"xmlns:" + prefix);
}
}
while(nnm.getLength() != 0) {
target.removeAttributeNode((Attr) nnm.item(0));
}
if (toPutBack != null) {
target.setAttributeNodeNS(toPutBack);
}
}
public static Element findChildByName(Element parent, QName name) {
return findChildByName(parent, name, false);
}
public static Element findChildByName(Element parent, QName name, boolean recurse) {
if (parent == null)
throw new IllegalArgumentException("null parent");
if (name == null)
throw new IllegalArgumentException("null name");
NodeList nl = parent.getChildNodes();
for (int i = 0; i < nl.getLength(); ++i) {
Node c = nl.item(i);
if(c.getNodeType() != Node.ELEMENT_NODE)
continue;
// For a reason that I can't fathom, when using in-mem DAO we actually get elements with
// no localname.
String nodeName = c.getLocalName() != null ? c.getLocalName() : c.getNodeName();
if (new QName(c.getNamespaceURI(),nodeName).equals(name))
return (Element) c;
}
if(recurse){
NodeList cnl = parent.getChildNodes();
for (int i = 0; i < cnl.getLength(); ++i) {
Node c = cnl.item(i);
if(c.getNodeType() != Node.ELEMENT_NODE)
continue;
Element result = findChildByName((Element)c, name, recurse);
if(result != null)
return result;
}
}
return null;
}
public static Node findChildByType(Element elem, int type) {
if (elem == null)
throw new NullPointerException("elem parameter must not be null!");
for (Node n = elem.getFirstChild(); n != null; n = n.getNextSibling()) {
if (n.getNodeType() == type) {
return n;
}
}
return null;
}
public static String getTextContent(Node node) {
for (int m = 0; m < node.getChildNodes().getLength(); m++) {
Node child = node.getChildNodes().item(m);
if (child.getNodeType() == Node.TEXT_NODE) {
String childText = child.getNodeValue().trim();
if (childText.length() > 0) return childText;
}
}
return null;
}
public static Element getElementContent(Node node) {
for (int m = 0; m < node.getChildNodes().getLength(); m++) {
Node child = node.getChildNodes().item(m);
if (child.getNodeType() == Node.ELEMENT_NODE) return (Element) child;
}
return null;
}
public static void injectNamespaces(Element domElement, NSContext nscontext) {
for (String uri : nscontext.getUriSet()) {
String prefix = nscontext.getPrefix(uri);
if (prefix == null || "".equals(prefix))
domElement.setAttributeNS(DOMUtils.NS_URI_XMLNS, "xmlns", uri);
else
domElement.setAttributeNS(DOMUtils.NS_URI_XMLNS, "xmlns:"+ prefix, uri);
}
}
public static void copyNSContext(Element source, Element dest) {
Map<String, String> sourceNS = getParentNamespaces(source);
sourceNS.putAll(getMyNamespaces(source));
Map<String, String> destNS = getParentNamespaces(dest);
destNS.putAll(getMyNamespaces(dest));
// (source - dest) to avoid adding twice the same ns on dest
for (String pr : destNS.keySet()) sourceNS.remove(pr);
for (Map.Entry<String, String> entry : sourceNS.entrySet()) {
String prefix = entry.getKey();
String uri = entry.getValue();
if (prefix == null || "".equals(prefix))
dest.setAttributeNS(DOMUtils.NS_URI_XMLNS, "xmlns", uri);
else
dest.setAttributeNS(DOMUtils.NS_URI_XMLNS, "xmlns:"+ prefix, uri);
}
}
public static Document toDOMDocument(Node node) throws TransformerException {
// If the node is the document, just cast it
if (node instanceof Document) {
return (Document) node;
// If the node is an element
} else if (node instanceof Element) {
Element elem = (Element) node;
// If this is the root element, return its owner document
if (elem.getOwnerDocument().getDocumentElement() == elem) {
return elem.getOwnerDocument();
// else, create a new doc and copy the element inside it
} else {
Document doc = newDocument();
doc.appendChild(doc.importNode(node, true));
return doc;
}
// other element types are not handled
} else {
throw new TransformerException("Unable to convert DOM node to a Document");
}
}
public static Document toDocumentFromStream(StreamSource source) throws IOException, SAXException {
DocumentBuilder builder = getBuilder();
Document document = null;
Reader reader = source.getReader();
if (reader != null) {
document = builder.parse(new InputSource(reader));
} else {
InputStream inputStream = source.getInputStream();
if (inputStream != null) {
InputSource inputsource = new InputSource(inputStream);
inputsource.setSystemId( source.getSystemId() );
document = builder.parse(inputsource);
}
else {
throw new IOException("No input stream or reader available");
}
}
return document;
}
// sadly, as of JDK 5.0 IOException still doesn't support new IOException(Throwable)
private static void throwIOException(Throwable t) throws IOException {
IOException e = new IOException(t.getMessage());
e.setStackTrace(t.getStackTrace());
throw e;
}
public static Document parse(XMLStreamReader reader)
throws XMLStreamException
{
Document doc = newDocument();
parse(reader, doc, doc);
return doc;
}
private static void parse(XMLStreamReader reader, Document doc, Node parent)
throws XMLStreamException
{
int event = reader.getEventType();
while (reader.hasNext()) {
switch (event) {
case XMLStreamConstants.START_ELEMENT:
// create element
Element e = doc.createElementNS(reader.getNamespaceURI(), reader.getLocalName());
if (reader.getPrefix() != null && reader.getPrefix() != "") {
e.setPrefix(reader.getPrefix());
}
parent.appendChild(e);
// copy namespaces
for (int ns = 0; ns < reader.getNamespaceCount(); ns++) {
String uri = reader.getNamespaceURI(ns);
String prefix = reader.getNamespacePrefix(ns);
declare(e, uri, prefix);
}
// copy attributes
for (int att = 0; att < reader.getAttributeCount(); att++) {
String name = reader.getAttributeLocalName(att);
String prefix = reader.getAttributePrefix(att);
if (prefix != null && prefix.length() > 0) {
name = prefix + ":" + name;
}
Attr attr = doc.createAttributeNS(reader.getAttributeNamespace(att), name);
attr.setValue(reader.getAttributeValue(att));
e.setAttributeNode(attr);
}
// sub-nodes
if (reader.hasNext()) {
reader.next();
parse(reader, doc, e);
}
if (parent instanceof Document) {
while (reader.hasNext()) reader.next();
return;
}
break;
case XMLStreamConstants.END_ELEMENT:
return;
case XMLStreamConstants.CHARACTERS:
if (parent != null) {
parent.appendChild(doc.createTextNode(reader.getText()));
}
break;
case XMLStreamConstants.COMMENT:
if (parent != null) {
parent.appendChild(doc.createComment(reader.getText()));
}
break;
case XMLStreamConstants.CDATA:
parent.appendChild(doc.createCDATASection(reader.getText()));
break;
case XMLStreamConstants.PROCESSING_INSTRUCTION:
parent.appendChild(doc.createProcessingInstruction(reader.getPITarget(), reader.getPIData()));
break;
case XMLStreamConstants.ENTITY_REFERENCE:
parent.appendChild(doc.createProcessingInstruction(reader.getPITarget(), reader.getPIData()));
break;
case XMLStreamConstants.NAMESPACE:
case XMLStreamConstants.ATTRIBUTE:
break;
default:
break;
}
if (reader.hasNext()) {
event = reader.next();
}
}
}
private static void declare(Element node, String uri, String prefix) {
if (prefix != null && prefix.length() > 0) {
node.setAttributeNS(NS_URI_XMLNS, "xmlns:" + prefix, uri);
} else {
if (uri != null) {
node.setAttributeNS(NS_URI_XMLNS, "xmlns", uri);
}
}
}
private static Transformer getTransformer() {
Transformer txer = __txers.get();
if (txer == null) {
synchronized(_transformerFactory) {
try {
txer = _transformerFactory.newTransformer();
} catch (TransformerConfigurationException e) {
String errmsg = "Transformer configuration error!";
__log.fatal(errmsg, e);
throw new Error(errmsg, e);
}
}
__txers.set(txer);
}
return txer;
}
private static DocumentBuilder getBuilder() {
DocumentBuilder builder = __builders.get();
if (builder == null) {
synchronized (__documentBuilderFactory) {
try {
builder = __documentBuilderFactory.newDocumentBuilder();
builder.setErrorHandler(new LoggingErrorHandler());
} catch (ParserConfigurationException e) {
__log.error(e);
throw new RuntimeException(e);
}
}
__builders.set(builder);
}
return builder;
}
public static List<Element> findChildrenByName(Element parent, QName name) {
if (parent == null)
throw new IllegalArgumentException("null parent");
if (name == null)
throw new IllegalArgumentException("null name");
LinkedList<Element> ret = new LinkedList<Element>();
NodeList nl = parent.getChildNodes();
for (int i = 0; i < nl.getLength(); ++i) {
Node c = nl.item(i);
if(c.getNodeType() != Node.ELEMENT_NODE)
continue;
// For a reason that I can't fathom, when using in-mem DAO we actually get elements with
// no localname.
String nodeName = c.getLocalName() != null ? c.getLocalName() : c.getNodeName();
if (new QName(c.getNamespaceURI(),nodeName).equals(name))
ret.add((Element)c);
}
return ret;
}
/**
* Somewhat eases the pain of dealing with both Lists and Nodelists by converting either
* passed as parameter to a List.
* @param nl a NodeList or a List
* @return a List
*/
public static List<Node> toList(Object nl) {
if (nl == null) return null;
if (nl instanceof List) return (List<Node>) nl;
NodeList cnl = (NodeList) nl;
List<Node> ll = new ArrayList<Node>();
for (int m = 0; m < cnl.getLength(); m++) ll.add(cnl.item(m));
return ll;
}
public static Document getDocument(Node contextNode) {
return (contextNode == null) ? DOMUtils.newDocument() : contextNode.getOwnerDocument();
}
public static String getQualifiedName(QName qName) {
String prefix = qName.getPrefix(), localPart = qName.getLocalPart();
return (prefix == null || "".equals(prefix)) ? localPart : (prefix + ":" + localPart);
}
/**
* Deep clone, but don't fry, the given node in the context of the given document.
* For all intents and purposes, the clone is the exact same copy of the node,
* except that it might have a different owner document.
*
* This method is fool-proof, unlike the <code>adoptNode</code> or <code>adoptNode</code> methods,
* in that it doesn't assume that the given node has a parent or a owner document.
*
* @param document
* @param sourceNode
* @return a clone of node
*/
public static Node cloneNode(Document document, Node sourceNode) {
Node clonedNode = null;
// what is my name?
QName sourceQName = getNodeQName(sourceNode);
String nodeName = sourceQName.getLocalPart();
String namespaceURI = sourceQName.getNamespaceURI();
// if the node is unqualified, don't assume that it inherits the WS-BPEL target namespace
if (Namespaces.WSBPEL2_0_FINAL_EXEC.equals(namespaceURI)) {
namespaceURI = null;
}
switch (sourceNode.getNodeType()) {
case Node.ATTRIBUTE_NODE:
if (namespaceURI == null) {
clonedNode = document.createAttribute(nodeName);
} else {
String prefix = ((Attr) sourceNode).lookupPrefix(namespaceURI);
// the prefix for the XML namespace can't be looked up, hence this...
if (prefix == null && namespaceURI.equals(NS_URI_XMLNS)) {
prefix = "xmlns";
}
// if a prefix exists, qualify the name with it
if (prefix != null && !"".equals(prefix)) {
nodeName = prefix + ":" + nodeName;
}
// create the appropriate type of attribute
if (prefix != null) {
clonedNode = document.createAttributeNS(namespaceURI, nodeName);
} else {
clonedNode = document.createAttribute(nodeName);
}
}
break;
case Node.CDATA_SECTION_NODE:
clonedNode = document.createCDATASection(((CDATASection) sourceNode).getData());
break;
case Node.COMMENT_NODE:
clonedNode = document.createComment(((Comment) sourceNode).getData());
break;
case Node.DOCUMENT_FRAGMENT_NODE:
clonedNode = document.createDocumentFragment();
break;
case Node.DOCUMENT_NODE:
clonedNode = document;
break;
case Node.ELEMENT_NODE:
// create the appropriate type of element
if (namespaceURI == null) {
clonedNode = document.createElement(nodeName);
} else {
String prefix = namespaceURI.equals(Namespaces.XMLNS_URI) ?
"xmlns" : ((Element) sourceNode).lookupPrefix(namespaceURI);
if (prefix != null && !"".equals(prefix)) {
nodeName = prefix + ":" + nodeName;
clonedNode = document.createElementNS(namespaceURI, nodeName);
} else {
clonedNode = document.createElement(nodeName);
}
}
// attributes are not treated as child nodes, so copy them explicitly
NamedNodeMap attributes = ((Element) sourceNode).getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
Attr attributeClone = (Attr) cloneNode(document, attributes.item(i));
if (attributeClone.getNamespaceURI() == null) {
((Element) clonedNode).setAttributeNode(attributeClone);
} else {
((Element) clonedNode).setAttributeNodeNS(attributeClone);
}
}
break;
case Node.ENTITY_NODE:
// TODO
break;
case Node.ENTITY_REFERENCE_NODE:
clonedNode = document.createEntityReference(nodeName);
// TODO
break;
case Node.NOTATION_NODE:
// TODO
break;
case Node.PROCESSING_INSTRUCTION_NODE:
clonedNode = document.createProcessingInstruction(((ProcessingInstruction) sourceNode).getData(), nodeName);
break;
case Node.TEXT_NODE:
clonedNode = document.createTextNode(((Text) sourceNode ).getData());
break;
default:
break;
}
// clone children of element and attribute nodes
NodeList sourceChildren = sourceNode.getChildNodes();
if (sourceChildren != null) {
for (int i = 0; i < sourceChildren.getLength(); i++) {
Node sourceChild = sourceChildren.item(i);
Node clonedChild = cloneNode(document, sourceChild);
clonedNode.appendChild(clonedChild);
// if the child has a textual value, parse it for any embedded prefixes
if (clonedChild.getNodeType() == Node.TEXT_NODE ||
clonedChild.getNodeType() == Node.CDATA_SECTION_NODE) {
parseEmbeddedPrefixes(sourceNode, clonedNode, clonedChild);
}
}
}
return clonedNode;
}
/**
* Parse the text in the cloneChild for any embedded prefixes, and define it in it's parent element
*
* @param sourceNode
* @param clonedNode
* @param clonedChild
*/
private static void parseEmbeddedPrefixes(Node sourceNode, Node clonedNode, Node clonedChild) {
Element clonedElement = null;
if (clonedNode instanceof Attr) {
clonedElement = ((Attr) clonedNode).getOwnerElement();
} else if (clonedNode instanceof Element) {
clonedElement = (Element) clonedNode;
}
if (clonedElement == null) {
// couldn't find an element to set prefixes on, so bail out
return;
}
String text = ((Text) clonedChild).getNodeValue();
if (text != null && text.indexOf(":") > 0) {
Name11Checker nameChecker = Name11Checker.getInstance();
for (int colonIndex = text.indexOf(":"); colonIndex != -1 && colonIndex < text.length(); colonIndex = text.indexOf(":", colonIndex + 1)) {
StringBuffer prefixString = new StringBuffer();
for (int prefixIndex = colonIndex - 1;
prefixIndex >= 0 && nameChecker.isNCNameChar(text.charAt(prefixIndex));
prefixIndex--) {
prefixString.append(text.charAt(prefixIndex));
}
prefixString.reverse();
if (prefixString.length() > 0) {
String uri = sourceNode.lookupNamespaceURI(prefixString.toString());
if (uri != null) {
clonedElement.setAttributeNS(NS_URI_XMLNS, "xmlns:" + prefixString, uri);
}
}
}
}
}
}
| |
/*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2018 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.core;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.repository.RepositoryDirectory;
import org.pentaho.di.core.util.Utils;
import java.util.Date;
public class LastUsedFile {
private static Class<?> PKG = LastUsedFile.class;
public static final String FILE_TYPE_TRANSFORMATION = "Trans";
public static final String FILE_TYPE_JOB = "Job";
public static final String FILE_TYPE_SCHEMA = "Schema";
public static final String FILE_TYPE_CUSTOM = "Custom";
public static final int OPENED_ITEM_TYPE_MASK_NONE = 0;
public static final int OPENED_ITEM_TYPE_MASK_GRAPH = 1;
public static final int OPENED_ITEM_TYPE_MASK_LOG = 2;
public static final int OPENED_ITEM_TYPE_MASK_HISTORY = 4;
private String fileType;
private String filename;
private String directory;
private boolean sourceRepository;
private String repositoryName;
private Date lastOpened;
private String username;
private boolean opened;
private int openItemTypes;
/**
* @param fileType
* The type of file to use (FILE_TYPE_TRANSFORMATION, FILE_TYPE_JOB, ...)
* @param filename
* @param directory
* @param sourceRepository
* @param repositoryName
* @param opened
* @param openItemTypes
*/
public LastUsedFile( String fileType, String filename, String directory, boolean sourceRepository,
String repositoryName, boolean opened, int openItemTypes ) {
this( fileType, filename, directory, sourceRepository, repositoryName, null, opened, openItemTypes, null );
}
/**
* @param fileType
* The type of file to use (FILE_TYPE_TRANSFORMATION, FILE_TYPE_JOB, ...)
* @param filename
* @param directory
* @param sourceRepository
* @param repositoryName
* @param username
* @param opened
* @param openItemTypes
*/
public LastUsedFile( String fileType, String filename, String directory, boolean sourceRepository,
String repositoryName, String username, boolean opened, int openItemTypes, Date lastOpened ) {
this.fileType = fileType;
this.filename = filename;
this.directory = directory;
this.sourceRepository = sourceRepository;
this.repositoryName = repositoryName;
this.username = username;
this.opened = opened;
this.openItemTypes = openItemTypes;
this.lastOpened = lastOpened == null ? new Date() : lastOpened;
}
public String toString() {
String string = "";
if ( sourceRepository && !Utils.isEmpty( directory ) && !Utils.isEmpty( repositoryName ) ) {
string += "[" + repositoryName + "] ";
if ( directory.endsWith( RepositoryDirectory.DIRECTORY_SEPARATOR ) ) {
string += ": " + directory + filename;
} else {
string += ": " + directory + RepositoryDirectory.DIRECTORY_SEPARATOR + filename;
}
} else {
string += filename;
}
return string;
}
public int hashCode() {
return ( getFileType() + toString() ).hashCode();
}
public boolean equals( Object obj ) {
LastUsedFile file = (LastUsedFile) obj;
return getFileType().equals( file.getFileType() ) && toString().equals( file.toString() );
}
/**
* @return the directory
*/
public String getDirectory() {
return directory;
}
/**
* @param directory
* the directory to set
*/
public void setDirectory( String directory ) {
this.directory = directory;
}
/**
* @return the filename
*/
public String getFilename() {
return filename;
}
/**
* @param filename
* the filename to set
*/
public void setFilename( String filename ) {
this.filename = filename;
}
/**
* @return the repositoryName
*/
public String getRepositoryName() {
return repositoryName;
}
/**
* @param repositoryName
* the repositoryName to set
*/
public void setRepositoryName( String repositoryName ) {
this.repositoryName = repositoryName;
}
/**
* @return the sourceRepository
*/
public boolean isSourceRepository() {
return sourceRepository;
}
/**
* @param sourceRepository
* the sourceRepository to set
*/
public void setSourceRepository( boolean sourceRepository ) {
this.sourceRepository = sourceRepository;
}
/**
* @return the fileType
*/
public String getFileType() {
return fileType;
}
public String getLongFileType() {
String fileType = BaseMessages.getString( PKG, "System.FileType.File" );
if ( FILE_TYPE_TRANSFORMATION.equals( getFileType() ) ) {
fileType = BaseMessages.getString( PKG, "System.FileType.Transformation" );
} else if ( FILE_TYPE_JOB.equals( getFileType() ) ) {
fileType = BaseMessages.getString( PKG, "System.FileType.Job" );
} else if ( FILE_TYPE_SCHEMA.equals( getFileType() ) ) {
fileType = FILE_TYPE_SCHEMA;
}
return fileType;
}
/**
* @param fileType
* the fileType to set
*/
public void setFileType( String fileType ) {
this.fileType = fileType;
}
public boolean isTransformation() {
return FILE_TYPE_TRANSFORMATION.equalsIgnoreCase( fileType );
}
public boolean isJob() {
return FILE_TYPE_JOB.equalsIgnoreCase( fileType );
}
public boolean isSchema() {
return FILE_TYPE_SCHEMA.equalsIgnoreCase( fileType );
}
/**
* @return the opened
*/
public boolean isOpened() {
return opened;
}
/**
* @param opened
* the opened to set
*/
public void setOpened( boolean opened ) {
this.opened = opened;
}
/**
* @return the openItemTypes
*/
public int getOpenItemTypes() {
return openItemTypes;
}
/**
* @param openItemTypes
* the openItemTypes to set
*/
public void setOpenItemTypes( int openItemTypes ) {
this.openItemTypes = openItemTypes;
}
public Date getLastOpened() {
return lastOpened;
}
public void setLastOpened( Date lastOpened ) {
this.lastOpened = lastOpened;
}
public String getUsername() {
return username;
}
public void setUsername( String username ) {
this.username = username;
}
}
| |
package org.apache.lucene.index;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import static org.apache.lucene.util.ByteBlockPool.BYTE_BLOCK_SIZE;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.apache.lucene.codecs.DocValuesConsumer;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.ByteBlockPool;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BytesRefHash.DirectBytesStartArray;
import org.apache.lucene.util.BytesRefHash;
import org.apache.lucene.util.Counter;
import org.apache.lucene.util.RamUsageEstimator;
import org.apache.lucene.util.packed.AppendingDeltaPackedLongBuffer;
import org.apache.lucene.util.packed.AppendingPackedLongBuffer;
import org.apache.lucene.util.packed.PackedInts;
/** Buffers up pending byte[]s per doc, deref and sorting via
* int ord, then flushes when segment flushes. */
class SortedSetDocValuesWriter extends DocValuesWriter {
final BytesRefHash hash;
private AppendingPackedLongBuffer pending; // stream of all termIDs
private AppendingDeltaPackedLongBuffer pendingCounts; // termIDs per doc
private final Counter iwBytesUsed;
private long bytesUsed; // this only tracks differences in 'pending' and 'pendingCounts'
private final FieldInfo fieldInfo;
private int currentDoc;
private int currentValues[] = new int[8];
private int currentUpto = 0;
private int maxCount = 0;
public SortedSetDocValuesWriter(FieldInfo fieldInfo, Counter iwBytesUsed) {
this.fieldInfo = fieldInfo;
this.iwBytesUsed = iwBytesUsed;
hash = new BytesRefHash(
new ByteBlockPool(
new ByteBlockPool.DirectTrackingAllocator(iwBytesUsed)),
BytesRefHash.DEFAULT_CAPACITY,
new DirectBytesStartArray(BytesRefHash.DEFAULT_CAPACITY, iwBytesUsed));
pending = new AppendingPackedLongBuffer(PackedInts.COMPACT);
pendingCounts = new AppendingDeltaPackedLongBuffer(PackedInts.COMPACT);
bytesUsed = pending.ramBytesUsed() + pendingCounts.ramBytesUsed();
iwBytesUsed.addAndGet(bytesUsed);
}
public void addValue(int docID, BytesRef value) {
if (value == null) {
throw new IllegalArgumentException("field \"" + fieldInfo.name + "\": null value not allowed");
}
if (value.length > (BYTE_BLOCK_SIZE - 2)) {
throw new IllegalArgumentException("DocValuesField \"" + fieldInfo.name + "\" is too large, must be <= " + (BYTE_BLOCK_SIZE - 2));
}
if (docID != currentDoc) {
finishCurrentDoc();
}
// Fill in any holes:
while(currentDoc < docID) {
pendingCounts.add(0); // no values
currentDoc++;
}
addOneValue(value);
updateBytesUsed();
}
// finalize currentDoc: this deduplicates the current term ids
private void finishCurrentDoc() {
Arrays.sort(currentValues, 0, currentUpto);
int lastValue = -1;
int count = 0;
for (int i = 0; i < currentUpto; i++) {
int termID = currentValues[i];
// if its not a duplicate
if (termID != lastValue) {
pending.add(termID); // record the term id
count++;
}
lastValue = termID;
}
// record the number of unique term ids for this doc
pendingCounts.add(count);
maxCount = Math.max(maxCount, count);
currentUpto = 0;
currentDoc++;
}
@Override
public void finish(int maxDoc) {
finishCurrentDoc();
// fill in any holes
for (int i = currentDoc; i < maxDoc; i++) {
pendingCounts.add(0); // no values
}
}
private void addOneValue(BytesRef value) {
int termID = hash.add(value);
if (termID < 0) {
termID = -termID-1;
} else {
// reserve additional space for each unique value:
// 1. when indexing, when hash is 50% full, rehash() suddenly needs 2*size ints.
// TODO: can this same OOM happen in THPF?
// 2. when flushing, we need 1 int per value (slot in the ordMap).
iwBytesUsed.addAndGet(2 * RamUsageEstimator.NUM_BYTES_INT);
}
if (currentUpto == currentValues.length) {
currentValues = ArrayUtil.grow(currentValues, currentValues.length+1);
// reserve additional space for max # values per-doc
// when flushing, we need an int[] to sort the mapped-ords within the doc
iwBytesUsed.addAndGet((currentValues.length - currentUpto) * 2 * RamUsageEstimator.NUM_BYTES_INT);
}
currentValues[currentUpto] = termID;
currentUpto++;
}
private void updateBytesUsed() {
final long newBytesUsed = pending.ramBytesUsed() + pendingCounts.ramBytesUsed();
iwBytesUsed.addAndGet(newBytesUsed - bytesUsed);
bytesUsed = newBytesUsed;
}
@Override
public void flush(SegmentWriteState state, DocValuesConsumer dvConsumer) throws IOException {
final int maxDoc = state.segmentInfo.getDocCount();
final int maxCountPerDoc = maxCount;
assert pendingCounts.size() == maxDoc;
final int valueCount = hash.size();
final int[] sortedValues = hash.sort(BytesRef.getUTF8SortedAsUnicodeComparator());
final int[] ordMap = new int[valueCount];
for(int ord=0;ord<valueCount;ord++) {
ordMap[sortedValues[ord]] = ord;
}
dvConsumer.addSortedSetField(fieldInfo,
// ord -> value
new Iterable<BytesRef>() {
@Override
public Iterator<BytesRef> iterator() {
return new ValuesIterator(sortedValues, valueCount);
}
},
// doc -> ordCount
new Iterable<Number>() {
@Override
public Iterator<Number> iterator() {
return new OrdCountIterator(maxDoc);
}
},
// ords
new Iterable<Number>() {
@Override
public Iterator<Number> iterator() {
return new OrdsIterator(ordMap, maxCountPerDoc);
}
});
}
// iterates over the unique values we have in ram
private class ValuesIterator implements Iterator<BytesRef> {
final int sortedValues[];
final BytesRef scratch = new BytesRef();
final int valueCount;
int ordUpto;
ValuesIterator(int sortedValues[], int valueCount) {
this.sortedValues = sortedValues;
this.valueCount = valueCount;
}
@Override
public boolean hasNext() {
return ordUpto < valueCount;
}
@Override
public BytesRef next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
hash.get(sortedValues[ordUpto], scratch);
ordUpto++;
return scratch;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
// iterates over the ords for each doc we have in ram
private class OrdsIterator implements Iterator<Number> {
final AppendingPackedLongBuffer.Iterator iter = pending.iterator();
final AppendingDeltaPackedLongBuffer.Iterator counts = pendingCounts.iterator();
final int ordMap[];
final long numOrds;
long ordUpto;
final int currentDoc[];
int currentUpto;
int currentLength;
OrdsIterator(int ordMap[], int maxCount) {
this.currentDoc = new int[maxCount];
this.ordMap = ordMap;
this.numOrds = pending.size();
}
@Override
public boolean hasNext() {
return ordUpto < numOrds;
}
@Override
public Number next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
while (currentUpto == currentLength) {
// refill next doc, and sort remapped ords within the doc.
currentUpto = 0;
currentLength = (int) counts.next();
for (int i = 0; i < currentLength; i++) {
currentDoc[i] = ordMap[(int) iter.next()];
}
Arrays.sort(currentDoc, 0, currentLength);
}
int ord = currentDoc[currentUpto];
currentUpto++;
ordUpto++;
// TODO: make reusable Number
return ord;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
private class OrdCountIterator implements Iterator<Number> {
final AppendingDeltaPackedLongBuffer.Iterator iter = pendingCounts.iterator();
final int maxDoc;
int docUpto;
OrdCountIterator(int maxDoc) {
this.maxDoc = maxDoc;
assert pendingCounts.size() == maxDoc;
}
@Override
public boolean hasNext() {
return docUpto < maxDoc;
}
@Override
public Number next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
docUpto++;
// TODO: make reusable Number
return iter.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
}
| |
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.eclipse.ceylon.langtools.tools.javac.api;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.Locale;
import java.util.Set;
import org.eclipse.ceylon.javax.lang.model.SourceVersion;
import org.eclipse.ceylon.javax.tools.*;
import org.eclipse.ceylon.langtools.source.util.JavacTask;
import org.eclipse.ceylon.langtools.tools.javac.file.JavacFileManager;
import org.eclipse.ceylon.langtools.tools.javac.main.Main;
import org.eclipse.ceylon.langtools.tools.javac.main.Option;
import org.eclipse.ceylon.langtools.tools.javac.main.OptionHelper;
import org.eclipse.ceylon.langtools.tools.javac.main.OptionHelper.GrumpyHelper;
import org.eclipse.ceylon.langtools.tools.javac.util.ClientCodeException;
import org.eclipse.ceylon.langtools.tools.javac.util.Context;
import org.eclipse.ceylon.langtools.tools.javac.util.Log;
import org.eclipse.ceylon.langtools.tools.javac.util.Options;
import org.eclipse.ceylon.langtools.tools.javac.util.Log.PrefixKind;
/**
* TODO: describe org.eclipse.ceylon.langtools.tools.javac.api.Tool
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own
* risk. This code and its internal interfaces are subject to change
* or deletion without notice.</b></p>
*
* @author Peter von der Ah\u00e9
*/
public class JavacTool implements JavaCompiler {
/**
* Constructor used by service provider mechanism. The recommended way to
* obtain an instance of this class is by using {@link #create} or the
* service provider mechanism.
* @see org.eclipse.ceylon.javax.tools.JavaCompiler
* @see org.eclipse.ceylon.javax.tools.ToolProvider
* @see #create
*/
@Deprecated
public JavacTool() {}
/**
* Static factory method for creating new instances of this tool.
* @return new instance of this tool
*/
public static JavacTool create() {
return new JavacTool();
}
public JavacFileManager getStandardFileManager(
DiagnosticListener<? super JavaFileObject> diagnosticListener,
Locale locale,
Charset charset) {
Context context = new Context();
context.put(Locale.class, locale);
if (diagnosticListener != null)
context.put(DiagnosticListener.class, diagnosticListener);
PrintWriter pw = (charset == null)
? new PrintWriter(System.err, true)
: new PrintWriter(new OutputStreamWriter(System.err, charset), true);
context.put(Log.outKey, pw);
return new JavacFileManager(context, true, charset);
}
@Override
public JavacTask getTask(Writer out,
JavaFileManager fileManager,
DiagnosticListener<? super JavaFileObject> diagnosticListener,
Iterable<String> options,
Iterable<String> classes,
Iterable<? extends JavaFileObject> compilationUnits) {
Context context = new Context();
return getTask(out, fileManager, diagnosticListener,
options, classes, compilationUnits,
context);
}
public JavacTask getTask(Writer out,
JavaFileManager fileManager,
DiagnosticListener<? super JavaFileObject> diagnosticListener,
Iterable<String> options,
Iterable<String> classes,
Iterable<? extends JavaFileObject> compilationUnits,
Context context)
{
try {
ClientCodeWrapper ccw = ClientCodeWrapper.instance(context);
if (options != null)
for (String option : options)
option.getClass(); // null check
if (classes != null) {
for (String cls : classes)
if (!SourceVersion.isName(cls)) // implicit null check
throw new IllegalArgumentException("Not a valid class name: " + cls);
}
if (compilationUnits != null) {
compilationUnits = ccw.wrapJavaFileObjects(compilationUnits); // implicit null check
for (JavaFileObject cu : compilationUnits) {
if (cu.getKind() != JavaFileObject.Kind.SOURCE) {
String kindMsg = "Compilation unit is not of SOURCE kind: "
+ "\"" + cu.getName() + "\"";
throw new IllegalArgumentException(kindMsg);
}
}
}
if (diagnosticListener != null)
context.put(DiagnosticListener.class, ccw.wrap(diagnosticListener));
if (out == null)
context.put(Log.outKey, new PrintWriter(System.err, true));
else
context.put(Log.outKey, new PrintWriter(out, true));
if (fileManager == null)
fileManager = getStandardFileManager(diagnosticListener, null, null);
fileManager = ccw.wrap(fileManager);
context.put(JavaFileManager.class, fileManager);
processOptions(context, fileManager, options);
Main compiler = new Main("javacTask", context.get(Log.outKey));
return new JavacTaskImpl(compiler, options, context, classes, compilationUnits);
} catch (ClientCodeException ex) {
throw new RuntimeException(ex.getCause());
}
}
public static void processOptions(Context context,
JavaFileManager fileManager,
Iterable<String> options)
{
if (options == null)
return;
final Options optionTable = Options.instance(context);
Log log = Log.instance(context);
Option[] recognizedOptions =
Option.getJavacToolOptions().toArray(new Option[0]);
OptionHelper optionHelper = new GrumpyHelper(log) {
@Override
public String get(Option option) {
return optionTable.get(option.getText());
}
@Override
public java.util.List<String> getMulti(Option option) {
return optionTable.getMulti(option);
}
@Override
public void put(String name, String value) {
optionTable.put(name, value);
}
@Override
public void addMulti(String name, String value) {
optionTable.addMulti(name, value);
}
@Override
public void remove(String name) {
optionTable.remove(name);
}
};
Iterator<String> flags = options.iterator();
while (flags.hasNext()) {
String flag = flags.next();
int j;
for (j=0; j<recognizedOptions.length; j++) {
Option ro = recognizedOptions[j];
if (ro.matches(flag))
break;
}
if (j == recognizedOptions.length) {
if (fileManager.handleOption(flag, flags)) {
continue;
} else {
String msg = log.localize(PrefixKind.JAVAC, "err.invalid.flag", flag);
throw new IllegalArgumentException(msg);
}
}
Option option = recognizedOptions[j];
if (option.hasArg()) {
if (!flags.hasNext()) {
String msg = log.localize(PrefixKind.JAVAC, "err.req.arg", flag);
throw new IllegalArgumentException(msg);
}
String operand = flags.next();
if (option.process(optionHelper, flag, operand))
// should not happen as the GrumpyHelper will throw exceptions
// in case of errors
throw new IllegalArgumentException(flag + " " + operand);
} else {
if (option.process(optionHelper, flag))
// should not happen as the GrumpyHelper will throw exceptions
// in case of errors
throw new IllegalArgumentException(flag);
}
}
optionTable.notifyListeners();
}
public int run(InputStream in, OutputStream out, OutputStream err, String... arguments) {
if (err == null)
err = System.err;
for (String argument : arguments)
argument.getClass(); // null check
return org.eclipse.ceylon.langtools.tools.javac.Main.compile(arguments, new PrintWriter(err, true));
}
public Set<SourceVersion> getSourceVersions() {
return Collections.unmodifiableSet(EnumSet.range(SourceVersion.RELEASE_3,
SourceVersion.latest()));
}
public int isSupportedOption(String option) {
Set<Option> recognizedOptions = Option.getJavacToolOptions();
for (Option o : recognizedOptions) {
if (o.matches(option))
return o.hasArg() ? 1 : 0;
}
return -1;
}
}
| |
/*
* Copyright (C) 2015 University of Oregon
*
* You may distribute under the terms of either the GNU General Public
* License or the Apache License, as specified in the LICENSE file.
*
* For more information, see the LICENSE file.
*/
package vnmr.ui.shuf;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import javax.swing.*;
import vnmr.bo.*;
import vnmr.ui.*;
import vnmr.util.*;
/**
* Tag button
*
*/
public class TagButton extends PopButton implements Serializable {
// ==== instance variables
/** Contains the two previous tags for each objType. The keys are
the objType followed by "1" and "2" for the two values for each. */
Hashtable previousTags;
static final String NEW = "New";
static final String EDIT = "Edit";
static boolean persistenceFilesRead=false;
ModalEntryDialog med=null;
TagAddRemoveDialog dialog=null;
TagEditDialog dial=null;
/** The dialog type for the current TagEditDialog. */
String DialogObjType=null;
/**
* constructor
*/
public TagButton() {
setIcon(Util.getImageIcon("tag.gif"));
setContentAreaFilled(false);
setUnderline(false);
setToolTipText(Util.getLabel("_Locator_Add_Remove"));
/* Get persistance from file */
readPersistence();
// Set Listener for when user clicks the tags icon.
// This will bring up the popup menu.
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
refreshMenu();
}
});
// Set Listener to internal Class for when the user selects
// an item from the menu.
addPopListener(new TagButtonListener());
}
/************************************************** <pre>
* Summary: Clear out and refill the popup menu.
*
</pre> **************************************************/
private void refreshMenu() {
JMenuItem mitem;
ArrayList tagList;
ArrayList selectionList;
String objType;
String tag;
ResultTable resultTable;
int match;
ImageIcon checkBlackIcon = Util.getImageIcon("checkblack.gif");
ImageIcon checkGrayIcon = Util.getImageIcon("checkgray.gif");
ImageIcon checkBlankIcon = Util.getImageIcon("checkblank.gif");
// Need objType
SessionShare sshare = ResultTable.getSshare();
StatementHistory history = sshare.statementHistory();
Hashtable statement = history.getCurrentStatement();
objType = (String)statement.get("ObjectType");
Color bgColor = Util.getBgColor();
// first, delete what's already there
popup.removeAll();
// Make a title of sorts
JMenuItem objMItem = new JMenuItem("Locator Groups");
objMItem.setBackground(bgColor);
popup.add(objMItem);
// Add a separator
popup.addSeparator();
// Get the list of currently selected locator items.
resultTable = Shuffler.getresultTable();
selectionList = resultTable.getSelectionList();
// Get Full List of Tags
tagList = TagList.getAllTagNames(objType);
// Put last two tags accessed at top of list
for(int i=1; i <= 2; i++) {
tag = (String) previousTags.get(objType + Integer.toString(i));
if(tag != null) {
match = matchStatus(tag, selectionList, objType);
mitem = new JMenuItem(tag, checkBlankIcon);
if(match == 1) {
// Matched all
mitem = new JMenuItem((String)tag, checkBlackIcon);
}
else if (match == 0) {
// Matched none
mitem = new JMenuItem((String)tag, checkBlankIcon);
}
else
// Matched some
mitem = new JMenuItem((String)tag, checkGrayIcon);
mitem.setActionCommand(objType + "/" + tag);
mitem.addActionListener(popActionListener);
mitem.setBackground(bgColor);
popup.add(mitem);
}
}
// Add a separator
popup.addSeparator();
// Go thru each tag and get the list of locator entries with that tag.
// Create the menu list
for(int i=0; i < tagList.size(); i++) {
tag = (String)tagList.get(i);
if(tag.length() == 0)
continue;
match = matchStatus(tag, selectionList, objType);
if(match == 1)
// Matched all
mitem = new JMenuItem(tag, checkBlackIcon);
else if (match == 0)
// Matched none
mitem = new JMenuItem(tag, checkBlankIcon);
else
// Matched some
mitem = new JMenuItem(tag, checkGrayIcon);
mitem.setActionCommand(objType+ "/" + tag);
mitem.addActionListener(popActionListener);
mitem.setBackground(bgColor);
popup.add(mitem);
}
// Add a separator
popup.addSeparator();
// Add New
mitem = new JMenuItem(NEW);
mitem.setActionCommand(objType+ "/" + NEW);
mitem.addActionListener(popActionListener);
mitem.setBackground(bgColor);
popup.add(mitem);
// Add Edit
mitem = new JMenuItem(EDIT);
mitem.setActionCommand(objType+ "/" + EDIT);
mitem.addActionListener(popActionListener);
mitem.setBackground(bgColor);
popup.add(mitem);
}
/************************************************** <pre>
* Summary: Return status of matched between items in a tag and selected
* items.
*
* Return: 0 for no matches
* 1 for all selected items have this tag.
* -1 for some matches
</pre> **************************************************/
private int matchStatus(String tag, ArrayList selectionList,
String objType) {
ArrayList itemsWithThisTag;
int numMatched=0;
if(selectionList.size() == 0)
return 0;
ShufDBManager dbMg = ShufDBManager.getdbManager();
itemsWithThisTag = dbMg.getAllEntriesWithThisTag(objType, tag);
// Check itemsWithThisTag against the selectionList of currently
// highlighted items.
numMatched = 0;
for(int k=0; itemsWithThisTag != null && k < selectionList.size(); k++){
if(itemsWithThisTag.contains(selectionList.get(k))) {
numMatched++;
}
}
// Matched none
if(numMatched == 0)
return 0;
// Matched all
else if(numMatched == selectionList.size())
return 1;
// Matched some
else
return -1;
}
/************************************************** <pre>
* Summary: Write out the persistence file.
*
</pre> **************************************************/
public void writePersistence() {
String filepath;
ObjectOutput out;
//String dir, perDir;
//File file;
//dir = System.getProperty("userdir");
//perDir = new String(dir + "/persistence");
//file = new File(perDir);
// If this directory does not exist, make it.
//if(!file.exists()) {
// file.mkdir();
//}
//filepath = new String (perDir + "/GroupMenu");
filepath = FileUtil.savePath("USER/PERSISTENCE/GroupMenu");
try {
out = new ObjectOutputStream(new FileOutputStream(filepath));
// Write it out.
out.writeObject(previousTags);
out.close();
}
catch (Exception ioe) {
Messages.postError("Problem writing filepath");
Messages.writeStackTrace(ioe, "Error caught in writePersistence");
}
}
/************************************************** <pre>
* Summary: Read in the persistence file.
*
</pre> **************************************************/
public void readPersistence() {
String filepath;
ObjectInputStream in;
//String dir;
//dir = System.getProperty("userdir");
//filepath = new String (dir + "/persistence/GroupMenu");
filepath = FileUtil.savePath("USER/PERSISTENCE/GroupMenu");
try {
in = new ObjectInputStream(new FileInputStream(filepath));
// Read it in.
previousTags = (Hashtable) in.readObject();
in.close();
}
catch (ClassNotFoundException ce) {
Messages.postError("Problem reading filepath");
Messages.writeStackTrace(ce, "Error caught in readPersistence");
}
catch (Exception e) {
// No error output here.
}
if(previousTags == null)
previousTags = new Hashtable();
}
/************************************************** <pre>
* Summary: Set this tag in the previous tag list if not duplicate.
*
</pre> **************************************************/
public void setPrevious(String objType, String tag) {
if(tag == null || tag.length() == 0) {
return;
}
// Check for duplicate. Get the 2 previous tags
String tag1 = (String) previousTags.get(objType + "1");
String tag2 = (String) previousTags.get(objType + "2");
if((tag1 == null || !tag.equals(tag1)) &&
(tag2 == null || !tag.equals(tag2))) {
// Set 1 to the current tag
Object lastTag = previousTags.put(objType + "1", tag);
// Set 2 to the previous value of 1
if(lastTag != null)
previousTags.put(objType + "2", lastTag);
}
}
/********************************************************** <pre>
* Summary: Inner Class Listener for selection of item from Tag menu
*
* Called when a selection is made from the Tag menu
</pre> **********************************************************/
public class TagButtonListener implements PopListener {
public void popHappened(String popStr) {
ShufDBManager dbManager = ShufDBManager.getdbManager();
String result;
boolean status=true;
// put down the menu popup
TagButton.this.popup.setVisible(false);
// The locator's JTable is not updated correctly when the
// popup is unshown. This seems to get around that java bug.
// by forcing it to be updated.
ResultTable resultTable = Shuffler.getresultTable();
resultTable.repaint();
refreshMenu();
// Update previousTags if not New nor Edit
if(!popStr.endsWith("/" + NEW) &&
!popStr.endsWith("/" + EDIT)) {
// Get the tag name following "/"
int index = popStr.indexOf("/");
String tag = popStr.substring(index +1);
// Get the objType
String objType = popStr.substring(0, index);
setPrevious(objType, tag);
// Get the list of currently selected locator items.
ArrayList selectionList = resultTable.getSelectionList();
int match = matchStatus(tag, selectionList, objType);
if(match == 1) {
// Matched all, remove this group
// Ask if they really want to remove this tag.
if(dialog == null)
dialog = new TagAddRemoveDialog();
// We don't need the Add button
dialog.disableAdd();
dialog.enableRemove();
result = dialog.showDialog(TagButton.this);
if(result != null && result.equals("remove")) {
// Remove these items from the tag group
// Or really, remove this tag from all items.
dbManager.deleteThisTag(objType, tag);
}
dialog.setVisible(false);
}
else if (match == 0) {
// Matched none, Add this group
// Ask if they really want to add these files.
if(dialog == null)
dialog = new TagAddRemoveDialog();
// We don't need the Remove button
dialog.disableRemove();
dialog.enableAdd();
result = dialog.showDialog(TagButton.this);
if(result != null && result.equals("add")) {
// Add these items to the tag group
// Or really, add this tag to each item.
status = dbManager.setTagInAllSelections(objType, tag);
if(status == true)
// Add this tag to the allTagNames list
TagList.addToAllTagNames(objType, tag);
}
dialog.setVisible(false);
}
else {
// Matched some, Ask what to do next.
if(dialog == null)
dialog = new TagAddRemoveDialog();
dialog.enableAdd();
dialog.enableRemove();
result = dialog.showDialog(TagButton.this);
if(result != null && result.equals("add")) {
status = dbManager.setTagInAllSelections(objType, tag);
if(status == true)
// Add this tag to the allTagNames list
TagList.addToAllTagNames(objType, tag);
}
else if(result != null && result.equals("remove")) {
dbManager.deleteTagFromAllSelections(objType, tag);
}
dialog.setVisible(false);
}
}
else {
// Get the objType
int index = popStr.indexOf("/");
String objType = popStr.substring(0, index);
if(popStr.endsWith("/" + NEW)) {
String tagName;
// Create one ModalEntryDialog and reuse it.
if(med == null)
med = new ModalEntryDialog(
Util.getLabel("_Locator_New_Group"),
Util.getLabel("_Locator_New_Group_Name_Entry"));
tagName = med.showDialogAndGetValue(TagButton.this);
if(tagName != null && tagName.length() != 0) {
status = dbManager.setTagInAllSelections(objType,
tagName);
if(status == true) {
// Add this tag to the allTagNames list
TagList.addToAllTagNames(objType, tagName);
setPrevious(objType, tagName);
// Set this tag value into LocAttr
dbManager.attrList.addTagValue(objType, tagName);
// Update the menus
SessionShare sshare = ResultTable.getSshare();
StatementHistory his = sshare.statementHistory();
Hashtable statement = his.getCurrentStatement();
StatementDefinition curStatement;
curStatement = sshare.getCurrentStatementType();
curStatement.updateValues(statement, true);
}
}
// Update statement menus
StatementDefinition curStatement;
SessionShare sshare = ResultTable.getSshare();
StatementHistory history = sshare.statementHistory();
Hashtable statement = history.getCurrentStatement();
curStatement = sshare.getCurrentStatementType();
curStatement.updateValues(statement, true);
}
else if(popStr.endsWith("/" + EDIT)) {
// Get the current objType and compare with the one
// for the existing dialog. If it has changed, create
// a new dialog.
SessionShare sshare = ResultTable.getSshare();
StatementHistory history = sshare.statementHistory();
Hashtable statement = history.getCurrentStatement();
String objT = (String)statement.get("ObjectType");
if(dial != null) {
// Dispose of the old dialog.
dial.dispose();
}
// Create a new one
dial = new TagEditDialog(TagButton.this);
// Set DialogObjType for testing next time
DialogObjType = objT;
if(dial != null)
dial.showDialog(TagButton.this);
}
}
if(status == true)
// Write out the previousTags to a persistence file
writePersistence();
}
}
}
| |
/*******************************************************************************
* Copyright (c) cortical.io GmbH. All rights reserved.
*
* This software is confidential and proprietary information.
* You shall use it only in accordance with the terms of the
* license agreement you entered into with cortical.io GmbH.
******************************************************************************/
package io.cortical.services.api.client;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.security.*;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.util.EntityUtils;
import com.fasterxml.jackson.databind.JavaType;
public class ApiInvoker {
private String basePath;
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
private HttpClient client = null;
private boolean ignoreSSLCertificates = false;
private ClientConnectionManager ignoreSSLConnectionManager;
public ApiInvoker(String basePath) {
this.basePath = basePath;
try {
initConnectionManager();
}
catch (ApiException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static <A> A deserializeResponse(HttpEntity he, Class<A> cls, Class baseType) throws IOException {
if (InputStream.class.isAssignableFrom(cls)) {
InputStream is = he.getContent();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
return (A) new ByteArrayInputStream(buffer.toByteArray());
}
else {
String json = EntityUtils.toString(he);
if (List.class.isAssignableFrom(cls)) {
List response = null;
JavaType typeInfo =
JsonUtil.getJsonMapper().getTypeFactory().constructCollectionType(List.class, baseType);
try {
response = (List<?>) JsonUtil.getJsonMapper().readValue(json, typeInfo);
}
catch (Exception e) {
JavaType typeInfo2 =
JsonUtil.getJsonMapper().getTypeFactory().constructCollectionType(List.class, typeInfo);
response = (List<?>) JsonUtil.getJsonMapper().readValue(json, typeInfo2);
}
return (A) response;
}
else if (String.class.equals(cls)) {
if (json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1) {
return (A) json.substring(1, json.length() - 2);
}
else {
return (A) json;
}
}
else {
return JsonUtil.getJsonMapper().readValue(json, cls);
}
}
}
public static Object deserialize(String json, String containerType, Class cls) throws ApiException {
try {
if ("List".equalsIgnoreCase(containerType) || "Array".equalsIgnoreCase(containerType)) {
JavaType typeInfo = JsonUtil.getJsonMapper().getTypeFactory().constructCollectionType(List.class, cls);
List response = (List<?>) JsonUtil.getJsonMapper().readValue(json, typeInfo);
return response;
}
else if (String.class.equals(cls)) {
if (json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1)
return json.substring(1, json.length() - 2);
else
return json;
}
else {
return JsonUtil.getJsonMapper().readValue(json, cls);
}
}
catch (IOException e) {
throw new ApiException(500, e.getMessage());
}
}
public static String serialize(Object obj) throws ApiException {
try {
if (obj != null) {
if (obj instanceof String) {
return String.valueOf(obj);
}
return JsonUtil.getJsonMapper().writeValueAsString(obj);
}
else
return null;
}
catch (Exception e) {
throw new ApiException(500, e.getMessage());
}
}
public void ignoreSSLCertificates(boolean ignoreSSLCertificates) {
this.ignoreSSLCertificates = ignoreSSLCertificates;
}
public void addDefaultHeader(String key, String value) {
defaultHeaderMap.put(key, value);
}
public String escapeString(String str) {
return str;
}
public <A> A invokeAPI(String path, String method, Map<String, String> queryParams, Object body,
Map<String, String> headerParams, String contentType, Class<A> cls, Class baseType) throws ApiException {
HttpClient client = getClient(this.basePath);
StringBuilder b = new StringBuilder();
for (String key : queryParams.keySet()) {
String value = queryParams.get(key);
if (value != null) {
if (b.toString().length() == 0)
b.append("?");
else
b.append("&");
b.append(escapeString(key)).append("=").append(escapeString(value));
}
}
String url = this.basePath + path + b.toString();
HashMap<String, String> headers = new HashMap<String, String>();
for (String key : headerParams.keySet()) {
headers.put(key, headerParams.get(key));
}
for (String key : defaultHeaderMap.keySet()) {
if (!headerParams.containsKey(key)) {
headers.put(key, defaultHeaderMap.get(key));
}
}
headers.put("Accept", "application/json,image/png");
HttpResponse response = null;
try {
if ("GET".equals(method)) {
HttpGet get = new HttpGet(url);
get.addHeader("Accept", "application/json");
for (String key : headers.keySet()) {
get.setHeader(key, headers.get(key));
}
response = client.execute(get);
}
else if ("POST".equals(method)) {
HttpPost post = new HttpPost(url);
if (body != null) {
post.setHeader("Content-Type", contentType);
post.setEntity(new StringEntity(serialize(body), "UTF-8"));
}
for (String key : headers.keySet()) {
post.setHeader(key, headers.get(key));
}
response = client.execute(post);
}
else if ("PUT".equals(method)) {
HttpPut put = new HttpPut(url);
if (body != null) {
put.setHeader("Content-Type", contentType);
put.setEntity(new StringEntity(serialize(body), "UTF-8"));
}
for (String key : headers.keySet()) {
put.setHeader(key, headers.get(key));
}
response = client.execute(put);
}
else if ("DELETE".equals(method)) {
HttpDelete delete = new HttpDelete(url);
for (String key : headers.keySet()) {
delete.setHeader(key, headers.get(key));
}
response = client.execute(delete);
}
else if ("PATCH".equals(method)) {
HttpPatch patch = new HttpPatch(url);
if (body != null) {
patch.setHeader("Content-Type", contentType);
patch.setEntity(new StringEntity(serialize(body), "UTF-8"));
}
for (String key : headers.keySet()) {
patch.setHeader(key, headers.get(key));
}
response = client.execute(patch);
}
int code = response.getStatusLine().getStatusCode();
if (code == 204)
return null;
else if (code >= 200 && code < 300) {
if (response.getEntity() != null) {
HttpEntity resEntity = response.getEntity();
return deserializeResponse(resEntity, cls, baseType);
}
else {
return cls.newInstance();
}
}
else {
if (response.getEntity() != null) {
HttpEntity resEntity = response.getEntity();
if (code == 400) {
String message = deserializeResponse(resEntity, String.class, baseType);
throw new ApiException(code, message);
}
return deserializeResponse(resEntity, cls, baseType);
}
else {
throw new ApiException(code, "no data");
}
}
}
catch (IOException e) {
throw new ApiException(500, e.getMessage());
}
catch (InstantiationException e) {
throw new ApiException(500, e.getMessage());
}
catch (IllegalAccessException e) {
throw new ApiException(500, e.getMessage());
}
}
private HttpClient getClient(String host) {
if (client == null) {
if (ignoreSSLCertificates && ignoreSSLConnectionManager != null) {
// Trust self signed certificates
client = new DefaultHttpClient(ignoreSSLConnectionManager, new BasicHttpParams());
}
else {
client = new DefaultHttpClient();
}
}
return client;
}
private void initConnectionManager() throws ApiException {
try {
final SSLContext sslContext = SSLContext.getInstance("SSL");
// set up a TrustManager that trusts everything
TrustManager[] trustManagers = new TrustManager[] { new X509TrustManager()
{
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} };
sslContext.init(null, trustManagers, new SecureRandom());
SSLSocketFactory sf = new SSLSocketFactory((KeyStore) null)
{
private javax.net.ssl.SSLSocketFactory sslFactory = sslContext.getSocketFactory();
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException {
return sslFactory.createSocket(socket, host, port, autoClose);
}
public Socket createSocket() throws IOException {
return sslFactory.createSocket();
}
};
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Scheme httpsScheme = new Scheme("https", sf, 443);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(httpsScheme);
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
ignoreSSLConnectionManager = new SingleClientConnManager(new BasicHttpParams(), schemeRegistry);
}
catch (NoSuchAlgorithmException e) {
// This will only be thrown if SSL isn't available for some reason.
throw new ApiException(500, e.getMessage());
}
catch (KeyManagementException e) {
// This might be thrown when passing a key into init(), but no key is being passed.
throw new ApiException(500, e.getMessage());
}
catch (GeneralSecurityException e) {
// This catches anything else that might go wrong.
// If anything goes wrong we default to the standard connection manager.
throw new ApiException(500, e.getMessage());
}
}
}
| |
package de.fu_berlin.imp.apiua.server.java_ee.utils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.SocketException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilderException;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.log4j.Logger;
import org.junit.Assert;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.UniformInterfaceException;
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.core.util.MultivaluedMapImpl;
import de.fu_berlin.imp.apiua.server.java_ee.model.Doclog;
import de.fu_berlin.imp.apiua.server.java_ee.model.DoclogAction;
import de.fu_berlin.imp.apiua.server.java_ee.model.DoclogRecord;
import de.fu_berlin.imp.apiua.server.java_ee.model.IIdentifier;
import de.fu_berlin.imp.apiua.server.java_ee.model.Rectangle;
public class DoclogRESTUtils {
private static final Logger LOGGER = Logger
.getLogger(DoclogRESTUtils.class);
public static WebResource getDoclogREST(URL APIUAsrv)
throws URISyntaxException {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
return client
.resource(new URI(APIUAsrv.toExternalForm() + "/rest/doclog"));
}
public static Doclog readDoclog(URL APIUAsrv, Object identifier)
throws Exception {
WebResource doclogService = getDoclogREST(APIUAsrv);
try {
return doclogService.path(identifier.toString()).path("test")
.accept(MediaType.APPLICATION_XML).get(Doclog.class);
} catch (UniformInterfaceException e) {
}
return null;
}
public static Doclog readDoclog(Object identifier) throws Exception {
return readDoclog(TestConfiguration.getDefaultAPIUAsrvURL(), identifier);
}
public static DoclogRecord readDoclogRecord(URL APIUAsrv, Object identifier,
int index) throws Exception {
WebResource doclogService = getDoclogREST(APIUAsrv);
try {
return doclogService.path(identifier.toString())
.path(new Integer(index).toString())
.accept(MediaType.APPLICATION_XML).get(DoclogRecord.class);
} catch (UniformInterfaceException e) {
} catch (WebApplicationException e) {
}
return null;
}
public static DoclogRecord readDoclogRecord(Object identifier, int index)
throws Exception {
return readDoclogRecord(TestConfiguration.getDefaultAPIUAsrvURL(),
identifier, index);
}
/**
* Returns the sorted {@link DoclogRecord}s identified by the given
* {@link IIdentifier} and the given indices.
*
* @param identifier
* @param indices
* @return
* @throws MalformedURLException
* @throws ConfigurationException
* @throws UriBuilderException
* @throws IllegalArgumentException
*/
public static DoclogRecord[] readSortedDoclogRecords(Object identifier,
int... indices) throws Exception {
List<DoclogRecord> doclogRecords = new ArrayList<DoclogRecord>();
for (int index : indices) {
DoclogRecord doclogRecord = readDoclogRecord(identifier, index);
doclogRecords.add(doclogRecord);
}
DoclogRecord[] sortedRecords = doclogRecords
.toArray(new DoclogRecord[0]);
Arrays.sort(sortedRecords, new Comparator<DoclogRecord>() {
@Override
public int compare(DoclogRecord o1, DoclogRecord o2) {
return o1.getDateTime().compareTo(o2.getDateTime());
}
});
return sortedRecords;
}
public static DoclogRecord createDoclogRecord(IIdentifier key,
final DoclogRecord doclogRecord) throws Exception {
return DoclogRESTUtils.createDoclogRecord(key, null, doclogRecord);
}
@SuppressWarnings("serial")
public static DoclogRecord createDoclogRecord(URL APIUAsrv, IIdentifier key,
final Object id, final DoclogRecord doclogRecord) throws Exception {
WebResource doclogService = getDoclogREST(APIUAsrv);
String success = doclogService.path(key.toString())
.type(MediaType.APPLICATION_FORM_URLENCODED)
.accept(MediaType.APPLICATION_XML)
.post(String.class, new MultivaluedMapImpl() {
{
if (id != null)
add("id", id.toString());
add("url", doclogRecord.getUrl());
add("ip", doclogRecord.getIp());
add("proxyIp", doclogRecord.getProxyIp());
add("action", doclogRecord.getAction());
add("actionParameter",
doclogRecord.getActionParameter());
add("dateTime", doclogRecord.getDateTime());
add("bounds.x", doclogRecord.getBounds().getX());
add("bounds.y", doclogRecord.getBounds().getY());
add("bounds.width", doclogRecord.getBounds().getWidth());
add("bounds.height", doclogRecord.getBounds()
.getHeight());
}
});
if (!success.contains("error")) {
return readDoclogRecord(key, -1);
}
return null;
}
public static DoclogRecord createDoclogRecord(IIdentifier key,
final Object id, final DoclogRecord doclogRecord) throws Exception {
return createDoclogRecord(TestConfiguration.getDefaultAPIUAsrvURL(), key,
id, doclogRecord);
}
public static boolean deleteDoclogRecord(URL APIUAsrv, Object identifier,
int index) throws Exception {
WebResource doclogService = getDoclogREST(APIUAsrv);
String success = doclogService.path(identifier.toString())
.path(new Integer(index).toString())
.accept(MediaType.APPLICATION_XML).delete(String.class);
return !success.contains("error");
}
public static boolean deleteDoclogRecord(Object identifier, int index)
throws Exception {
return deleteDoclogRecord(TestConfiguration.getDefaultAPIUAsrvURL(),
identifier, index);
}
/**
* Tests if the {@link DoclogRecord} sufficiently equals the given
* {@link DoclogRecord}.
* <p>
* The actual {@link DoclogRecord} is retrieved from the REST server.
*
* @param identifier
* @param index
* @param expected
* @param maxTimeDifference
* @throws SocketException
* @throws UnknownHostException
* @throws MalformedURLException
* @throws ConfigurationException
* @throws UriBuilderException
* @throws IllegalArgumentException
*/
public static void testDoclogRecord(IIdentifier identifier, int index,
DoclogRecord expected, int maxTimeDifference) throws Exception {
DoclogRecord actual = readDoclogRecord(identifier, index);
testDoclogRecord(expected, actual, maxTimeDifference);
}
/**
* Tests if the {@link DoclogRecord} sufficiently equals the given
* {@link DoclogRecord}.
* <p>
* The actual {@link DoclogRecord} is retrieved from the REST server.
*
* @param expected
* @param actual
* @throws SocketException
* @throws UnknownHostException
* @throws MalformedURLException
*/
public static void testDoclogRecord(DoclogRecord expected,
DoclogRecord actual, int maxTimeDifference) throws SocketException,
UnknownHostException, MalformedURLException {
assertNotNull(actual);
LOGGER.debug("Comparing " + DoclogRecord.class.getSimpleName()
+ ":\n\t" + expected + "\n\t" + actual);
if (expected.getIp() == null) {
InetAddress[] inetAddresses = Utils.getIPAdresses();
InetAddress inetAddress = InetAddress.getByName(actual.getIp());
assertTrue(ArrayUtils.contains(inetAddresses, inetAddress));
} else {
assertEquals(expected.getIp(), actual.getIp());
}
assertEquals("Proxy IP differs", expected.getProxyIp(),
actual.getProxyIp());
if (expected.getUrl() != null) {
List<String> expectedUrls = Arrays.asList(expected.getUrl(),
UrlUtils.removeUserInfo(expected.getUrl()));
assertTrue("URL " + actual.getUrl()
+ " was not element of the possible expected urls "
+ StringUtils.join(expectedUrls, " or "),
expectedUrls.contains(expected.getUrl()));
}
assertEquals(DoclogAction.class.getSimpleName() + " differs",
expected.getAction(), actual.getAction());
assertEquals(DoclogAction.class.getSimpleName() + " parameter differs",
expected.getActionParameter(), actual.getActionParameter());
Rectangle actualBounds = actual.getBounds();
Rectangle expectedBounds = expected.getBounds();
if (actualBounds != null && expectedBounds != null) {
if (expectedBounds.getX() > -1)
assertEquals("X scroll position differs",
expectedBounds.getX(), actualBounds.getX());
if (expectedBounds.getY() > -1)
assertEquals("Y scroll position differs",
expectedBounds.getY(), actualBounds.getY());
if (expectedBounds.getWidth() > -1) {
int maxWidth = expectedBounds.getWidth();
int minWidth = expectedBounds.getWidth() - 20;
assertTrue(
"The actual browser width (" + actualBounds.getWidth()
+ ") is not within " + minWidth + " and "
+ maxWidth, actualBounds.getWidth() <= maxWidth
&& actualBounds.getWidth() >= minWidth);
}
if (expectedBounds.getHeight() > -1) {
int maxHeight = expectedBounds.getHeight();
int minHeight = expectedBounds.getHeight() - 20;
assertTrue(
"The actual browser height ("
+ actualBounds.getHeight() + ") is not within "
+ minHeight + " and " + maxHeight,
actualBounds.getHeight() <= maxHeight
&& actualBounds.getHeight() >= minHeight);
}
} else {
assertTrue(actualBounds == null && expectedBounds == null);
}
long difference = expected.getDateTime().getMillis()
- actual.getDateTime().getMillis();
if (difference < -maxTimeDifference) {
Assert.fail("Actual event occured " + (-difference)
+ "ms to late although the tolerance is set to "
+ maxTimeDifference + "ms.");
} else if (difference > maxTimeDifference) {
Assert.fail("Actual event occured " + difference
+ "ms to early although the tolerance is set to "
+ maxTimeDifference + "ms.");
}
}
}
| |
/*
* Copyright 2015 OpenCB
*
* 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.opencb.opencga.storage.core.runner;
import org.opencb.commons.io.DataReader;
import org.opencb.commons.io.DataWriter;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.*;
/**
* Created by jacobo on 5/02/15.
*/
@Deprecated
public class ThreadRunner {
private ExecutorService executorService;
private List<ReadNode> readNodes = new LinkedList<>();
private List<Node> taskNodes = new LinkedList<>();
private List<WriterNode> writerNodes = new LinkedList<>();
private List<Node> nodes = new LinkedList<>();
private final int batchSize;
private final Object syncObject = new Object();
private static final List<Object> SINGLETON_LIST = Collections.singletonList(new Object());
private static final List POISON_PILL = new LinkedList();
public ThreadRunner(ExecutorService executorService, int batchSize) {
this.executorService = executorService;
this.batchSize = batchSize;
}
public <I,O> TaskNode<I,O> newTaskNode(List<Task<I,O>> tasks) {
TaskNode<I, O> taskNode = new TaskNode<>(tasks, "task-node-" + taskNodes.size());
taskNodes.add(taskNode);
return taskNode;
}
public <T> SimpleTaskNode<T> newSimpleTaskNode(org.opencb.commons.run.Task<T> task, int n) {
List<org.opencb.commons.run.Task<T>> tasks = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
tasks.add(task);
}
SimpleTaskNode<T> taskNode = new SimpleTaskNode<>(tasks, "task-node-" + taskNodes.size());
taskNodes.add(taskNode);
return taskNode;
}
public <T> SimpleTaskNode<T> newSimpleTaskNode(List<org.opencb.commons.run.Task<T>> tasks) {
SimpleTaskNode<T> taskNode = new SimpleTaskNode<>(tasks, "task-node-" + taskNodes.size());
taskNodes.add(taskNode);
return taskNode;
}
public <I,O> TaskNode<I,O> newTaskNode(Task<I,O> task, int n) {
List<Task<I,O>> tasks = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
tasks.add(task);
}
TaskNode<I, O> taskNode = new TaskNode<>(tasks, "task-node-" + taskNodes.size());
taskNodes.add(taskNode);
return taskNode;
}
public <O> ReadNode<O> newReaderNode(List<DataReader<O>> readers) {
ReadNode<O> readNode = new ReadNode<>(readers, "reader-node-" + readNodes.size());
readNodes.add(readNode);
return readNode;
}
public <O> ReadNode<O> newReaderNode(DataReader<O> reader, int n) {
List<DataReader<O>> readers = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
readers.add(reader);
}
ReadNode<O> readNode = new ReadNode<>(readers, "reader-node-" + readNodes.size());
readNodes.add(readNode);
return readNode;
}
public <I> WriterNode<I> newWriterNode(List<DataWriter<I>> writers) {
WriterNode<I> writerNode = new WriterNode<>(writers, "writer-node-" + writerNodes.size());
writerNodes.add(writerNode);
return writerNode;
}
public <I> WriterNode<I> newWriterNode(DataWriter<I> writer, int n) {
List<DataWriter<I>> writers = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
writers.add(writer);
}
WriterNode<I> writerNode = new WriterNode<>(writers, "writer-node-" + writerNodes.size());
writerNodes.add(writerNode);
return writerNode;
}
public void run() {
start();
join();
}
public void start() {
nodes.addAll(readNodes);
nodes.addAll(taskNodes);
nodes.addAll(writerNodes);
for (Node node : nodes) {
node.init();
node.pre();
}
for (ReadNode readNode : readNodes) {
readNode.start();
}
}
public void join() {
boolean allFinalized;
synchronized (syncObject) {
do {
allFinalized = true;
for (Node node : nodes) {
if (!node.isFinished()) {
System.out.println("Node " + node.name + " is not finished pending:" + node.pendingJobs + " lastBatch:" + node.lastBatch);
allFinalized = false;
break;
} /*else {
System.out.println("Node " + node.name + " is finished");
}*/
}
if (!allFinalized) {
try {
System.out.println("WAIT");
syncObject.wait();
System.out.println("NOTIFY");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} while (!allFinalized);
}
for (Node node : nodes) {
node.post();
}
executorService.shutdown();
}
public static abstract class Task<I, O> {
public boolean pre() {return true;}
public abstract List<O> apply(List<I> batch) throws IOException;
public boolean post() {return true;}
}
public class ReadNode<O> extends Node<Object, O, DataReader<O>> {
private ReadNode(List<DataReader<O>> tasks, String name) {
super(tasks, name);
}
public void start() {
submit(SINGLETON_LIST);
}
@Override
List<O> doJob(List<Object> b) {
// System.out.println(name + " - read start - " );
List<O> reddenBatch = super.doJob(b);
if (reddenBatch != null) {
// System.out.println(name + " - read end - " + reddenBatch.size());
if (!reddenBatch.isEmpty()) {
// System.out.println(name + " - non empty list! - " + reddenBatch.size());
start();
} else {
// System.out.println("Empty list! Lets submit the last batch " + !isLastBatchSent());
if (!isLastBatchSent()) {
submit(POISON_PILL);
}
}
} else {
// System.out.println(name + " - read end NULL taskQueue.size : " + taskQueue.size());
}
return reddenBatch;
}
@Override
protected List<O> execute(DataReader<O> reader, List<Object> ignored) {
List<O> read = reader.read(batchSize);
return read;
}
@Override
protected void pre() {
for (DataReader<O> reader : tasks) {
reader.open();
reader.pre();
}
}
@Override
protected void post() {
for (DataReader<O> reader : tasks) {
reader.post();
reader.close();
}
}
}
public class TaskNode<I, O> extends Node<I,O,Task<I,O>> {
private TaskNode(List<Task<I, O>> tasks, String name) {
super(tasks, name);
}
@Override
protected List<O> execute(Task<I, O> task, List<I> batch) {
try {
return task.apply(batch);
} catch (IOException e) {
e.printStackTrace();
}
return Collections.emptyList();
}
@Override
protected void pre() {
for (Task<I, O> task : tasks) {
task.pre();
}
}
@Override
protected void post() {
for (Task<I, O> task : tasks) {
task.post();
}
}
}
public class SimpleTaskNode<I> extends Node<I, I, org.opencb.commons.run.Task<I>> {
private SimpleTaskNode(List<org.opencb.commons.run.Task<I>> tasks, String name) {
super(tasks, name);
}
@Override
protected void pre() {
for (org.opencb.commons.run.Task<I> task : tasks) {
task.pre();
}
}
@Override
protected void post() {
for (org.opencb.commons.run.Task<I> task : tasks) {
task.post();
}
}
@Override
protected List<I> execute(org.opencb.commons.run.Task<I> task, List<I> batch) {
try {
task.apply(batch);
} catch (IOException e) {
e.printStackTrace();
}
return batch;
}
}
public class WriterNode<I> extends Node<I,Object, DataWriter<I>> {
private WriterNode(List<DataWriter<I>> tasks, String name) {
super(tasks, name);
}
@Override
protected void pre() {
for (DataWriter<I> writer : tasks) {
writer.open();
writer.pre();
}
}
@Override
protected void post() {
for (DataWriter<I> writer : tasks) {
writer.post();
writer.close();
}
}
@Override
protected List<Object> execute(DataWriter<I> writer, List<I> batch) {
writer.write(batch);
return SINGLETON_LIST;
}
}
abstract class Node<I, O, EXECUTOR> {
protected final List<EXECUTOR> tasks;
protected final String name;
private final BlockingQueue<EXECUTOR> taskQueue;
private List<Node<O, ?, ?>> nodes;
private int pendingJobs;
private boolean lastBatch;
private boolean lastBatchSent;
public Node(List<EXECUTOR> tasks, String name) {
this.tasks = tasks;
this.name = name;
taskQueue = new ArrayBlockingQueue<>(tasks.size(), false, tasks);
nodes = new LinkedList<>();
}
/* package */ void init() {
pendingJobs = 0;
lastBatch = false;
lastBatchSent = false;
}
protected abstract void pre ();
protected abstract void post ();
/*package*/ List<O> doJob(List<I> batch) {
List<O> generatedBatch;
assert lastBatchSent == false;
if (batch == POISON_PILL) {
lastBatch = true;
synchronized (name) {
pendingJobs--;
}
// System.out.println(name + " - lastBatch");
generatedBatch = Collections.emptyList();
} else {
EXECUTOR task = taskQueue.poll();
boolean nextNodesAvailable = true;
for (Node<O, ?, ?> node : nodes) {
nextNodesAvailable &= node.isAvailable();
}
if (task == null) { //No available task
resubmit(batch);
generatedBatch = null;
} else if (!nextNodesAvailable) { //Next nodes have to many batches.
try {
taskQueue.put(task);
} catch (InterruptedException e) {
e.printStackTrace();
}
resubmit(batch);
generatedBatch = null;
} else { //Execute
generatedBatch = execute(task, batch);
// System.out.println(name + " - end job - " + generatedBatch.size());
for (Node<O, ?, ?> node : nodes) {
node.submit(generatedBatch);
}
try {
taskQueue.put(task);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (name) {
pendingJobs--;
}
// System.out.println(name + " - pendingJobs " + pendingJobs);
}
}
if (isFinished()) {
if (!lastBatchSent) {
for (Node<O, ?, ?> node : nodes) {
node.submit(POISON_PILL);
}
lastBatchSent = true;
}
System.out.println("Node '" + name + "' is finished");
synchronized (syncObject) {
syncObject.notify();
}
} else {
System.out.println("Node '" + name + "' pendingJobs " + pendingJobs);
}
return generatedBatch;
}
protected abstract List<O> execute(EXECUTOR task, List<I> batch);
private void resubmit(final List<I> batch) {
executorService.submit(new Runnable() {
public void run() {
doJob(batch);
}
});
}
/*package*/ void submit(final List<I> batch) {
// System.out.println("Submitting batch: pendingJobs = " + pendingJobs + " - " + "[" + (isAvailable()? " " : "*") + "]" + name + " - " + Thread.currentThread().getName());
pendingJobs ++;
resubmit(batch);
}
public boolean isAvailable() {
return pendingJobs < tasks.size();
}
public boolean isFinished() {
return pendingJobs == 0 && lastBatch;
}
public boolean isLastBatchSent() {
return lastBatchSent;
}
public Node<I, O, EXECUTOR> append(Node<O, ?, ?> node) {
nodes.add(node);
return this;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.db.marshal;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.cassandra.exceptions.*;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.utils.Pair;
/**
* Parse a string containing an Type definition.
*/
public class TypeParser
{
private final String str;
private int idx;
// A cache of parsed string, specially useful for DynamicCompositeType
private static final Map<String, AbstractType<?>> cache = new HashMap<String, AbstractType<?>>();
public static final TypeParser EMPTY_PARSER = new TypeParser("", 0);
private TypeParser(String str, int idx)
{
this.str = str;
this.idx = idx;
}
public TypeParser(String str)
{
this(str, 0);
}
/**
* Parse a string containing an type definition.
*/
public static AbstractType<?> parse(String str) throws SyntaxException, ConfigurationException
{
if (str == null)
return BytesType.instance;
AbstractType<?> type = cache.get(str);
if (type != null)
return type;
// This could be simplier (i.e. new TypeParser(str).parse()) but we avoid creating a TypeParser object if not really necessary.
int i = 0;
i = skipBlank(str, i);
int j = i;
while (!isEOS(str, i) && isIdentifierChar(str.charAt(i)))
++i;
if (i == j)
return BytesType.instance;
String name = str.substring(j, i);
i = skipBlank(str, i);
if (!isEOS(str, i) && str.charAt(i) == '(')
type = getAbstractType(name, new TypeParser(str, i));
else
type = getAbstractType(name);
// We don't really care about concurrency here. Worst case scenario, we do some parsing unnecessarily
cache.put(str, type);
return type;
}
public static AbstractType<?> parse(CharSequence compareWith) throws SyntaxException, ConfigurationException
{
return parse(compareWith == null ? null : compareWith.toString());
}
public static String getShortName(AbstractType<?> type)
{
return type.getClass().getSimpleName();
}
/**
* Parse an AbstractType from current position of this parser.
*/
public AbstractType<?> parse() throws SyntaxException, ConfigurationException
{
skipBlank();
String name = readNextIdentifier();
skipBlank();
if (!isEOS() && str.charAt(idx) == '(')
return getAbstractType(name, this);
else
return getAbstractType(name);
}
public Map<String, String> getKeyValueParameters() throws SyntaxException
{
Map<String, String> map = new HashMap<String, String>();
if (isEOS())
return map;
if (str.charAt(idx) != '(')
throw new IllegalStateException();
++idx; // skipping '('
while (skipBlankAndComma())
{
if (str.charAt(idx) == ')')
{
++idx;
return map;
}
String k = readNextIdentifier();
String v = "";
skipBlank();
if (str.charAt(idx) == '=')
{
++idx;
skipBlank();
v = readNextIdentifier();
}
else if (str.charAt(idx) != ',' && str.charAt(idx) != ')')
{
throwSyntaxError("unexpected character '" + str.charAt(idx) + "'");
}
map.put(k, v);
}
throw new SyntaxException(String.format("Syntax error parsing '%s' at char %d: unexpected end of string", str, idx));
}
public List<AbstractType<?>> getTypeParameters() throws SyntaxException, ConfigurationException
{
List<AbstractType<?>> list = new ArrayList<AbstractType<?>>();
if (isEOS())
return list;
if (str.charAt(idx) != '(')
throw new IllegalStateException();
++idx; // skipping '('
while (skipBlankAndComma())
{
if (str.charAt(idx) == ')')
{
++idx;
return list;
}
try
{
list.add(parse());
}
catch (SyntaxException e)
{
SyntaxException ex = new SyntaxException(String.format("Exception while parsing '%s' around char %d", str, idx));
ex.initCause(e);
throw ex;
}
}
throw new SyntaxException(String.format("Syntax error parsing '%s' at char %d: unexpected end of string", str, idx));
}
public Map<Byte, AbstractType<?>> getAliasParameters() throws SyntaxException, ConfigurationException
{
Map<Byte, AbstractType<?>> map = new HashMap<Byte, AbstractType<?>>();
if (isEOS())
return map;
if (str.charAt(idx) != '(')
throw new IllegalStateException();
++idx; // skipping '('
while (skipBlankAndComma())
{
if (str.charAt(idx) == ')')
{
++idx;
return map;
}
String alias = readNextIdentifier();
if (alias.length() != 1)
throwSyntaxError("An alias should be a single character");
char aliasChar = alias.charAt(0);
if (aliasChar < 33 || aliasChar > 127)
throwSyntaxError("An alias should be a single character in [0..9a..bA..B-+._&]");
skipBlank();
if (!(str.charAt(idx) == '=' && str.charAt(idx+1) == '>'))
throwSyntaxError("expecting '=>' token");
idx += 2;
skipBlank();
try
{
map.put((byte)aliasChar, parse());
}
catch (SyntaxException e)
{
SyntaxException ex = new SyntaxException(String.format("Exception while parsing '%s' around char %d", str, idx));
ex.initCause(e);
throw ex;
}
}
throw new SyntaxException(String.format("Syntax error parsing '%s' at char %d: unexpected end of string", str, idx));
}
public Map<ByteBuffer, CollectionType> getCollectionsParameters() throws SyntaxException, ConfigurationException
{
Map<ByteBuffer, CollectionType> map = new HashMap<ByteBuffer, CollectionType>();
if (isEOS())
return map;
if (str.charAt(idx) != '(')
throw new IllegalStateException();
++idx; // skipping '('
while (skipBlankAndComma())
{
if (str.charAt(idx) == ')')
{
++idx;
return map;
}
ByteBuffer bb = fromHex(readNextIdentifier());
skipBlank();
if (str.charAt(idx) != ':')
throwSyntaxError("expecting ':' token");
++idx;
skipBlank();
try
{
AbstractType<?> type = parse();
if (!(type instanceof CollectionType))
throw new SyntaxException(type.toString() + " is not a collection type");
map.put(bb, (CollectionType)type);
}
catch (SyntaxException e)
{
SyntaxException ex = new SyntaxException(String.format("Exception while parsing '%s' around char %d", str, idx));
ex.initCause(e);
throw ex;
}
}
throw new SyntaxException(String.format("Syntax error parsing '%s' at char %d: unexpected end of string", str, idx));
}
private ByteBuffer fromHex(String hex) throws SyntaxException
{
try
{
return ByteBufferUtil.hexToBytes(hex);
}
catch (NumberFormatException e)
{
throwSyntaxError(e.getMessage());
return null;
}
}
public Pair<Pair<String, ByteBuffer>, List<Pair<ByteBuffer, AbstractType>>> getUserTypeParameters() throws SyntaxException, ConfigurationException
{
if (isEOS() || str.charAt(idx) != '(')
throw new IllegalStateException();
++idx; // skipping '('
skipBlankAndComma();
String keyspace = readNextIdentifier();
skipBlankAndComma();
ByteBuffer typeName = fromHex(readNextIdentifier());
List<Pair<ByteBuffer, AbstractType>> defs = new ArrayList<>();
while (skipBlankAndComma())
{
if (str.charAt(idx) == ')')
{
++idx;
return Pair.create(Pair.create(keyspace, typeName), defs);
}
ByteBuffer name = fromHex(readNextIdentifier());
skipBlank();
if (str.charAt(idx) != ':')
throwSyntaxError("expecting ':' token");
++idx;
skipBlank();
try
{
AbstractType type = parse();
defs.add(Pair.create(name, type));
}
catch (SyntaxException e)
{
SyntaxException ex = new SyntaxException(String.format("Exception while parsing '%s' around char %d", str, idx));
ex.initCause(e);
throw ex;
}
}
throw new SyntaxException(String.format("Syntax error parsing '%s' at char %d: unexpected end of string", str, idx));
}
private static AbstractType<?> getAbstractType(String compareWith) throws ConfigurationException
{
String className = compareWith.contains(".") ? compareWith : "org.apache.cassandra.db.marshal." + compareWith;
Class<? extends AbstractType<?>> typeClass = FBUtilities.<AbstractType<?>>classForName(className, "abstract-type");
try
{
Field field = typeClass.getDeclaredField("instance");
return (AbstractType<?>) field.get(null);
}
catch (NoSuchFieldException e)
{
// Trying with empty parser
return getRawAbstractType(typeClass, EMPTY_PARSER);
}
catch (IllegalAccessException e)
{
// Trying with empty parser
return getRawAbstractType(typeClass, EMPTY_PARSER);
}
}
private static AbstractType<?> getAbstractType(String compareWith, TypeParser parser) throws SyntaxException, ConfigurationException
{
String className = compareWith.contains(".") ? compareWith : "org.apache.cassandra.db.marshal." + compareWith;
Class<? extends AbstractType<?>> typeClass = FBUtilities.<AbstractType<?>>classForName(className, "abstract-type");
try
{
Method method = typeClass.getDeclaredMethod("getInstance", TypeParser.class);
return (AbstractType<?>) method.invoke(null, parser);
}
catch (NoSuchMethodException e)
{
// Trying to see if we have an instance field and apply the default parameter to it
AbstractType<?> type = getRawAbstractType(typeClass);
return AbstractType.parseDefaultParameters(type, parser);
}
catch (IllegalAccessException e)
{
// Trying to see if we have an instance field and apply the default parameter to it
AbstractType<?> type = getRawAbstractType(typeClass);
return AbstractType.parseDefaultParameters(type, parser);
}
catch (InvocationTargetException e)
{
ConfigurationException ex = new ConfigurationException("Invalid definition for comparator " + typeClass.getName() + ".");
ex.initCause(e.getTargetException());
throw ex;
}
}
private static AbstractType<?> getRawAbstractType(Class<? extends AbstractType<?>> typeClass) throws ConfigurationException
{
try
{
Field field = typeClass.getDeclaredField("instance");
return (AbstractType<?>) field.get(null);
}
catch (NoSuchFieldException e)
{
throw new ConfigurationException("Invalid comparator class " + typeClass.getName() + ": must define a public static instance field or a public static method getInstance(TypeParser).");
}
catch (IllegalAccessException e)
{
throw new ConfigurationException("Invalid comparator class " + typeClass.getName() + ": must define a public static instance field or a public static method getInstance(TypeParser).");
}
}
private static AbstractType<?> getRawAbstractType(Class<? extends AbstractType<?>> typeClass, TypeParser parser) throws ConfigurationException
{
try
{
Method method = typeClass.getDeclaredMethod("getInstance", TypeParser.class);
return (AbstractType<?>) method.invoke(null, parser);
}
catch (NoSuchMethodException e)
{
throw new ConfigurationException("Invalid comparator class " + typeClass.getName() + ": must define a public static instance field or a public static method getInstance(TypeParser).");
}
catch (IllegalAccessException e)
{
throw new ConfigurationException("Invalid comparator class " + typeClass.getName() + ": must define a public static instance field or a public static method getInstance(TypeParser).");
}
catch (InvocationTargetException e)
{
ConfigurationException ex = new ConfigurationException("Invalid definition for comparator " + typeClass.getName() + ".");
ex.initCause(e.getTargetException());
throw ex;
}
}
private void throwSyntaxError(String msg) throws SyntaxException
{
throw new SyntaxException(String.format("Syntax error parsing '%s' at char %d: %s", str, idx, msg));
}
private boolean isEOS()
{
return isEOS(str, idx);
}
private static boolean isEOS(String str, int i)
{
return i >= str.length();
}
private static boolean isBlank(int c)
{
return c == ' ' || c == '\t' || c == '\n';
}
private void skipBlank()
{
idx = skipBlank(str, idx);
}
private static int skipBlank(String str, int i)
{
while (!isEOS(str, i) && isBlank(str.charAt(i)))
++i;
return i;
}
// skip all blank and at best one comma, return true if there not EOS
private boolean skipBlankAndComma()
{
boolean commaFound = false;
while (!isEOS())
{
int c = str.charAt(idx);
if (c == ',')
{
if (commaFound)
return true;
else
commaFound = true;
}
else if (!isBlank(c))
{
return true;
}
++idx;
}
return false;
}
/*
* [0..9a..bA..B-+._&]
*/
private static boolean isIdentifierChar(int c)
{
return (c >= '0' && c <= '9')
|| (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
|| c == '-' || c == '+' || c == '.' || c == '_' || c == '&';
}
// left idx positioned on the character stopping the read
public String readNextIdentifier()
{
int i = idx;
while (!isEOS() && isIdentifierChar(str.charAt(idx)))
++idx;
return str.substring(i, idx);
}
public char readNextChar()
{
skipBlank();
return str.charAt(idx++);
}
/**
* Helper function to ease the writing of AbstractType.toString() methods.
*/
public static String stringifyAliasesParameters(Map<Byte, AbstractType<?>> aliases)
{
StringBuilder sb = new StringBuilder();
sb.append('(');
Iterator<Map.Entry<Byte, AbstractType<?>>> iter = aliases.entrySet().iterator();
if (iter.hasNext())
{
Map.Entry<Byte, AbstractType<?>> entry = iter.next();
sb.append((char)(byte)entry.getKey()).append("=>").append(entry.getValue());
}
while (iter.hasNext())
{
Map.Entry<Byte, AbstractType<?>> entry = iter.next();
sb.append(',').append((char)(byte)entry.getKey()).append("=>").append(entry.getValue());
}
sb.append(')');
return sb.toString();
}
/**
* Helper function to ease the writing of AbstractType.toString() methods.
*/
public static String stringifyTypeParameters(List<AbstractType<?>> types)
{
StringBuilder sb = new StringBuilder();
sb.append('(').append(StringUtils.join(types, ",")).append(')');
return sb.toString();
}
public static String stringifyCollectionsParameters(Map<ByteBuffer, CollectionType> collections)
{
StringBuilder sb = new StringBuilder();
sb.append('(');
boolean first = true;
for (Map.Entry<ByteBuffer, CollectionType> entry : collections.entrySet())
{
if (!first)
{
sb.append(',');
}
first = false;
sb.append(ByteBufferUtil.bytesToHex(entry.getKey())).append(":");
entry.getValue().appendToStringBuilder(sb);
}
sb.append(')');
return sb.toString();
}
public static String stringifyUserTypeParameters(String keysace, ByteBuffer typeName, List<ByteBuffer> columnNames, List<AbstractType<?>> columnTypes)
{
StringBuilder sb = new StringBuilder();
sb.append('(').append(keysace).append(",").append(ByteBufferUtil.bytesToHex(typeName));
for (int i = 0; i < columnNames.size(); i++)
{
sb.append(',');
sb.append(ByteBufferUtil.bytesToHex(columnNames.get(i))).append(":");
sb.append(columnTypes.get(i).toString());
}
sb.append(')');
return sb.toString();
}
}
| |
/*
* 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.security.authc.ldap;
import com.unboundid.ldap.listener.InMemoryDirectoryServer;
import com.unboundid.ldap.sdk.GetEntryLDAPConnectionPoolHealthCheck;
import com.unboundid.ldap.sdk.LDAPConnectionPool;
import com.unboundid.ldap.sdk.LDAPConnectionPoolHealthCheck;
import com.unboundid.ldap.sdk.LDAPException;
import com.unboundid.ldap.sdk.LDAPURL;
import com.unboundid.ldap.sdk.SimpleBindRequest;
import com.unboundid.ldap.sdk.SingleServerSet;
import org.elasticsearch.action.support.PlainActionFuture;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.settings.MockSecureSettings;
import org.elasticsearch.common.settings.SecureString;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.TestEnvironment;
import org.elasticsearch.threadpool.TestThreadPool;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.xpack.core.security.authc.RealmConfig;
import org.elasticsearch.xpack.core.security.authc.ldap.LdapUserSearchSessionFactorySettings;
import org.elasticsearch.xpack.core.security.authc.ldap.PoolingSessionFactorySettings;
import org.elasticsearch.xpack.core.security.authc.ldap.support.LdapSearchScope;
import org.elasticsearch.xpack.core.security.authc.ldap.support.SessionFactorySettings;
import org.elasticsearch.xpack.core.security.support.NoOpLogger;
import org.elasticsearch.xpack.core.ssl.SSLService;
import org.elasticsearch.xpack.security.authc.ldap.support.LdapSession;
import org.elasticsearch.xpack.security.authc.ldap.support.LdapTestCase;
import org.junit.After;
import org.junit.Before;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isEmptyString;
import static org.hamcrest.Matchers.notNullValue;
public class LdapUserSearchSessionFactoryTests extends LdapTestCase {
private SSLService sslService;
private Settings globalSettings;
private ThreadPool threadPool;
@Before
public void init() throws Exception {
Path certPath = getDataPath("support/smb_ca.crt");
Environment env = TestEnvironment.newEnvironment(Settings.builder().put("path.home", createTempDir()).build());
/*
* Prior to each test we reinitialize the socket factory with a new SSLService so that we get a new SSLContext.
* If we re-use a SSLContext, previously connected sessions can get re-established which breaks hostname
* verification tests since a re-established connection does not perform hostname verification.
*/
globalSettings = Settings.builder()
.put("path.home", createTempDir())
.put("xpack.ssl.certificate_authorities", certPath)
.build();
sslService = new SSLService(globalSettings, env);
threadPool = new TestThreadPool("LdapUserSearchSessionFactoryTests");
}
@After
public void shutdown() throws InterruptedException {
terminate(threadPool);
}
private MockSecureSettings newSecureSettings(String key, String value) {
MockSecureSettings secureSettings = new MockSecureSettings();
secureSettings.setString(key, value);
return secureSettings;
}
public void testSupportsUnauthenticatedSessions() throws Exception {
final boolean useAttribute = randomBoolean();
Settings.Builder builder = Settings.builder()
.put(buildLdapSettings(ldapUrls(), Strings.EMPTY_ARRAY, "", LdapSearchScope.SUB_TREE))
.put("user_search.base_dn", "")
.put("bind_dn", "cn=Horatio Hornblower,ou=people,o=sevenSeas")
.put("user_search.pool.enabled", randomBoolean());
final boolean useLegacyBindPassword = configureBindPassword(builder);
if (useAttribute) {
builder.put("user_search.attribute", "cn");
} else {
builder.put("user_search.filter", "(cn={0})");
}
RealmConfig config = new RealmConfig("ldap_realm", builder.build(), globalSettings, TestEnvironment.newEnvironment(globalSettings),
new ThreadContext(globalSettings));
LdapUserSearchSessionFactory sessionFactory = getLdapUserSearchSessionFactory(config, sslService, threadPool);
try {
assertThat(sessionFactory.supportsUnauthenticatedSession(), is(true));
} finally {
sessionFactory.close();
}
assertDeprecationWarnings(useAttribute, useLegacyBindPassword);
}
public void testUserSearchSubTree() throws Exception {
String groupSearchBase = "o=sevenSeas";
String userSearchBase = "o=sevenSeas";
final boolean useAttribute = randomBoolean();
Settings.Builder builder = Settings.builder()
.put(buildLdapSettings(ldapUrls(), Strings.EMPTY_ARRAY, groupSearchBase, LdapSearchScope.SUB_TREE))
.put("user_search.base_dn", userSearchBase)
.put("bind_dn", "cn=Horatio Hornblower,ou=people,o=sevenSeas")
.put("user_search.pool.enabled", randomBoolean());
final boolean useLegacyBindPassword = configureBindPassword(builder);
if (useAttribute) {
builder.put("user_search.attribute", "cn");
} else {
builder.put("user_search.filter", "(cn={0})");
}
RealmConfig config = new RealmConfig("ldap_realm", builder.build(), globalSettings, TestEnvironment.newEnvironment(globalSettings),
new ThreadContext(globalSettings));
LdapUserSearchSessionFactory sessionFactory = getLdapUserSearchSessionFactory(config, sslService, threadPool);
String user = "William Bush";
SecureString userPass = new SecureString("pass");
try {
// auth
try (LdapSession ldap = session(sessionFactory, user, userPass)) {
assertConnectionValid(ldap.getConnection(), sessionFactory.bindCredentials);
String dn = ldap.userDn();
assertThat(dn, containsString(user));
}
//lookup
try (LdapSession ldap = unauthenticatedSession(sessionFactory, user)) {
assertConnectionValid(ldap.getConnection(), sessionFactory.bindCredentials);
String dn = ldap.userDn();
assertThat(dn, containsString(user));
}
} finally {
sessionFactory.close();
}
assertDeprecationWarnings(useAttribute, useLegacyBindPassword);
}
public void testUserSearchBaseScopeFailsWithWrongBaseDN() throws Exception {
String groupSearchBase = "o=sevenSeas";
String userSearchBase = "o=sevenSeas";
final boolean useAttribute = randomBoolean();
Settings.Builder builder = Settings.builder()
.put(buildLdapSettings(ldapUrls(), Strings.EMPTY_ARRAY, groupSearchBase, LdapSearchScope.SUB_TREE))
.put("user_search.base_dn", userSearchBase)
.put("bind_dn", "cn=Horatio Hornblower,ou=people,o=sevenSeas")
.put("user_search.scope", LdapSearchScope.BASE)
.put("user_search.pool.enabled", randomBoolean());
final boolean useLegacyBindPassword = configureBindPassword(builder);
if (useAttribute) {
builder.put("user_search.attribute", "cn");
} else {
builder.put("user_search.filter", "(cn={0})");
}
RealmConfig config = new RealmConfig("ldap_realm", builder.build(), globalSettings, TestEnvironment.newEnvironment(globalSettings),
new ThreadContext(globalSettings));
LdapUserSearchSessionFactory sessionFactory = getLdapUserSearchSessionFactory(config, sslService, threadPool);
String user = "William Bush";
SecureString userPass = new SecureString("pass");
try {
assertNull(session(sessionFactory, user, userPass));
assertNull(unauthenticatedSession(sessionFactory, user));
} finally {
sessionFactory.close();
}
assertDeprecationWarnings(useAttribute, useLegacyBindPassword);
}
public void testUserSearchBaseScopePassesWithCorrectBaseDN() throws Exception {
String groupSearchBase = "o=sevenSeas";
String userSearchBase = "cn=William Bush,ou=people,o=sevenSeas";
Settings.Builder builder = Settings.builder()
.put(buildLdapSettings(ldapUrls(), Strings.EMPTY_ARRAY, groupSearchBase, LdapSearchScope.SUB_TREE))
.put("user_search.base_dn", userSearchBase)
.put("bind_dn", "cn=Horatio Hornblower,ou=people,o=sevenSeas")
.put("user_search.scope", LdapSearchScope.BASE)
.put("user_search.pool.enabled", randomBoolean());
final boolean useLegacyBindPassword = configureBindPassword(builder);
final boolean useAttribute = randomBoolean();
if (useAttribute) {
builder.put("user_search.attribute", "cn");
} else {
builder.put("user_search.filter", "(cn={0})");
}
RealmConfig config = new RealmConfig("ldap_realm", builder.build(), globalSettings, TestEnvironment.newEnvironment(globalSettings),
new ThreadContext(globalSettings));
LdapUserSearchSessionFactory sessionFactory = getLdapUserSearchSessionFactory(config, sslService, threadPool);
String user = "William Bush";
SecureString userPass = new SecureString("pass");
try {
// auth
try (LdapSession ldap = session(sessionFactory, user, userPass)) {
assertConnectionValid(ldap.getConnection(), sessionFactory.bindCredentials);
String dn = ldap.userDn();
assertThat(dn, containsString(user));
}
//lookup
try (LdapSession ldap = unauthenticatedSession(sessionFactory, user)) {
assertConnectionValid(ldap.getConnection(), sessionFactory.bindCredentials);
String dn = ldap.userDn();
assertThat(dn, containsString(user));
}
} finally {
sessionFactory.close();
}
assertDeprecationWarnings(useAttribute, useLegacyBindPassword);
}
public void testUserSearchOneLevelScopeFailsWithWrongBaseDN() throws Exception {
String groupSearchBase = "o=sevenSeas";
String userSearchBase = "o=sevenSeas";
Settings.Builder builder = Settings.builder()
.put(buildLdapSettings(ldapUrls(), Strings.EMPTY_ARRAY, groupSearchBase, LdapSearchScope.SUB_TREE))
.put("user_search.base_dn", userSearchBase)
.put("bind_dn", "cn=Horatio Hornblower,ou=people,o=sevenSeas")
.put("user_search.scope", LdapSearchScope.ONE_LEVEL)
.put("user_search.pool.enabled", randomBoolean());
final boolean useLegacyBindPassword = configureBindPassword(builder);
final boolean useAttribute = randomBoolean();
if (useAttribute) {
builder.put("user_search.attribute", "cn");
} else {
builder.put("user_search.filter", "(cn={0})");
}
RealmConfig config = new RealmConfig("ldap_realm", builder.build(), globalSettings, TestEnvironment.newEnvironment(globalSettings),
new ThreadContext(globalSettings));
LdapUserSearchSessionFactory sessionFactory = getLdapUserSearchSessionFactory(config, sslService, threadPool);
String user = "William Bush";
SecureString userPass = new SecureString("pass");
try {
assertNull(session(sessionFactory, user, userPass));
assertNull(unauthenticatedSession(sessionFactory, user));
} finally {
sessionFactory.close();
}
assertDeprecationWarnings(useAttribute, useLegacyBindPassword);
}
public void testUserSearchOneLevelScopePassesWithCorrectBaseDN() throws Exception {
String groupSearchBase = "o=sevenSeas";
String userSearchBase = "ou=people,o=sevenSeas";
Settings.Builder builder = Settings.builder()
.put(buildLdapSettings(ldapUrls(), Strings.EMPTY_ARRAY, groupSearchBase, LdapSearchScope.SUB_TREE))
.put("user_search.base_dn", userSearchBase)
.put("bind_dn", "cn=Horatio Hornblower,ou=people,o=sevenSeas")
.put("user_search.scope", LdapSearchScope.ONE_LEVEL)
.put("user_search.pool.enabled", randomBoolean());
final boolean useLegacyBindPassword = configureBindPassword(builder);
final boolean useAttribute = randomBoolean();
if (useAttribute) {
builder.put("user_search.attribute", "cn");
} else {
builder.put("user_search.filter", "(cn={0})");
}
RealmConfig config = new RealmConfig("ldap_realm", builder.build(), globalSettings, TestEnvironment.newEnvironment(globalSettings),
new ThreadContext(globalSettings));
LdapUserSearchSessionFactory sessionFactory = getLdapUserSearchSessionFactory(config, sslService, threadPool);
String user = "William Bush";
SecureString userPass = new SecureString("pass");
try {
//auth
try (LdapSession ldap = session(sessionFactory, user, userPass)) {
assertConnectionValid(ldap.getConnection(), sessionFactory.bindCredentials);
String dn = ldap.userDn();
assertThat(dn, containsString(user));
}
//lookup
try (LdapSession ldap = unauthenticatedSession(sessionFactory, user)) {
assertConnectionValid(ldap.getConnection(), sessionFactory.bindCredentials);
String dn = ldap.userDn();
assertThat(dn, containsString(user));
}
} finally {
sessionFactory.close();
}
assertDeprecationWarnings(useAttribute, useLegacyBindPassword);
}
public void testUserSearchWithBadAttributeFails() throws Exception {
String groupSearchBase = "o=sevenSeas";
String userSearchBase = "o=sevenSeas";
Settings.Builder builder = Settings.builder()
.put(buildLdapSettings(ldapUrls(), Strings.EMPTY_ARRAY, groupSearchBase, LdapSearchScope.SUB_TREE))
.put("user_search.base_dn", userSearchBase)
.put("bind_dn", "cn=Horatio Hornblower,ou=people,o=sevenSeas")
.put("user_search.pool.enabled", randomBoolean());
final boolean useLegacyBindPassword = configureBindPassword(builder);
final boolean useAttribute = randomBoolean();
if (useAttribute) {
builder.put("user_search.attribute", "uid1");
} else {
builder.put("user_search.filter", "(uid1={0})");
}
RealmConfig config = new RealmConfig("ldap_realm", builder.build(), globalSettings, TestEnvironment.newEnvironment(globalSettings),
new ThreadContext(globalSettings));
LdapUserSearchSessionFactory sessionFactory = getLdapUserSearchSessionFactory(config, sslService, threadPool);
String user = "William Bush";
SecureString userPass = new SecureString("pass");
try {
assertNull(session(sessionFactory, user, userPass));
assertNull(unauthenticatedSession(sessionFactory, user));
} finally {
sessionFactory.close();
}
assertDeprecationWarnings(useAttribute, useLegacyBindPassword);
}
public void testUserSearchWithoutAttributePasses() throws Exception {
String groupSearchBase = "o=sevenSeas";
String userSearchBase = "o=sevenSeas";
final Settings.Builder realmSettings = Settings.builder()
.put(buildLdapSettings(ldapUrls(), Strings.EMPTY_ARRAY, groupSearchBase, LdapSearchScope.SUB_TREE))
.put("user_search.base_dn", userSearchBase)
.put("bind_dn", "cn=Horatio Hornblower,ou=people,o=sevenSeas")
.put("user_search.pool.enabled", randomBoolean());
final boolean useLegacyBindPassword = configureBindPassword(realmSettings);
RealmConfig config = new RealmConfig("ldap_realm", realmSettings.build(), globalSettings,
TestEnvironment.newEnvironment(globalSettings), new ThreadContext(globalSettings));
LdapUserSearchSessionFactory sessionFactory = getLdapUserSearchSessionFactory(config, sslService, threadPool);
String user = "wbush";
SecureString userPass = new SecureString("pass");
try {
//auth
try (LdapSession ldap = session(sessionFactory, user, userPass)) {
assertConnectionValid(ldap.getConnection(), sessionFactory.bindCredentials);
String dn = ldap.userDn();
assertThat(dn, containsString("William Bush"));
}
//lookup
try (LdapSession ldap = unauthenticatedSession(sessionFactory, user)) {
assertConnectionValid(ldap.getConnection(), sessionFactory.bindCredentials);
String dn = ldap.userDn();
assertThat(dn, containsString("William Bush"));
}
} finally {
sessionFactory.close();
}
assertDeprecationWarnings(false, useLegacyBindPassword);
}
public void testConnectionPoolDefaultSettings() throws Exception {
String groupSearchBase = "o=sevenSeas";
String userSearchBase = "o=sevenSeas";
final Settings.Builder realmSettings = Settings.builder()
.put(buildLdapSettings(ldapUrls(), Strings.EMPTY_ARRAY, groupSearchBase, LdapSearchScope.SUB_TREE))
.put("user_search.base_dn", userSearchBase)
.put("bind_dn", "cn=Horatio Hornblower,ou=people,o=sevenSeas");
configureBindPassword(realmSettings);
RealmConfig config = new RealmConfig("ldap_realm", realmSettings.build(), globalSettings,
TestEnvironment.newEnvironment(globalSettings), new ThreadContext(globalSettings));
LDAPConnectionPool connectionPool = LdapUserSearchSessionFactory.createConnectionPool(config, new SingleServerSet("localhost",
randomFrom(ldapServers).getListenPort()), TimeValue.timeValueSeconds(5), NoOpLogger.INSTANCE,
new SimpleBindRequest("cn=Horatio Hornblower,ou=people,o=sevenSeas", "pass"),
() -> "cn=Horatio Hornblower,ou=people,o=sevenSeas");
try {
assertThat(connectionPool.getCurrentAvailableConnections(),
is(PoolingSessionFactorySettings.DEFAULT_CONNECTION_POOL_INITIAL_SIZE));
assertThat(connectionPool.getMaximumAvailableConnections(),
is(PoolingSessionFactorySettings.DEFAULT_CONNECTION_POOL_SIZE));
assertEquals(connectionPool.getHealthCheck().getClass(), GetEntryLDAPConnectionPoolHealthCheck.class);
GetEntryLDAPConnectionPoolHealthCheck healthCheck = (GetEntryLDAPConnectionPoolHealthCheck) connectionPool.getHealthCheck();
assertThat(healthCheck.getEntryDN(), is("cn=Horatio Hornblower,ou=people,o=sevenSeas"));
assertThat(healthCheck.getMaxResponseTimeMillis(), is(SessionFactorySettings.TIMEOUT_DEFAULT.millis()));
} finally {
connectionPool.close();
}
}
public void testConnectionPoolSettings() throws Exception {
String groupSearchBase = "o=sevenSeas";
String userSearchBase = "o=sevenSeas";
final Settings.Builder realmSettings = Settings.builder()
.put(buildLdapSettings(ldapUrls(), Strings.EMPTY_ARRAY, groupSearchBase, LdapSearchScope.SUB_TREE))
.put("user_search.base_dn", userSearchBase)
.put("bind_dn", "cn=Horatio Hornblower,ou=people,o=sevenSeas")
.put("user_search.pool.initial_size", 10)
.put("user_search.pool.size", 12)
.put("user_search.pool.health_check.enabled", false);
configureBindPassword(realmSettings);
RealmConfig config = new RealmConfig("ldap_realm", realmSettings.build(), globalSettings,
TestEnvironment.newEnvironment(globalSettings), new ThreadContext(globalSettings));
LDAPConnectionPool connectionPool = LdapUserSearchSessionFactory.createConnectionPool(config, new SingleServerSet("localhost",
randomFrom(ldapServers).getListenPort()), TimeValue.timeValueSeconds(5), NoOpLogger.INSTANCE,
new SimpleBindRequest("cn=Horatio Hornblower,ou=people,o=sevenSeas", "pass"),
() -> "cn=Horatio Hornblower,ou=people,o=sevenSeas");
try {
assertThat(connectionPool.getCurrentAvailableConnections(), is(10));
assertThat(connectionPool.getMaximumAvailableConnections(), is(12));
assertThat(connectionPool.retryFailedOperationsDueToInvalidConnections(), is(true));
assertEquals(connectionPool.getHealthCheck().getClass(), LDAPConnectionPoolHealthCheck.class);
} finally {
connectionPool.close();
}
}
public void testThatEmptyBindDNWithHealthCheckEnabledDoesNotThrow() throws Exception {
String groupSearchBase = "o=sevenSeas";
String userSearchBase = "o=sevenSeas";
RealmConfig config = new RealmConfig("ldap_realm", Settings.builder()
.put(buildLdapSettings(ldapUrls(), Strings.EMPTY_ARRAY, groupSearchBase, LdapSearchScope.SUB_TREE))
.put("user_search.base_dn", userSearchBase)
.put("bind_password", "pass")
.build(), globalSettings, TestEnvironment.newEnvironment(globalSettings), new ThreadContext(globalSettings));
LdapUserSearchSessionFactory searchSessionFactory = null;
try {
searchSessionFactory = getLdapUserSearchSessionFactory(config, sslService, threadPool);
} finally {
if (searchSessionFactory != null) {
searchSessionFactory.close();
}
}
assertDeprecationWarnings(false, true);
}
public void testThatEmptyBindDNAndDisabledPoolingDoesNotThrow() throws Exception {
String groupSearchBase = "o=sevenSeas";
String userSearchBase = "o=sevenSeas";
RealmConfig config = new RealmConfig("ldap_realm", Settings.builder()
.put(buildLdapSettings(ldapUrls(), Strings.EMPTY_ARRAY, groupSearchBase, LdapSearchScope.SUB_TREE))
.put("user_search.base_dn", userSearchBase)
.put("user_search.pool.enabled", false)
.put("bind_password", "pass")
.build(), globalSettings, TestEnvironment.newEnvironment(globalSettings), new ThreadContext(globalSettings));
LdapUserSearchSessionFactory searchSessionFactory = null;
try {
searchSessionFactory = getLdapUserSearchSessionFactory(config, sslService, threadPool);
final PlainActionFuture<LdapSession> future = new PlainActionFuture<>();
searchSessionFactory.session("cn=ironman", new SecureString("password".toCharArray()), future);
future.get();
} finally {
if (searchSessionFactory != null) {
searchSessionFactory.close();
}
}
assertDeprecationWarnings(false, true);
}
public void testEmptyBindDNReturnsAnonymousBindRequest() throws LDAPException {
String groupSearchBase = "o=sevenSeas";
String userSearchBase = "o=sevenSeas";
final Settings.Builder realmSettings = Settings.builder()
.put(buildLdapSettings(ldapUrls(), Strings.EMPTY_ARRAY, groupSearchBase, LdapSearchScope.SUB_TREE))
.put("user_search.base_dn", userSearchBase);
final boolean useLegacyBindPassword = configureBindPassword(realmSettings);
RealmConfig config = new RealmConfig("ldap_realm", realmSettings.build(), globalSettings,
TestEnvironment.newEnvironment(globalSettings), new ThreadContext(globalSettings));
try (LdapUserSearchSessionFactory searchSessionFactory = getLdapUserSearchSessionFactory(config, sslService, threadPool)) {
assertThat(searchSessionFactory.bindCredentials, notNullValue());
assertThat(searchSessionFactory.bindCredentials.getBindDN(), isEmptyString());
}
assertDeprecationWarnings(false, useLegacyBindPassword);
}
public void testThatBindRequestReturnsSimpleBindRequest() throws LDAPException {
String groupSearchBase = "o=sevenSeas";
String userSearchBase = "o=sevenSeas";
final Settings.Builder realmSettings = Settings.builder()
.put(buildLdapSettings(ldapUrls(), Strings.EMPTY_ARRAY, groupSearchBase, LdapSearchScope.SUB_TREE))
.put("bind_dn", "cn=ironman")
.put("user_search.base_dn", userSearchBase);
final boolean useLegacyBindPassword = configureBindPassword(realmSettings);
RealmConfig config = new RealmConfig("ldap_realm", realmSettings.build(), globalSettings,
TestEnvironment.newEnvironment(globalSettings), new ThreadContext(globalSettings));
try (LdapUserSearchSessionFactory searchSessionFactory = getLdapUserSearchSessionFactory(config, sslService, threadPool)) {
assertThat(searchSessionFactory.bindCredentials, notNullValue());
assertThat(searchSessionFactory.bindCredentials.getBindDN(), is("cn=ironman"));
}
assertDeprecationWarnings(false, useLegacyBindPassword);
}
public void testThatConnectErrorIsNotThrownOnConstruction() throws Exception {
String groupSearchBase = "DC=ad,DC=test,DC=elasticsearch,DC=com";
String userSearchBase = "CN=Users,DC=ad,DC=test,DC=elasticsearch,DC=com";
// pick a random ldap server and stop it
InMemoryDirectoryServer inMemoryDirectoryServer = randomFrom(ldapServers);
String ldapUrl = new LDAPURL("ldap", "localhost", inMemoryDirectoryServer.getListenPort(), null, null, null, null).toString();
inMemoryDirectoryServer.shutDown(true);
final Settings.Builder ldapSettingsBuilder = Settings.builder()
.put(LdapTestCase.buildLdapSettings(new String[]{ldapUrl}, Strings.EMPTY_ARRAY,
groupSearchBase, LdapSearchScope.SUB_TREE))
.put("user_search.base_dn", userSearchBase)
.put("bind_dn", "ironman@ad.test.elasticsearch.com")
.put("user_search.attribute", "cn")
.put("timeout.tcp_connect", "500ms")
.put("type", "ldap")
.put("user_search.pool.health_check.enabled", false)
.put("user_search.pool.enabled", randomBoolean());
final boolean useLegacyBindPassword = configureBindPassword(ldapSettingsBuilder);
RealmConfig config = new RealmConfig("ldap_realm", ldapSettingsBuilder.build(), globalSettings,
TestEnvironment.newEnvironment(globalSettings), new ThreadContext(globalSettings));
LdapUserSearchSessionFactory searchSessionFactory = null;
try {
searchSessionFactory = getLdapUserSearchSessionFactory(config, sslService, threadPool);
} finally {
if (searchSessionFactory != null) {
searchSessionFactory.close();
}
}
assertDeprecationWarnings(true, useLegacyBindPassword);
}
private void assertDeprecationWarnings(boolean useAttribute, boolean legacyBindPassword) {
List<Setting<?>> deprecatedSettings = new ArrayList<>();
if (useAttribute) {
deprecatedSettings.add(LdapUserSearchSessionFactorySettings.SEARCH_ATTRIBUTE);
}
if (legacyBindPassword) {
deprecatedSettings.add(PoolingSessionFactorySettings.LEGACY_BIND_PASSWORD);
}
if (deprecatedSettings.size() > 0) {
assertSettingDeprecationsAndWarnings(deprecatedSettings.toArray(new Setting<?>[deprecatedSettings.size()]));
}
}
private boolean configureBindPassword(Settings.Builder builder) {
final boolean useLegacyBindPassword = randomBoolean();
if (useLegacyBindPassword) {
builder.put("bind_password", "pass");
} else {
builder.setSecureSettings(newSecureSettings("secure_bind_password", "pass"));
}
return useLegacyBindPassword;
}
static LdapUserSearchSessionFactory getLdapUserSearchSessionFactory(RealmConfig config, SSLService sslService, ThreadPool threadPool)
throws LDAPException {
LdapUserSearchSessionFactory sessionFactory = new LdapUserSearchSessionFactory(config, sslService, threadPool);
if (sessionFactory.getConnectionPool() != null) {
// don't use this in production
// used here to catch bugs that might get masked by an automatic retry
sessionFactory.getConnectionPool().setRetryFailedOperationsDueToInvalidConnections(false);
}
return sessionFactory;
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.security.token.delegation.web;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.authentication.client.AuthenticationException;
import org.apache.hadoop.security.authentication.client.KerberosAuthenticator;
import org.apache.hadoop.security.authentication.server.AuthenticationHandler;
import org.apache.hadoop.security.authentication.server.AuthenticationToken;
import org.apache.hadoop.security.token.SecretManager;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.util.HttpExceptionUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Map;
import java.util.Properties;
public class TestDelegationTokenAuthenticationHandlerWithMocks {
public static class MockDelegationTokenAuthenticationHandler
extends DelegationTokenAuthenticationHandler {
public MockDelegationTokenAuthenticationHandler() {
super(new AuthenticationHandler() {
@Override
public String getType() {
return "T";
}
@Override
public void init(Properties config) throws ServletException {
}
@Override
public void destroy() {
}
@Override
public boolean managementOperation(AuthenticationToken token,
HttpServletRequest request, HttpServletResponse response)
throws IOException, AuthenticationException {
return false;
}
@Override
public AuthenticationToken authenticate(HttpServletRequest request,
HttpServletResponse response)
throws IOException, AuthenticationException {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, "mock");
return null;
}
});
}
}
private DelegationTokenAuthenticationHandler handler;
@Before
public void setUp() throws Exception {
Properties conf = new Properties();
conf.put(KerberosDelegationTokenAuthenticationHandler.TOKEN_KIND, "foo");
handler = new MockDelegationTokenAuthenticationHandler();
handler.initTokenManager(conf);
}
@After
public void cleanUp() {
handler.destroy();
}
@Test
public void testManagementOperations() throws Exception {
testNonManagementOperation();
testManagementOperationErrors();
testGetToken(null, new Text("foo"));
testGetToken("bar", new Text("foo"));
testCancelToken();
testRenewToken();
}
private void testNonManagementOperation() throws Exception {
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(request.getParameter(
DelegationTokenAuthenticator.OP_PARAM)).thenReturn(null);
Assert.assertTrue(handler.managementOperation(null, request, null));
Mockito.when(request.getParameter(
DelegationTokenAuthenticator.OP_PARAM)).thenReturn("CREATE");
Assert.assertTrue(handler.managementOperation(null, request, null));
}
private void testManagementOperationErrors() throws Exception {
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
Mockito.when(request.getQueryString()).thenReturn(
DelegationTokenAuthenticator.OP_PARAM + "=" +
DelegationTokenAuthenticator.DelegationTokenOperation.
GETDELEGATIONTOKEN.toString()
);
Mockito.when(request.getMethod()).thenReturn("FOO");
Assert.assertFalse(handler.managementOperation(null, request, response));
Mockito.verify(response).sendError(
Mockito.eq(HttpServletResponse.SC_BAD_REQUEST),
Mockito.startsWith("Wrong HTTP method"));
Mockito.reset(response);
Mockito.when(request.getMethod()).thenReturn(
DelegationTokenAuthenticator.DelegationTokenOperation.
GETDELEGATIONTOKEN.getHttpMethod()
);
Assert.assertFalse(handler.managementOperation(null, request, response));
Mockito.verify(response).setStatus(
Mockito.eq(HttpServletResponse.SC_UNAUTHORIZED));
Mockito.verify(response).setHeader(
Mockito.eq(KerberosAuthenticator.WWW_AUTHENTICATE),
Mockito.eq("mock"));
}
private void testGetToken(String renewer, Text expectedTokenKind)
throws Exception {
DelegationTokenAuthenticator.DelegationTokenOperation op =
DelegationTokenAuthenticator.DelegationTokenOperation.
GETDELEGATIONTOKEN;
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
Mockito.when(request.getQueryString()).
thenReturn(DelegationTokenAuthenticator.OP_PARAM + "=" + op.toString());
Mockito.when(request.getMethod()).thenReturn(op.getHttpMethod());
AuthenticationToken token = Mockito.mock(AuthenticationToken.class);
Mockito.when(token.getUserName()).thenReturn("user");
Mockito.when(response.getWriter()).thenReturn(new PrintWriter(
new StringWriter()));
Assert.assertFalse(handler.managementOperation(token, request, response));
Mockito.when(request.getQueryString()).
thenReturn(DelegationTokenAuthenticator.OP_PARAM + "=" + op.toString() +
"&" + DelegationTokenAuthenticator.RENEWER_PARAM + "=" + renewer);
Mockito.reset(response);
Mockito.reset(token);
Mockito.when(token.getUserName()).thenReturn("user");
StringWriter writer = new StringWriter();
PrintWriter pwriter = new PrintWriter(writer);
Mockito.when(response.getWriter()).thenReturn(pwriter);
Assert.assertFalse(handler.managementOperation(token, request, response));
if (renewer == null) {
Mockito.verify(token).getUserName();
} else {
Mockito.verify(token).getUserName();
}
Mockito.verify(response).setStatus(HttpServletResponse.SC_OK);
Mockito.verify(response).setContentType(MediaType.APPLICATION_JSON);
pwriter.close();
String responseOutput = writer.toString();
String tokenLabel = DelegationTokenAuthenticator.
DELEGATION_TOKEN_JSON;
Assert.assertTrue(responseOutput.contains(tokenLabel));
Assert.assertTrue(responseOutput.contains(
DelegationTokenAuthenticator.DELEGATION_TOKEN_URL_STRING_JSON));
ObjectMapper jsonMapper = new ObjectMapper();
Map json = jsonMapper.readValue(responseOutput, Map.class);
json = (Map) json.get(tokenLabel);
String tokenStr;
tokenStr = (String) json.get(DelegationTokenAuthenticator.
DELEGATION_TOKEN_URL_STRING_JSON);
Token<DelegationTokenIdentifier> dt = new Token<DelegationTokenIdentifier>();
dt.decodeFromUrlString(tokenStr);
handler.getTokenManager().verifyToken(dt);
Assert.assertEquals(expectedTokenKind, dt.getKind());
}
@SuppressWarnings("unchecked")
private void testCancelToken() throws Exception {
DelegationTokenAuthenticator.DelegationTokenOperation op =
DelegationTokenAuthenticator.DelegationTokenOperation.
CANCELDELEGATIONTOKEN;
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
Mockito.when(request.getQueryString()).thenReturn(
DelegationTokenAuthenticator.OP_PARAM + "=" + op.toString());
Mockito.when(request.getMethod()).
thenReturn(op.getHttpMethod());
Assert.assertFalse(handler.managementOperation(null, request, response));
Mockito.verify(response).sendError(
Mockito.eq(HttpServletResponse.SC_BAD_REQUEST),
Mockito.contains("requires the parameter [token]"));
Mockito.reset(response);
Token<DelegationTokenIdentifier> token =
(Token<DelegationTokenIdentifier>) handler.getTokenManager().createToken(
UserGroupInformation.getCurrentUser(), "foo");
Mockito.when(request.getQueryString()).thenReturn(
DelegationTokenAuthenticator.OP_PARAM + "=" + op.toString() + "&" +
DelegationTokenAuthenticator.TOKEN_PARAM + "=" +
token.encodeToUrlString()
);
Assert.assertFalse(handler.managementOperation(null, request, response));
Mockito.verify(response).setStatus(HttpServletResponse.SC_OK);
try {
handler.getTokenManager().verifyToken(token);
Assert.fail();
} catch (SecretManager.InvalidToken ex) {
//NOP
} catch (Throwable ex) {
Assert.fail();
}
}
@SuppressWarnings("unchecked")
private void testRenewToken() throws Exception {
DelegationTokenAuthenticator.DelegationTokenOperation op =
DelegationTokenAuthenticator.DelegationTokenOperation.
RENEWDELEGATIONTOKEN;
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
Mockito.when(request.getQueryString()).
thenReturn(DelegationTokenAuthenticator.OP_PARAM + "=" + op.toString());
Mockito.when(request.getMethod()).
thenReturn(op.getHttpMethod());
Assert.assertFalse(handler.managementOperation(null, request, response));
Mockito.verify(response).setStatus(
Mockito.eq(HttpServletResponse.SC_UNAUTHORIZED));
Mockito.verify(response).setHeader(Mockito.eq(
KerberosAuthenticator.WWW_AUTHENTICATE),
Mockito.eq("mock")
);
Mockito.reset(response);
AuthenticationToken token = Mockito.mock(AuthenticationToken.class);
Mockito.when(token.getUserName()).thenReturn("user");
Assert.assertFalse(handler.managementOperation(token, request, response));
Mockito.verify(response).sendError(
Mockito.eq(HttpServletResponse.SC_BAD_REQUEST),
Mockito.contains("requires the parameter [token]"));
Mockito.reset(response);
StringWriter writer = new StringWriter();
PrintWriter pwriter = new PrintWriter(writer);
Mockito.when(response.getWriter()).thenReturn(pwriter);
Token<DelegationTokenIdentifier> dToken =
(Token<DelegationTokenIdentifier>) handler.getTokenManager().createToken(
UserGroupInformation.getCurrentUser(), "user");
Mockito.when(request.getQueryString()).
thenReturn(DelegationTokenAuthenticator.OP_PARAM + "=" + op.toString() +
"&" + DelegationTokenAuthenticator.TOKEN_PARAM + "=" +
dToken.encodeToUrlString());
Assert.assertFalse(handler.managementOperation(token, request, response));
Mockito.verify(response).setStatus(HttpServletResponse.SC_OK);
pwriter.close();
Assert.assertTrue(writer.toString().contains("long"));
handler.getTokenManager().verifyToken(dToken);
}
@Test
public void testAuthenticate() throws Exception {
testValidDelegationTokenQueryString();
testValidDelegationTokenHeader();
testInvalidDelegationTokenQueryString();
testInvalidDelegationTokenHeader();
}
@SuppressWarnings("unchecked")
private void testValidDelegationTokenQueryString() throws Exception {
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
Token<DelegationTokenIdentifier> dToken =
(Token<DelegationTokenIdentifier>) handler.getTokenManager().createToken(
UserGroupInformation.getCurrentUser(), "user");
Mockito.when(request.getQueryString()).thenReturn(
DelegationTokenAuthenticator.DELEGATION_PARAM + "=" +
dToken.encodeToUrlString());
AuthenticationToken token = handler.authenticate(request, response);
Assert.assertEquals(UserGroupInformation.getCurrentUser().
getShortUserName(), token.getUserName());
Assert.assertEquals(0, token.getExpires());
Assert.assertEquals(handler.getType(),
token.getType());
Assert.assertTrue(token.isExpired());
}
@SuppressWarnings("unchecked")
private void testValidDelegationTokenHeader() throws Exception {
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
Token<DelegationTokenIdentifier> dToken =
(Token<DelegationTokenIdentifier>) handler.getTokenManager().createToken(
UserGroupInformation.getCurrentUser(), "user");
Mockito.when(request.getHeader(Mockito.eq(
DelegationTokenAuthenticator.DELEGATION_TOKEN_HEADER))).thenReturn(
dToken.encodeToUrlString());
AuthenticationToken token = handler.authenticate(request, response);
Assert.assertEquals(UserGroupInformation.getCurrentUser().
getShortUserName(), token.getUserName());
Assert.assertEquals(0, token.getExpires());
Assert.assertEquals(handler.getType(),
token.getType());
Assert.assertTrue(token.isExpired());
}
private void testInvalidDelegationTokenQueryString() throws Exception {
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
Mockito.when(request.getQueryString()).thenReturn(
DelegationTokenAuthenticator.DELEGATION_PARAM + "=invalid");
StringWriter writer = new StringWriter();
Mockito.when(response.getWriter()).thenReturn(new PrintWriter(writer));
Assert.assertNull(handler.authenticate(request, response));
Mockito.verify(response).setStatus(HttpServletResponse.SC_FORBIDDEN);
Assert.assertTrue(writer.toString().contains("AuthenticationException"));
}
private void testInvalidDelegationTokenHeader() throws Exception {
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
Mockito.when(request.getHeader(Mockito.eq(
DelegationTokenAuthenticator.DELEGATION_TOKEN_HEADER))).thenReturn(
"invalid");
StringWriter writer = new StringWriter();
Mockito.when(response.getWriter()).thenReturn(new PrintWriter(writer));
Assert.assertNull(handler.authenticate(request, response));
Assert.assertTrue(writer.toString().contains("AuthenticationException"));
}
}
| |
import ij.*;
import ij.IJ;
import ij.gui.DialogListener;
import ij.gui.GenericDialog;
import static ij.plugin.filter.ExtendedPlugInFilter.KEEP_PREVIEW;
import static ij.plugin.filter.PlugInFilter.DOES_16;
import static ij.plugin.filter.PlugInFilter.DOES_32;
import static ij.plugin.filter.PlugInFilter.DOES_8G;
import static ij.plugin.filter.PlugInFilter.DONE;
import ij.plugin.filter.PlugInFilterRunner;
import ij.process.ImageProcessor;
import java.awt.AWTEvent;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.imgproc.Imgproc;
/*
* The MIT License
*
* Copyright 2016 Takehito Nishida.
*
* 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.
*/
/**
* Sobel (OpenCV4.5.3).
*/
public class OCV_Sobel implements ij.plugin.filter.ExtendedPlugInFilter, DialogListener
{
// constant var.
private static final int FLAGS = DOES_8G | DOES_16 | DOES_32 | KEEP_PREVIEW;
private static final int[] INT_KSIZE = { 1, 3, 5, 7};
private static final String[] STR_KSIZE = { "1" , "3", "5", "7" };
/*
Various border types, image boundaries are denoted with '|'
* BORDER_CONSTANT: iiiiii|abcdefgh|iiiiiii with some specified i
* BORDER_REPLICATE: aaaaaa|abcdefgh|hhhhhhh
* BORDER_REFLECT: fedcba|abcdefgh|hgfedcb
* BORDER_REFLECT_101: gfedcb|abcdefgh|gfedcba
* BORDER_WRAP: cdefgh|abcdefgh|abcdefg (Error occurred)
* BORDER_TRANSPARENT: uvwxyz|abcdefgh|ijklmno (Error occurred)
* BORDER_ISOLATED: do not look outside of ROI
*/
private static final int[] INT_BORDERTYPE = { Core.BORDER_CONSTANT, Core.BORDER_REPLICATE, Core.BORDER_REFLECT, Core.BORDER_REFLECT101, /*Core.BORDER_WRAP, Core.BORDER_TRANSPARENT,*/ Core.BORDER_ISOLATED };
private static final String[] STR_BORDERTYPE = { "BORDER_CONSTANT", "BORDER_REPLICATE", "BORDER_REFLECT", "BORDER_REFLECT101", /*"BORDER_WRAP", "BORDER_TRANSPARENT",*/ "BORDER_ISOLATED" };
// staic var.
private static int dx = 1; // order of the derivative x.
private static int dy = 1; // order of the derivative y.
private static int indKsize = 1; // size of the extended Sobel kernel; it must be 1, 3, 5, or 7.
private static double scale = 1; // optional scale factor for the computed derivative values.
private static double delta = 0; // optional delta value that is added to the results prior to storing them in dst.
private static int indBorderType = 2; // border type
@Override
public int showDialog(ImagePlus imp, String command, PlugInFilterRunner pfr)
{
GenericDialog gd = new GenericDialog(command.trim() + " ...");
gd.addNumericField("dx", dx, 0);
gd.addNumericField("dy", dy, 0);
gd.addChoice("ksize", STR_KSIZE, STR_KSIZE[indKsize]);
gd.addNumericField("scale", scale, 4);
gd.addNumericField("delta", delta, 4);
gd.addChoice("borderType", STR_BORDERTYPE, STR_BORDERTYPE[indBorderType]);
gd.addPreviewCheckbox(pfr);
gd.addDialogListener(this);
gd.showDialog();
if (gd.wasCanceled())
{
return DONE;
}
else
{
return IJ.setupDialog(imp, FLAGS);
}
}
@Override
public boolean dialogItemChanged(GenericDialog gd, AWTEvent awte)
{
dx = (int)gd.getNextNumber();
dy = (int)gd.getNextNumber();
indKsize = (int)gd.getNextChoiceIndex();
scale = (double)gd.getNextNumber();
delta = (double)gd.getNextNumber();
indBorderType = (int)gd.getNextChoiceIndex();
if(dx < 0) { IJ.showStatus("'0 <= dx' is necessary."); return false; }
if(dy < 0) { IJ.showStatus("'0 <= dy' is necessary."); return false; }
if(dx <= 0 && dy <= 0) { IJ.showStatus("Either dx or dy is greater than zero."); return false; }
if(Double.isNaN(scale) || Double.isNaN(delta)) { IJ.showStatus("ERR : NaN"); return false; }
IJ.showStatus("OCV_Sobel");
return true;
}
@Override
public void setNPasses(int nPasses)
{
// do nothing
}
@Override
public int setup(String arg, ImagePlus imp)
{
if(!OCV__LoadLibrary.isLoad())
{
IJ.error("Library is not loaded.");
return DONE;
}
if (imp == null)
{
IJ.noImage();
return DONE;
}
else
{
return FLAGS;
}
}
@Override
public void run(ImageProcessor ip)
{
if(ip.getBitDepth() == 8)
{
// srcdst
int imw = ip.getWidth();
int imh = ip.getHeight();
byte[] srcdst_bytes = (byte[])ip.getPixels();
// mat
Mat src_mat = new Mat(imh, imw, CvType.CV_8UC1);
Mat dst_mat = new Mat(imh, imw, CvType.CV_8UC1);
// run
src_mat.put(0, 0, srcdst_bytes);
Imgproc.Sobel(src_mat, dst_mat, src_mat.depth(), dx, dy, INT_KSIZE[indKsize], scale, delta, INT_BORDERTYPE[indBorderType]);
dst_mat.get(0, 0, srcdst_bytes);
}
else if(ip.getBitDepth() == 16)
{
// srcdst
int imw = ip.getWidth();
int imh = ip.getHeight();
short[] srcdst_shorts = (short[])ip.getPixels();
// mat
Mat src_mat = new Mat(imh, imw, CvType.CV_16S);
Mat dst_mat = new Mat(imh, imw, CvType.CV_16S);
// run
src_mat.put(0, 0, srcdst_shorts);
Imgproc.Sobel(src_mat, dst_mat, src_mat.depth(), dx, dy, INT_KSIZE[indKsize], scale, delta, INT_BORDERTYPE[indBorderType]);
dst_mat.get(0, 0, srcdst_shorts);
}
else if(ip.getBitDepth() == 32)
{
// srcdst
int imw = ip.getWidth();
int imh = ip.getHeight();
float[] srcdst_floats = (float[])ip.getPixels();
// mat
Mat src_mat = new Mat(imh, imw, CvType.CV_32F);
Mat dst_mat = new Mat(imh, imw, CvType.CV_32F);
// run
src_mat.put(0, 0, srcdst_floats);
Imgproc.Sobel(src_mat, dst_mat, src_mat.depth(), dx, dy, INT_KSIZE[indKsize], scale, delta, INT_BORDERTYPE[indBorderType]);
dst_mat.get(0, 0, srcdst_floats);
}
else
{
IJ.error("Wrong image format");
}
}
}
| |
/*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available 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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
package org.nd4j.linalg.dataset;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.nd4j.linalg.dataset.api.DataSetPreProcessor;
import org.nd4j.linalg.dataset.api.iterator.DataSetIterator;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.indexing.NDArrayIndex;
import org.nd4j.common.util.ND4JFileUtils;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* Mini batch file datasetiterator
* auto partitions a dataset in to mini batches
*/
@Slf4j
public class MiniBatchFileDataSetIterator implements DataSetIterator {
private int batchSize;
private List<String[]> paths;
private int currIdx;
private File rootDir;
private int totalExamples;
private int totalLabels;
private int totalBatches = -1;
private DataSetPreProcessor dataSetPreProcessor;
/**
*
* @param baseData the base dataset
* @param batchSize the batch size to split by
* @throws IOException
*/
public MiniBatchFileDataSetIterator(DataSet baseData, int batchSize) throws IOException {
this(baseData, batchSize, true);
}
/**
*
* @param baseData the base dataset
* @param batchSize the batch size to split by
* @throws IOException
*/
public MiniBatchFileDataSetIterator(DataSet baseData, int batchSize, boolean delete, File rootDir)
throws IOException {
if (baseData.numExamples() < batchSize)
throw new IllegalAccessError("Number of examples smaller than batch size");
this.batchSize = batchSize;
this.rootDir = new File(rootDir, UUID.randomUUID().toString());
this.rootDir.mkdirs();
if (delete)
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
try {
FileUtils.deleteDirectory(MiniBatchFileDataSetIterator.this.rootDir);
} catch (IOException e) {
log.error("",e);
}
}
}));
currIdx = 0;
paths = new ArrayList<>();
totalExamples = baseData.numExamples();
totalLabels = baseData.numOutcomes();
int offset = 0;
totalBatches = baseData.numExamples() / batchSize;
for (int i = 0; i < baseData.numExamples() / batchSize; i++) {
paths.add(writeData(new DataSet(
baseData.getFeatures().get(NDArrayIndex.interval(offset, offset + batchSize)),
baseData.getLabels().get(NDArrayIndex.interval(offset, offset + batchSize)))));
offset += batchSize;
if (offset >= totalExamples)
break;
}
}
/**
*
* @param baseData the base dataset
* @param batchSize the batch size to split by
* @throws IOException
*/
public MiniBatchFileDataSetIterator(DataSet baseData, int batchSize, boolean delete) throws IOException {
this(baseData, batchSize, delete, ND4JFileUtils.getTempDir());
}
@Override
public DataSet next(int num) {
throw new UnsupportedOperationException("Unable to load custom number of examples");
}
@Override
public int inputColumns() {
return 0;
}
@Override
public int totalOutcomes() {
return totalLabels;
}
@Override
public boolean resetSupported() {
return true;
}
@Override
public boolean asyncSupported() {
return true;
}
@Override
public void reset() {
currIdx = 0;
}
@Override
public int batch() {
return batchSize;
}
@Override
public void setPreProcessor(DataSetPreProcessor preProcessor) {
this.dataSetPreProcessor = preProcessor;
}
@Override
public DataSetPreProcessor getPreProcessor() {
return dataSetPreProcessor;
}
@Override
public List<String> getLabels() {
return null;
}
@Override
public boolean hasNext() {
return currIdx < totalBatches;
}
@Override
public void remove() {
//no opt;
}
@Override
public DataSet next() {
try {
DataSet ret = read(currIdx);
if (dataSetPreProcessor != null)
dataSetPreProcessor.preProcess(ret);
currIdx++;
return ret;
} catch (IOException e) {
throw new IllegalStateException("Unable to read dataset");
}
}
private DataSet read(int idx) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(paths.get(idx)[0]));
DataInputStream dis = new DataInputStream(bis);
BufferedInputStream labelInputStream = new BufferedInputStream(new FileInputStream(paths.get(idx)[1]));
DataInputStream labelDis = new DataInputStream(labelInputStream);
DataSet d = new DataSet(Nd4j.read(dis), Nd4j.read(labelDis));
dis.close();
labelDis.close();
return d;
}
private String[] writeData(DataSet write) throws IOException {
String[] ret = new String[2];
String dataSetId = UUID.randomUUID().toString();
BufferedOutputStream dataOut =
new BufferedOutputStream(new FileOutputStream(new File(rootDir, dataSetId + ".bin")));
DataOutputStream dos = new DataOutputStream(dataOut);
Nd4j.write(write.getFeatures(), dos);
dos.flush();
dos.close();
BufferedOutputStream dataOutLabels =
new BufferedOutputStream(new FileOutputStream(new File(rootDir, dataSetId + ".labels.bin")));
DataOutputStream dosLabels = new DataOutputStream(dataOutLabels);
Nd4j.write(write.getLabels(), dosLabels);
dosLabels.flush();
dosLabels.close();
ret[0] = new File(rootDir, dataSetId + ".bin").getAbsolutePath();
ret[1] = new File(rootDir, dataSetId + ".labels.bin").getAbsolutePath();
return ret;
}
public File getRootDir() {
return rootDir;
}
public void setRootDir(File rootDir) {
this.rootDir = rootDir;
}
}
| |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT;
import static com.google.common.truth.Truth.assertThat;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
/**
* Tests for {@link Multimap#putAll(Object, Iterable)}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MultimapPutIterableTester<K, V> extends AbstractMultimapTester<K, V, Multimap<K, V>> {
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(SUPPORTS_PUT)
public void testPutAllNonEmptyIterableOnPresentKey() {
assertTrue(multimap().putAll(sampleKeys().e0, new Iterable<V>() {
@Override
public Iterator<V> iterator() {
return Lists.newArrayList(sampleValues().e3, sampleValues().e4).iterator();
}
}));
assertGet(sampleKeys().e0, sampleValues().e0, sampleValues().e3, sampleValues().e4);
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(SUPPORTS_PUT)
public void testPutAllNonEmptyCollectionOnPresentKey() {
assertTrue(multimap().putAll(
sampleKeys().e0, Lists.newArrayList(sampleValues().e3, sampleValues().e4)));
assertGet(sampleKeys().e0, sampleValues().e0, sampleValues().e3, sampleValues().e4);
}
@MapFeature.Require(SUPPORTS_PUT)
public void testPutAllNonEmptyIterableOnAbsentKey() {
assertTrue(multimap().putAll(sampleKeys().e3, new Iterable<V>() {
@Override
public Iterator<V> iterator() {
return Lists.newArrayList(sampleValues().e3, sampleValues().e4).iterator();
}
}));
assertGet(sampleKeys().e3, sampleValues().e3, sampleValues().e4);
}
@MapFeature.Require(SUPPORTS_PUT)
public void testPutAllNonEmptyCollectionOnAbsentKey() {
assertTrue(multimap().putAll(
sampleKeys().e3, Lists.newArrayList(sampleValues().e3, sampleValues().e4)));
assertGet(sampleKeys().e3, sampleValues().e3, sampleValues().e4);
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES})
public void testPutAllNullValueOnPresentKey_supported() {
assertTrue(multimap().putAll(sampleKeys().e0, Lists.newArrayList(sampleValues().e3, null)));
assertGet(sampleKeys().e0, sampleValues().e0, sampleValues().e3, null);
}
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES})
public void testPutAllNullValueOnAbsentKey_supported() {
assertTrue(multimap().putAll(sampleKeys().e3, Lists.newArrayList(sampleValues().e3, null)));
assertGet(sampleKeys().e3, sampleValues().e3, null);
}
@MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_VALUES)
public void testPutAllNullValueSingle_unsupported() {
multimap().putAll(sampleKeys().e1, Lists.newArrayList((V) null));
expectUnchanged();
}
// In principle, it would be nice to apply these two tests to keys with existing values, too.
@MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_VALUES)
public void testPutAllNullValueNullLast_unsupported() {
int size = getNumElements();
try {
multimap().putAll(sampleKeys().e3, Lists.newArrayList(sampleValues().e3, null));
fail();
} catch (NullPointerException expected) {
}
Collection<V> values = multimap().get(sampleKeys().e3);
if (values.size() == 0) {
expectUnchanged();
// Be extra thorough in case internal state was corrupted by the expected null.
assertEquals(Lists.newArrayList(), Lists.newArrayList(values));
assertEquals(size, multimap().size());
} else {
assertEquals(Lists.newArrayList(sampleValues().e3), Lists.newArrayList(values));
assertEquals(size + 1, multimap().size());
}
}
@MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_VALUES)
public void testPutAllNullValueNullFirst_unsupported() {
int size = getNumElements();
try {
multimap().putAll(sampleKeys().e3, Lists.newArrayList(null, sampleValues().e3));
fail();
} catch (NullPointerException expected) {
}
/*
* In principle, a Multimap implementation could add e3 first before failing on the null. But
* that seems unlikely enough to be worth complicating the test over, especially if there's any
* chance that a permissive test could mask a bug.
*/
expectUnchanged();
// Be extra thorough in case internal state was corrupted by the expected null.
assertEquals(Lists.newArrayList(), Lists.newArrayList(multimap().get(sampleKeys().e3)));
assertEquals(size, multimap().size());
}
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_KEYS})
public void testPutAllOnPresentNullKey() {
assertTrue(multimap().putAll(null, Lists.newArrayList(sampleValues().e3, sampleValues().e4)));
assertGet(null, sampleValues().e3, sampleValues().e4);
}
@MapFeature.Require(absent = ALLOWS_NULL_KEYS)
public void testPutAllNullForbidden() {
try {
multimap().putAll(null, Collections.singletonList(sampleValues().e3));
fail("Expected NullPointerException");
} catch (NullPointerException expected) {
// success
}
}
private static final Object[] EMPTY = new Object[0];
@MapFeature.Require(SUPPORTS_PUT)
public void testPutAllEmptyCollectionOnAbsentKey() {
assertFalse(multimap().putAll(sampleKeys().e3, Collections.<V>emptyList()));
expectUnchanged();
}
@MapFeature.Require(SUPPORTS_PUT)
public void testPutAllEmptyIterableOnAbsentKey() {
Iterable<V> iterable = new Iterable<V>() {
@Override
public Iterator<V> iterator() {
return Iterators.emptyIterator();
}
};
assertFalse(multimap().putAll(sampleKeys().e3, iterable));
expectUnchanged();
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(SUPPORTS_PUT)
public void testPutAllEmptyIterableOnPresentKey() {
multimap().putAll(sampleKeys().e0, Collections.<V>emptyList());
expectUnchanged();
}
@MapFeature.Require(SUPPORTS_PUT)
public void testPutAllOnlyCallsIteratorOnce() {
Iterable<V> iterable = new Iterable<V>() {
private boolean calledIteratorAlready = false;
@Override
public Iterator<V> iterator() {
checkState(!calledIteratorAlready);
calledIteratorAlready = true;
return Iterators.forArray(sampleValues().e3);
}
};
multimap().putAll(sampleKeys().e3, iterable);
}
@MapFeature.Require(SUPPORTS_PUT)
public void testPutAllPropagatesToGet() {
Collection<V> getCollection = multimap().get(sampleKeys().e0);
int getCollectionSize = getCollection.size();
assertTrue(multimap().putAll(
sampleKeys().e0, Lists.newArrayList(sampleValues().e3, sampleValues().e4)));
assertEquals(getCollectionSize + 2, getCollection.size());
assertThat(getCollection).has().allOf(sampleValues().e3, sampleValues().e4);
}
}
| |
/*
* Copyright (c) 2010-2013 Evolveum
*
* 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.evolveum.midpoint.repo.sql.data.common;
import com.evolveum.midpoint.prism.Definition;
import com.evolveum.midpoint.prism.ItemDefinition;
import com.evolveum.midpoint.prism.PrismContext;
import com.evolveum.midpoint.prism.PrismObjectDefinition;
import com.evolveum.midpoint.repo.sql.data.common.embedded.REmbeddedReference;
import com.evolveum.midpoint.repo.sql.data.common.embedded.RPolyString;
import com.evolveum.midpoint.repo.sql.data.common.enums.RFailedOperationType;
import com.evolveum.midpoint.repo.sql.data.common.enums.ROperationResultStatus;
import com.evolveum.midpoint.repo.sql.data.common.enums.RShadowKind;
import com.evolveum.midpoint.repo.sql.data.common.enums.RSynchronizationSituation;
import com.evolveum.midpoint.repo.sql.data.common.type.RObjectExtensionType;
import com.evolveum.midpoint.repo.sql.util.DtoTranslationException;
import com.evolveum.midpoint.repo.sql.util.IdGeneratorResult;
import com.evolveum.midpoint.repo.sql.util.RUtil;
import com.evolveum.midpoint.schema.GetOperationOptions;
import com.evolveum.midpoint.schema.SelectorOptions;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType;
import org.hibernate.annotations.ForeignKey;
import org.hibernate.annotations.Index;
import javax.persistence.*;
import javax.xml.datatype.XMLGregorianCalendar;
import java.util.Collection;
/**
* @author lazyman
*/
@Entity
@Table(name = "m_shadow")
@org.hibernate.annotations.Table(appliesTo = "m_shadow",
indexes = {@Index(name = "iShadowResourceRef", columnNames = "resourceRef_targetOid"),
@Index(name = "iShadowDead", columnNames = "dead")})
@ForeignKey(name = "fk_shadow")
public class RShadow<T extends ShadowType> extends RObject<T> implements OperationResult {
private static final Trace LOGGER = TraceManager.getTrace(RShadow.class);
private RPolyString name;
private String objectClass;
//operation result
private ROperationResultStatus status;
//end of operation result
private REmbeddedReference resourceRef;
private Integer attemptNumber;
private Boolean dead;
private RFailedOperationType failedOperationType;
private String intent;
private RSynchronizationSituation synchronizationSituation;
//attributes
private XMLGregorianCalendar synchronizationTimestamp;
private RShadowKind kind;
private Boolean exists;
private XMLGregorianCalendar fullSynchronizationTimestamp;
@Column(name = "exist")
public Boolean isExists() {
return exists;
}
@Enumerated(EnumType.ORDINAL)
@Column(nullable = true)
public RShadowKind getKind() {
return kind;
}
@Column(length = RUtil.COLUMN_LENGTH_QNAME)
public String getObjectClass() {
return objectClass;
}
@Embedded
public REmbeddedReference getResourceRef() {
return resourceRef;
}
@Column(nullable = true)
public Integer getAttemptNumber() {
return attemptNumber;
}
@Enumerated(EnumType.ORDINAL)
@Column(nullable = true)
public RFailedOperationType getFailedOperationType() {
return failedOperationType;
}
@Embedded
public RPolyString getName() {
return name;
}
@Enumerated(EnumType.ORDINAL)
public RSynchronizationSituation getSynchronizationSituation() {
return synchronizationSituation;
}
public Boolean isDead() {
return dead;
}
public String getIntent() {
return intent;
}
public XMLGregorianCalendar getSynchronizationTimestamp() {
return synchronizationTimestamp;
}
public XMLGregorianCalendar getFullSynchronizationTimestamp() {
return fullSynchronizationTimestamp;
}
@Enumerated(EnumType.ORDINAL)
public ROperationResultStatus getStatus() {
return status;
}
public void setStatus(ROperationResultStatus status) {
this.status = status;
}
public void setFullSynchronizationTimestamp(XMLGregorianCalendar fullSynchronizationTimestamp) {
this.fullSynchronizationTimestamp = fullSynchronizationTimestamp;
}
public void setSynchronizationTimestamp(XMLGregorianCalendar synchronizationTimestamp) {
this.synchronizationTimestamp = synchronizationTimestamp;
}
public void setName(RPolyString name) {
this.name = name;
}
public void setAttemptNumber(Integer attemptNumber) {
this.attemptNumber = attemptNumber;
}
public void setFailedOperationType(RFailedOperationType failedOperationType) {
this.failedOperationType = failedOperationType;
}
public void setKind(RShadowKind kind) {
this.kind = kind;
}
public void setResourceRef(REmbeddedReference resourceRef) {
this.resourceRef = resourceRef;
}
public void setObjectClass(String objectClass) {
this.objectClass = objectClass;
}
public void setIntent(String intent) {
this.intent = intent;
}
public void setSynchronizationSituation(RSynchronizationSituation synchronizationSituation) {
this.synchronizationSituation = synchronizationSituation;
}
public void setDead(Boolean dead) {
this.dead = dead;
}
public void setExists(Boolean exists) {
this.exists = exists;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
RShadow that = (RShadow) o;
if (name != null ? !name.equals(that.name) : that.name != null) return false;
if (attemptNumber != null ? !attemptNumber.equals(that.attemptNumber) : that.attemptNumber != null)
return false;
if (failedOperationType != that.failedOperationType) return false;
if (objectClass != null ? !objectClass.equals(that.objectClass) : that.objectClass != null) return false;
if (resourceRef != null ? !resourceRef.equals(that.resourceRef) : that.resourceRef != null) return false;
if (intent != null ? !intent.equals(that.intent) : that.intent != null) return false;
if (synchronizationSituation != null ? !synchronizationSituation.equals(that.synchronizationSituation) : that.synchronizationSituation != null)
return false;
if (kind != null ? !kind.equals(that.kind) : that.kind != null) return false;
if (exists != null ? !exists.equals(that.exists) : that.exists != null) return false;
if (status != that.status) return false;
return true;
}
@Override
public int hashCode() {
int result1 = super.hashCode();
result1 = 31 * result1 + (name != null ? name.hashCode() : 0);
result1 = 31 * result1 + (objectClass != null ? objectClass.hashCode() : 0);
result1 = 31 * result1 + (attemptNumber != null ? attemptNumber.hashCode() : 0);
result1 = 31 * result1 + (failedOperationType != null ? failedOperationType.hashCode() : 0);
result1 = 31 * result1 + (intent != null ? intent.hashCode() : 0);
result1 = 31 * result1 + (synchronizationSituation != null ? synchronizationSituation.hashCode() : 0);
result1 = 31 * result1 + (kind != null ? kind.hashCode() : 0);
result1 = 31 * result1 + (exists != null ? exists.hashCode() : 0);
result1 = 31 * result1 + (fullSynchronizationTimestamp != null ? fullSynchronizationTimestamp.hashCode() : 0);
result1 = 31 * result1 + (status != null ? status.hashCode() : 0);
return result1;
}
public static <T extends ShadowType> void copyFromJAXB(ShadowType jaxb, RShadow<T> repo,
PrismContext prismContext, IdGeneratorResult generatorResult)
throws DtoTranslationException {
RObject.copyFromJAXB(jaxb, repo, prismContext, generatorResult);
repo.setName(RPolyString.copyFromJAXB(jaxb.getName()));
repo.setObjectClass(RUtil.qnameToString(jaxb.getObjectClass()));
repo.setIntent(jaxb.getIntent());
repo.setKind(RUtil.getRepoEnumValue(jaxb.getKind(), RShadowKind.class));
repo.setFullSynchronizationTimestamp(jaxb.getFullSynchronizationTimestamp());
ItemDefinition def = jaxb.asPrismObject().getDefinition();
RUtil.copyResultFromJAXB(def, ShadowType.F_RESULT, jaxb.getResult(), repo, prismContext);
if (jaxb.getSynchronizationSituation() != null) {
repo.setSynchronizationSituation(RUtil.getRepoEnumValue(jaxb.getSynchronizationSituation(),
RSynchronizationSituation.class));
}
repo.setSynchronizationTimestamp(jaxb.getSynchronizationTimestamp());
repo.setResourceRef(RUtil.jaxbRefToEmbeddedRepoRef(jaxb.getResourceRef(), prismContext));
repo.setAttemptNumber(jaxb.getAttemptNumber());
repo.setExists(jaxb.isExists());
repo.setDead(jaxb.isDead());
repo.setFailedOperationType(RUtil.getRepoEnumValue(jaxb.getFailedOperationType(), RFailedOperationType.class));
if (jaxb.getResource() != null) {
LOGGER.warn("Resource from resource object shadow type won't be saved. It should be " +
"translated to resource reference.");
}
if (jaxb.getAttributes() != null) {
copyFromJAXB(jaxb.getAttributes().asPrismContainerValue(), repo, prismContext, RObjectExtensionType.ATTRIBUTES);
}
}
@Override
public T toJAXB(PrismContext prismContext, Collection<SelectorOptions<GetOperationOptions>> options)
throws DtoTranslationException {
ShadowType object = new ShadowType();
RUtil.revive(object, prismContext);
RObject.copyToJAXB(this, object, prismContext, options);
return (T) object;
}
}
| |
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.extensions;
import com.intellij.psi.*;
import com.intellij.psi.util.PropertyUtil;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement;
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentLabel;
import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyPsiManager;
import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyResolveResultImpl;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil;
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames;
/**
* @author Sergey Evdokimov
*/
public class NamedArgumentDescriptor {
public static final NamedArgumentDescriptor SIMPLE_ON_TOP = new UnmodifiableDescriptor(Priority.ALWAYS_ON_TOP);
public static final NamedArgumentDescriptor SIMPLE_AS_LOCAL_VAR = new UnmodifiableDescriptor(Priority.AS_LOCAL_VARIABLE);
public static final NamedArgumentDescriptor SIMPLE_NORMAL = new UnmodifiableDescriptor(Priority.NORMAL);
public static final NamedArgumentDescriptor SIMPLE_UNLIKELY = new UnmodifiableDescriptor(Priority.UNLIKELY);
public static final StringTypeConditionWithPriority TYPE_STRING = new StringTypeConditionWithPriority(CommonClassNames.JAVA_LANG_STRING);
public static final StringTypeConditionWithPriority TYPE_CLOSURE = new StringTypeConditionWithPriority(GroovyCommonClassNames.GROOVY_LANG_CLOSURE);
public static final StringTypeConditionWithPriority TYPE_MAP = new StringTypeConditionWithPriority(CommonClassNames.JAVA_UTIL_MAP);
public static final StringTypeConditionWithPriority TYPE_LIST = new StringTypeConditionWithPriority(CommonClassNames.JAVA_UTIL_LIST);
public static final StringTypeConditionWithPriority TYPE_BOOL = new StringTypeConditionWithPriority(CommonClassNames.JAVA_LANG_BOOLEAN);
public static final StringTypeConditionWithPriority TYPE_CLASS = new StringTypeConditionWithPriority(CommonClassNames.JAVA_LANG_CLASS);
public static final StringTypeConditionWithPriority TYPE_INTEGER = new StringTypeConditionWithPriority(CommonClassNames.JAVA_LANG_INTEGER);
private final PsiElement myNavigationElement;
private final PsiSubstitutor mySubstitutor;
private Priority myPriority = Priority.ALWAYS_ON_TOP;
public NamedArgumentDescriptor() {
this(null);
}
public NamedArgumentDescriptor(@Nullable PsiElement navigationElement) {
this(navigationElement, PsiSubstitutor.EMPTY);
}
public NamedArgumentDescriptor(@Nullable PsiElement navigationElement, PsiSubstitutor substitutor) {
myNavigationElement = navigationElement;
mySubstitutor = substitutor;
}
@NotNull
public Priority getPriority() {
return myPriority;
}
public NamedArgumentDescriptor setPriority(@NotNull Priority priority) {
myPriority = priority;
return this;
}
public boolean checkType(@NotNull PsiType type, @NotNull GroovyPsiElement context) {
return true;
}
@Nullable
public PsiPolyVariantReference createReference(@NotNull GrArgumentLabel element) {
final PsiElement navigationElement = getNavigationElement();
if (navigationElement == null) return null;
return new NamedArgumentReference(element, navigationElement, mySubstitutor);
}
@Nullable
public PsiElement getNavigationElement() {
return myNavigationElement;
}
public static class NamedArgumentReference extends PsiPolyVariantReferenceBase<GrArgumentLabel> {
private final PsiElement myNavigationElement;
private final PsiSubstitutor mySubstitutor;
public NamedArgumentReference(GrArgumentLabel element, @NotNull PsiElement navigationElement, PsiSubstitutor substitutor) {
super(element);
myNavigationElement = navigationElement;
mySubstitutor = substitutor;
}
@Override
public PsiElement resolve() {
return myNavigationElement;
}
@Override
public PsiElement bindToElement(@NotNull PsiElement element) throws IncorrectOperationException {
if (element == myNavigationElement) return getElement();
return super.bindToElement(element);
}
@Override
public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException {
final PsiElement resolved = resolve();
if (resolved instanceof PsiMethod) {
final PsiMethod method = (PsiMethod) resolved;
final String oldName = getElement().getName();
if (!method.getName().equals(oldName)) { //was property reference to accessor
if (PropertyUtil.isSimplePropertySetter(method)) {
final String newPropertyName = PropertyUtil.getPropertyName(newElementName);
if (newPropertyName != null) {
newElementName = newPropertyName;
}
}
}
}
return super.handleElementRename(newElementName);
}
@NotNull
@Override
public Object[] getVariants() {
return ArrayUtil.EMPTY_OBJECT_ARRAY;
}
@NotNull
@Override
public GroovyResolveResult[] multiResolve(boolean incompleteCode) {
return new GroovyResolveResult[]{new GroovyResolveResultImpl(myNavigationElement, null, null, mySubstitutor, true, true, false)};
}
}
public enum Priority {
ALWAYS_ON_TOP,
AS_LOCAL_VARIABLE,
NORMAL,
UNLIKELY
}
private static class StringTypeConditionWithPriority extends StringTypeCondition {
private StringTypeConditionWithPriority[] myInstances;
public StringTypeConditionWithPriority(String typeName) {
this(typeName, Priority.ALWAYS_ON_TOP, new StringTypeConditionWithPriority[Priority.values().length]);
}
private StringTypeConditionWithPriority(String typeName, Priority priority, StringTypeConditionWithPriority[] instances) {
super(typeName);
myInstances = instances;
super.setPriority(priority);
instances[priority.ordinal()] = this;
}
public StringTypeConditionWithPriority withPriority(Priority priority) {
StringTypeConditionWithPriority res = myInstances[priority.ordinal()];
if (res == null) {
res = new StringTypeConditionWithPriority(myTypeName, priority, myInstances);
}
return res;
}
@Override
public NamedArgumentDescriptor setPriority(@NotNull Priority priority) {
throw new UnsupportedOperationException("Use withPriority(priority)");
}
}
public static class StringTypeCondition extends NamedArgumentDescriptor {
protected final String myTypeName;
public StringTypeCondition(String typeName) {
this(typeName, null);
}
public StringTypeCondition(String typeName, @Nullable PsiElement navigationElement) {
super(navigationElement);
myTypeName = typeName;
}
@Override
public boolean checkType(@NotNull PsiType type, @NotNull GroovyPsiElement context) {
return GroovyPsiManager.isInheritorCached(type, myTypeName);
}
}
public static class StringArrayTypeCondition extends NamedArgumentDescriptor {
private final String[] myTypeNames;
public StringArrayTypeCondition(String... typeNames) {
this(null, typeNames);
}
public StringArrayTypeCondition(@Nullable PsiElement navigationElement, String... typeNames) {
super(navigationElement);
this.myTypeNames = typeNames;
}
@Override
public boolean checkType(@NotNull PsiType type, @NotNull GroovyPsiElement context) {
for (String typeName : myTypeNames) {
if (GroovyPsiManager.isInheritorCached(type, typeName)) {
return true;
}
}
return false;
}
}
public static class TypeCondition extends NamedArgumentDescriptor {
private final PsiType myType;
public TypeCondition(@NotNull PsiType type) {
this(type, null, PsiSubstitutor.EMPTY);
}
public TypeCondition(@NotNull PsiType type, @Nullable PsiElement navigationElement) {
this(type, navigationElement, PsiSubstitutor.EMPTY);
}
public TypeCondition(PsiType type, PsiElement navigationElement, PsiSubstitutor substitutor) {
super(navigationElement, substitutor);
myType = type;
}
@Override
public boolean checkType(@NotNull PsiType type, @NotNull GroovyPsiElement context) {
return TypesUtil.isAssignable(myType, type, context);
}
}
private static class UnmodifiableDescriptor extends NamedArgumentDescriptor {
public UnmodifiableDescriptor(Priority priority) {
super.setPriority(priority);
}
@Override
public NamedArgumentDescriptor setPriority(@NotNull Priority priority) {
throw new UnsupportedOperationException();
}
}
}
| |
/**
* Copyright Microsoft Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.windowsazure.management.scheduler;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import com.microsoft.windowsazure.core.OperationResponse;
import com.microsoft.windowsazure.core.OperationStatus;
import com.microsoft.windowsazure.core.OperationStatusResponse;
import com.microsoft.windowsazure.exception.ServiceException;
import com.microsoft.windowsazure.management.scheduler.models.*;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.xml.sax.SAXException;
public class JobCollectionOperationsTests extends SchedulerIntegrationTestBase {
private static String jobCollectionName;
private static String cloudServiceName;
@BeforeClass
public static void setup() throws Exception {
cloudServiceName = testJobCollectionPrefix + "jobcls" + randomString(5);
jobCollectionName = testJobCollectionPrefix + "jobcl" + randomString(7);
addRegexRule(testJobCollectionPrefix + "jobcls[a-z]{5}");
addRegexRule(testJobCollectionPrefix + "jobcl[a-z]{7}");
createManagementClient();
createCloudServiceManagementService();
createSchedulerManagementService();
setupTest(JobCollectionOperationsTests.class.getSimpleName());
getLocation();
createCloudService();
createJobCollection();
resetTest(JobCollectionOperationsTests.class.getSimpleName());
}
@AfterClass
public static void cleanup() throws Exception {
setupTest(JobCollectionOperationsTests.class.getSimpleName() + CLEANUP_SUFFIX);
cleanJobCollection();
cleanCloudService();
resetTest(JobCollectionOperationsTests.class.getSimpleName() + CLEANUP_SUFFIX);
}
private static void cleanJobCollection() {
try {
schedulerManagementClient.getJobCollectionsOperations().delete(cloudServiceName, jobCollectionName);
} catch (IOException e) {
} catch (ServiceException e) {
} catch (ExecutionException e) {
} catch (InterruptedException e) {
}
}
private static void cleanCloudService() {
CloudServiceGetResponse cloudServiceGetResponse = null;
try {
cloudServiceGetResponse = cloudServiceManagementClient.getCloudServicesOperations().get(cloudServiceName);
} catch (ServiceException e) {
} catch (IOException e) {
} catch (ParserConfigurationException e) {
} catch (SAXException e) {
}
if ((cloudServiceGetResponse != null ) &&(cloudServiceGetResponse.getResources().contains(cloudServiceName)))
{
CloudServiceOperationStatusResponse operationStatusResponse = null;
try {
operationStatusResponse = cloudServiceManagementClient.getCloudServicesOperations().delete(cloudServiceName);
} catch (InterruptedException e) {
} catch (ExecutionException e) {
} catch (ServiceException e) {
} catch (IOException e) {
}
if (operationStatusResponse != null) {
Assert.assertEquals(200, operationStatusResponse.getStatusCode());
waitOperationToComplete(operationStatusResponse.getRequestId(), 20, 60);
}
}
}
private static void createCloudService() throws InterruptedException, ExecutionException, ServiceException, IOException, ParserConfigurationException, SAXException, TransformerException, URISyntaxException {
String cloudServiceDesc = testJobCollectionPrefix + "Desc1";
CloudServiceCreateParameters createParameters = new CloudServiceCreateParameters();
//required
createParameters.setLabel(cloudServiceName);
createParameters.setDescription(cloudServiceDesc);
createParameters.setGeoRegion(hostedLocation);
OperationResponse CloudServiceOperationResponse = cloudServiceManagementClient.getCloudServicesOperations().create(cloudServiceName, createParameters);
Assert.assertEquals(200, CloudServiceOperationResponse.getStatusCode());
Assert.assertNotNull(CloudServiceOperationResponse.getRequestId());
}
private static void createJobCollection() throws Exception {
String jcLabels = "JcLabel01";
//Arrange
JobCollectionCreateParameters createParameters = new JobCollectionCreateParameters();
createParameters.setLabel(jcLabels);
//act
OperationResponse operationResponse = schedulerManagementClient.getJobCollectionsOperations().create(cloudServiceName, jobCollectionName, createParameters);
//Assert
Assert.assertEquals(200, operationResponse.getStatusCode());
Assert.assertNotNull(operationResponse.getRequestId());
}
@Before
public void beforeTest() throws Exception {
setupTest();
}
@After
public void afterTest() throws Exception {
resetTest();
}
@Test
public void listCloudServiceSuccess() throws Exception {
//Act
CloudServiceListResponse listResponse = cloudServiceManagementClient.getCloudServicesOperations().list();
ArrayList<CloudServiceListResponse.CloudService> cloudServiceList = listResponse.getCloudServices();
//Assert
Assert.assertNotNull(cloudServiceList);
Assert.assertTrue(cloudServiceList.size() > 0);
}
@Test
public void getJobCollectionSuccess() throws Exception {
//Act
JobCollectionGetResponse getResponse = schedulerManagementClient.getJobCollectionsOperations().get(cloudServiceName, jobCollectionName);
//Assert
Assert.assertEquals(200, getResponse.getStatusCode());
Assert.assertNotNull(getResponse.getRequestId());
}
@Test
public void checkAvailabilitySuccess() throws Exception {
String checkJobCollectionName = testJobCollectionPrefix + "chk"+randomString(8);
addRegexRule(testJobCollectionPrefix + "chk[a-z]{8}");
//Act
JobCollectionCheckNameAvailabilityResponse checkNameAvailabilityResponse = schedulerManagementClient.getJobCollectionsOperations().checkNameAvailability(cloudServiceName, checkJobCollectionName);
//Assert
Assert.assertEquals(true, checkNameAvailabilityResponse.isAvailable());
}
@Test
public void updateJobCollectionSuccess() throws Exception {
//Arrange
String updatedJobCollectionLabel = "testJobCollectionUpdatedLabel3";
JobCollectionGetResponse getResponse = schedulerManagementClient.getJobCollectionsOperations().get(cloudServiceName, jobCollectionName);
JobCollectionUpdateParameters updateParameters = new JobCollectionUpdateParameters();
updateParameters.setLabel(updatedJobCollectionLabel);
updateParameters.setETag(getResponse.getETag());
SchedulerOperationStatusResponse updateOperationResponse = schedulerManagementClient.getJobCollectionsOperations().update(cloudServiceName, jobCollectionName, updateParameters);
//Assert
Assert.assertEquals(200, updateOperationResponse.getStatusCode());
Assert.assertNotNull(updateOperationResponse.getRequestId());
}
private static void waitOperationToComplete(String requestId, long waitTimeBetweenTriesInSeconds, int maximumNumberOfTries) {
boolean operationCompleted = false;
int tryCount =0;
while ((!operationCompleted)&&(tryCount<maximumNumberOfTries))
{
CloudServiceOperationStatusResponse operationStatus = null;
try {
operationStatus = cloudServiceManagementClient.getOperationStatus(requestId);
} catch (IOException e) {
e.printStackTrace();
} catch (ServiceException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
if ((operationStatus.getStatus() == CloudServiceOperationStatus.Failed) || (operationStatus.getStatus() == CloudServiceOperationStatus.Succeeded))
{
operationCompleted = true;
}else{
try {
Thread.sleep(waitTimeBetweenTriesInSeconds * 1000);
tryCount ++;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
| |
package io.hawt.log.support;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.hawt.log.LogFilter;
import io.hawt.log.LogResults;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Base class for any {@link LogQuerySupportMBean} implementation
*/
public abstract class LogQuerySupport implements LogQuerySupportMBean {
private static final transient Logger LOG = LoggerFactory.getLogger(LogQuerySupport.class);
protected ObjectMapper mapper = new ObjectMapper();
private ObjectName mbeanName;
private MBeanServer mbeanServer;
private String hostName;
private volatile ObjectInstance objectInstance;
protected LogQuerySupport() {
try {
hostName = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
LOG.warn("Failed to get host name: " + e, e);
}
}
protected static String loadString(URL url) throws IOException {
InputStream is = url.openStream();
if (is == null) {
return null;
}
try {
InputStreamReader reader = new InputStreamReader(is);
StringWriter writer = new StringWriter();
final char[] buffer = new char[4096];
int n;
while ( -1 != ( n = reader.read( buffer ) ) )
{
writer.write( buffer, 0, n );
}
writer.flush();
return writer.toString();
} finally {
is.close();
}
}
/**
* Registers the object with JMX
*/
public void start() {
MBeanServer server = getMbeanServer();
if (server != null) {
registerMBeanServer(server);
} else {
LOG.error("No MBeanServer available so cannot register mbean");
}
}
/**
* Unregisters the object with JMX
*/
public void stop() {
MBeanServer server = getMbeanServer();
if (server != null) {
unregisterMBeanServer(server);
}
}
public LogResults allLogResults() throws IOException {
return getLogResults(-1);
}
@Override
public LogResults logResultsSince(long time) throws IOException {
LogFilter filter = new LogFilter();
filter.setAfterTimestamp(time);
return queryLogResults(filter);
}
public String getLogEvents(int maxCount) throws IOException {
LogResults results = getLogResults(maxCount);
return toJSON(results);
}
@Override
public String filterLogEvents(String jsonFilter) throws IOException {
LogResults results = jsonQueryLogResults(jsonFilter);
return toJSON(results);
}
@Override
public LogResults jsonQueryLogResults(String jsonFilter) throws IOException {
LogFilter filter = jsonToLogFilter(jsonFilter);
return queryLogResults(filter);
}
public ObjectName getMbeanName() throws MalformedObjectNameException {
if (mbeanName == null) {
mbeanName = new ObjectName("hawtio:type=LogQuery");
}
return mbeanName;
}
public void setMbeanName(ObjectName mbeanName) {
this.mbeanName = mbeanName;
}
public MBeanServer getMbeanServer() {
if (mbeanServer == null) {
mbeanServer = ManagementFactory.getPlatformMBeanServer();
}
return mbeanServer;
}
public void setMbeanServer(MBeanServer mbeanServer) {
this.mbeanServer = mbeanServer;
}
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
public void registerMBeanServer(MBeanServer mbeanServer) {
try {
ObjectName name = getMbeanName();
if (mbeanServer.isRegistered(name)) {
LOG.warn("MBean " + name + " is already registered!");
} else {
objectInstance = mbeanServer.registerMBean(this, name);
}
} catch (Exception e) {
LOG.warn("An error occurred during mbean server registration: " + e, e);
}
}
public void unregisterMBeanServer(MBeanServer mbeanServer) {
if (mbeanServer != null) {
try {
ObjectName name = objectInstance != null ? objectInstance.getObjectName() : getMbeanName();
if (name != null && mbeanServer.isRegistered(name)) {
mbeanServer.unregisterMBean(name);
objectInstance = null;
}
} catch (Exception e) {
LOG.warn("An error occurred during mbean server registration: " + e, e);
}
}
}
protected String toJSON(Object answer) throws IOException {
try {
StringWriter writer = new StringWriter();
mapper.writeValue(writer, answer);
return writer.toString();
} catch (IOException e) {
LOG.warn("Failed to marshal the events: " + e, e);
throw new IOException(e.getMessage());
}
}
protected LogFilter jsonToLogFilter(String json) throws IOException {
if (json == null) {
return null;
}
json = json.trim();
if (json.length() == 0 || json.equals("{}")) {
return null;
}
return mapper.readerFor(LogFilter.class).readValue(json);
}
public String getSource(String mavenCoords, String className, String filePath) throws IOException {
// the fileName could be just a name and extension so we may have to use the className to make a fully qualified package
String classNamePath = null;
if (!Objects.isBlank(className)) {
classNamePath = className.replace('.', '/') + ".java";
}
if (Objects.isBlank(filePath)) {
filePath = classNamePath;
} else {
// we may have package in the className but not in the file name
if (filePath.lastIndexOf('/') <= 0 && classNamePath != null) {
int idx = classNamePath.lastIndexOf('/');
if (idx > 0) {
filePath = classNamePath.substring(0, idx) + ensureStartsWithSlash(filePath);
}
}
}
return getArtifactFile(mavenCoords, filePath, "sources");
}
public String getJavaDoc(String mavenCoordinates, String filePath) throws IOException {
return getArtifactFile(mavenCoordinates, filePath, "javadoc");
}
protected String getArtifactFile(String mavenCoords, String filePath, String classifier) throws IOException {
filePath = ensureStartsWithSlash(filePath);
String coords = mavenCoords.replace(':', '/');
String[] array = coords.split("\\s+");
if (array == null || array.length < 2) {
return loadCoords(coords, filePath, classifier);
} else {
// lets enumerate all values if space separated
if (isRoot(filePath)) {
StringBuilder buffer = new StringBuilder();
for (String coord : array) {
try {
String text = loadCoords(coord, filePath, classifier);
if (text != null) {
buffer.append(text);
}
} catch (IOException e) {
if (LOG.isDebugEnabled()) {
LOG.debug("" + e);
}
}
}
return buffer.toString();
} else {
for (String coord : array) {
try {
return loadCoords(coord, filePath, classifier);
} catch (IOException e) {
if (LOG.isDebugEnabled()) {
LOG.debug("" + e);
}
}
}
return null;
}
}
}
protected String loadCoords(String coords, String filePath, String classifier) throws IOException {
URL url = new URL("jar:mvn:" + coords + "/jar/" + classifier + "!" + filePath);
if (isRoot(filePath)) {
return jarIndex(url);
}
return loadString(url);
}
protected String jarIndex(URL url) throws IOException {
StringBuilder buffer = new StringBuilder();
JarURLConnection uc = (JarURLConnection) url.openConnection();
return jarIndex(uc.getJarFile());
}
protected String jarIndex(File file) throws IOException {
JarFile jarFile = new JarFile(file);
return jarIndex(jarFile);
}
protected String jarIndex(JarFile jarFile) {
StringBuilder buffer = new StringBuilder();
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
addJarEntryToIndex(entry, buffer);
}
return buffer.toString();
}
protected void addJarEntryToIndex(JarEntry entry, StringBuilder buffer) {
// no need to show empty directories
if (!entry.isDirectory()) {
buffer.append(entry.getName());
buffer.append("\n");
}
}
/**
* Returns true if the file path is "/" or empty
*/
protected boolean isRoot(String filePath) {
return filePath == null || filePath.length() == 0 || filePath.equals("/");
}
public static String ensureStartsWithSlash(String path) {
if (path != null && !path.startsWith("/")) {
return "/" + path;
} else {
return path;
}
}
}
| |
package org.doxu.iota.ui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JPanel;
import org.doxu.iota.board.Board;
import org.doxu.iota.board.BoardBounds;
import org.doxu.iota.Card;
import org.doxu.iota.Game;
import org.doxu.iota.Location;
public class Table extends JPanel implements ComponentListener {
private static final Color TABLE_COLOR = new Color(153, 186, 132);
private static final Color TABLE_BOUNDS_COLOR = new Color(90, 90, 90);
private static final Color STARTING_CARD_COLOR = new Color(255, 0, 0);
private static final Color SELECTED_TURN_CARD_COLOR = new Color(152, 51, 153);
private static final Color NEXT_TURN_CARD_COLOR = new Color(0, 0, 0);
private static final Color GRID_COLOR = new Color(200, 200, 200);
private final Board gameBoard;
private Board board;
private int xAnchor;
private int yAnchor;
private final List<Location> selection;
private final List<Location> nextTurn;
public Table(Game game) {
gameBoard = game.getBoard();
board = gameBoard;
setBackground(TABLE_COLOR);
addComponentListener(this);
xAnchor = 12;
yAnchor = 12;
selection = new ArrayList<>();
nextTurn = new ArrayList<>();
addClickListener(new LocationListener() {
@Override
public void locationClicked(Location location) {
System.out.println("X - " + location.getX() + " Y - " + location.getY());
}
});
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
draw(g);
}
private void draw(Graphics g) {
drawGrid(g);
drawTableBounds((Graphics2D) g);
int xTileOffset = Board.MIDDLE - xAnchor;
int yTileOffset = Board.MIDDLE - yAnchor;
for (int i = 0; i < getTableWidth(); i++) {
for (int j = 0; j < getTableHeight(); j++) {
Card card = board.getCard(i + xTileOffset, j + yTileOffset);
if (!card.isBlank()) {
int x = i * CardRenderer.CARD_WIDTH;
int y = j * CardRenderer.CARD_WIDTH;
Graphics g2card = g.create(x, y, CardRenderer.CARD_WIDTH, CardRenderer.CARD_WIDTH);
CardRenderer.draw(g2card, card);
g2card.dispose();
if (i == xAnchor && j == yAnchor) {
g.setColor(STARTING_CARD_COLOR);
g.drawRect(x, y, CardRenderer.CARD_WIDTH, CardRenderer.CARD_WIDTH);
}
}
}
}
for (Location location : selection) {
int x = (location.getX() - xTileOffset) * CardRenderer.CARD_WIDTH;
int y = (location.getY() - yTileOffset) * CardRenderer.CARD_WIDTH;
g.setColor(SELECTED_TURN_CARD_COLOR);
g.drawRect(x, y, CardRenderer.CARD_WIDTH, CardRenderer.CARD_WIDTH);
g.drawRect(x + 1, y + 1, CardRenderer.CARD_WIDTH - 2, CardRenderer.CARD_WIDTH - 2);
}
for (Location location : nextTurn) {
int x = (location.getX() - xTileOffset) * CardRenderer.CARD_WIDTH;
int y = (location.getY() - yTileOffset) * CardRenderer.CARD_WIDTH;
g.setColor(NEXT_TURN_CARD_COLOR);
g.drawRect(x, y, CardRenderer.CARD_WIDTH, CardRenderer.CARD_WIDTH);
g.drawRect(x + 1, y + 1, CardRenderer.CARD_WIDTH - 2, CardRenderer.CARD_WIDTH - 2);
}
}
private void drawGrid(Graphics g2d) {
g2d.setColor(GRID_COLOR);
Dimension tableDim = getSize();
for (int i = CardRenderer.CARD_WIDTH; i < tableDim.height; i += CardRenderer.CARD_WIDTH) {
g2d.drawLine(0, i, tableDim.width, i);
}
for (int i = CardRenderer.CARD_WIDTH; i < tableDim.width; i += CardRenderer.CARD_WIDTH) {
g2d.drawLine(i, 0, i, tableDim.height);
}
}
private void drawTableBounds(Graphics2D g2d) {
Rectangle tableBounds = toScreenCoords(getTableBounds());
g2d.setColor(TABLE_BOUNDS_COLOR);
g2d.draw(tableBounds);
}
private Rectangle toScreenCoords(Rectangle tableCoords) {
return new Rectangle(
tableCoords.x * CardRenderer.CARD_WIDTH,
tableCoords.y * CardRenderer.CARD_WIDTH,
tableCoords.width * CardRenderer.CARD_WIDTH,
tableCoords.height * CardRenderer.CARD_WIDTH);
}
private int getTableWidth() {
return (int) Math.floor(getWidth() / (double) CardRenderer.CARD_WIDTH);
}
private int getTableHeight() {
return (int) Math.floor(getHeight() / (double) CardRenderer.CARD_WIDTH);
}
private Rectangle getTableBounds() {
BoardBounds bounds = board.getBounds();
return new Rectangle(
toTableCoordX(bounds.getMinX()),
toTableCoordY(bounds.getMinY()),
bounds.getMaxX() - bounds.getMinX() + 1,
bounds.getMaxY() - bounds.getMinY() + 1);
}
/**
* Converts a board coordinate to a table coordinate.
*
* @param x
* @return
*/
private int toTableCoordX(int x) {
int xTileOffset = Board.MIDDLE - xAnchor;
return x - xTileOffset;
}
private int toTableCoordY(int y) {
int yTileOffset = Board.MIDDLE - yAnchor;
return y - yTileOffset;
}
private int toBoardCoordX(int x) {
int xTileOffset = Board.MIDDLE - xAnchor;
return x + xTileOffset;
}
private int toBoardCoordY(int y) {
int yTileOffset = Board.MIDDLE - yAnchor;
return y + yTileOffset;
}
public void setSelection(List<Location> selection) {
this.selection.clear();
this.selection.addAll(selection);
repaint();
}
public void setNextTurn(List<Location> nextTurn) {
this.nextTurn.clear();
this.nextTurn.addAll(nextTurn);
repaint();
}
public void addClickListener(final LocationListener locationListener) {
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
Point loc = e.getPoint();
int xIndex = (int) Math.floor((double) loc.x / CardRenderer.CARD_WIDTH);
int yIndex = (int) Math.floor((double) loc.y / CardRenderer.CARD_WIDTH);
int xBoard = toBoardCoordX(xIndex);
int yBoard = toBoardCoordY(yIndex);
locationListener.locationClicked(new Location(xBoard, yBoard));
}
});
}
public void resetBoard() {
board = gameBoard;
}
public Board getBoard() {
return board;
}
public void setBoard(Board board) {
this.board = board;
}
@Override
public void componentResized(ComponentEvent e) {
xAnchor = getTableWidth() / 2;
yAnchor = getTableHeight() / 2;
}
@Override
public void componentMoved(ComponentEvent e) {
}
@Override
public void componentShown(ComponentEvent e) {
}
@Override
public void componentHidden(ComponentEvent e) {
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.druid.query.aggregation.hyperloglog;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.druid.hll.HyperLogLogCollector;
import org.apache.druid.java.util.common.IAE;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.java.util.common.guava.Comparators;
import org.apache.druid.query.aggregation.AggregateCombiner;
import org.apache.druid.query.aggregation.Aggregator;
import org.apache.druid.query.aggregation.AggregatorFactory;
import org.apache.druid.query.aggregation.AggregatorFactoryNotMergeableException;
import org.apache.druid.query.aggregation.AggregatorUtil;
import org.apache.druid.query.aggregation.BufferAggregator;
import org.apache.druid.query.aggregation.NoopAggregator;
import org.apache.druid.query.aggregation.NoopBufferAggregator;
import org.apache.druid.query.aggregation.NoopVectorAggregator;
import org.apache.druid.query.aggregation.VectorAggregator;
import org.apache.druid.query.aggregation.cardinality.HyperLogLogCollectorAggregateCombiner;
import org.apache.druid.query.cache.CacheKeyBuilder;
import org.apache.druid.segment.BaseObjectColumnValueSelector;
import org.apache.druid.segment.ColumnSelectorFactory;
import org.apache.druid.segment.NilColumnValueSelector;
import org.apache.druid.segment.column.ColumnCapabilities;
import org.apache.druid.segment.column.ValueType;
import org.apache.druid.segment.vector.VectorColumnSelectorFactory;
import javax.annotation.Nullable;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
/**
*/
public class HyperUniquesAggregatorFactory extends AggregatorFactory
{
public static Object estimateCardinality(@Nullable Object object, boolean round)
{
if (object == null) {
return 0;
}
final HyperLogLogCollector collector = (HyperLogLogCollector) object;
// Avoid ternary, it causes estimateCardinalityRound to be cast to double.
if (round) {
return collector.estimateCardinalityRound();
} else {
return collector.estimateCardinality();
}
}
private final String name;
private final String fieldName;
private final boolean isInputHyperUnique;
private final boolean round;
@JsonCreator
public HyperUniquesAggregatorFactory(
@JsonProperty("name") String name,
@JsonProperty("fieldName") String fieldName,
@JsonProperty("isInputHyperUnique") boolean isInputHyperUnique,
@JsonProperty("round") boolean round
)
{
this.name = name;
this.fieldName = fieldName;
this.isInputHyperUnique = isInputHyperUnique;
this.round = round;
}
public HyperUniquesAggregatorFactory(
String name,
String fieldName
)
{
this(name, fieldName, false, false);
}
@Override
public Aggregator factorize(ColumnSelectorFactory metricFactory)
{
BaseObjectColumnValueSelector selector = metricFactory.makeColumnValueSelector(fieldName);
if (selector instanceof NilColumnValueSelector) {
return NoopAggregator.instance();
}
final Class classOfObject = selector.classOfObject();
if (classOfObject.equals(Object.class) || HyperLogLogCollector.class.isAssignableFrom(classOfObject)) {
return new HyperUniquesAggregator(selector);
}
throw new IAE("Incompatible type for metric[%s], expected a HyperUnique, got a %s", fieldName, classOfObject);
}
@Override
public BufferAggregator factorizeBuffered(ColumnSelectorFactory metricFactory)
{
BaseObjectColumnValueSelector selector = metricFactory.makeColumnValueSelector(fieldName);
if (selector instanceof NilColumnValueSelector) {
return NoopBufferAggregator.instance();
}
final Class classOfObject = selector.classOfObject();
if (classOfObject.equals(Object.class) || HyperLogLogCollector.class.isAssignableFrom(classOfObject)) {
return new HyperUniquesBufferAggregator(selector);
}
throw new IAE("Incompatible type for metric[%s], expected a HyperUnique, got a %s", fieldName, classOfObject);
}
@Override
public VectorAggregator factorizeVector(final VectorColumnSelectorFactory selectorFactory)
{
final ColumnCapabilities capabilities = selectorFactory.getColumnCapabilities(fieldName);
if (capabilities == null || capabilities.getType() != ValueType.COMPLEX) {
return NoopVectorAggregator.instance();
} else {
return new HyperUniquesVectorAggregator(selectorFactory.makeObjectSelector(fieldName));
}
}
@Override
public boolean canVectorize()
{
return true;
}
@Override
public Comparator getComparator()
{
return Comparators.naturalNullsFirst();
}
@Override
public Object combine(Object lhs, Object rhs)
{
if (rhs == null) {
return lhs;
}
if (lhs == null) {
return rhs;
}
return ((HyperLogLogCollector) lhs).fold((HyperLogLogCollector) rhs);
}
@Override
public AggregateCombiner makeAggregateCombiner()
{
return new HyperLogLogCollectorAggregateCombiner();
}
@Override
public AggregatorFactory getCombiningFactory()
{
return new HyperUniquesAggregatorFactory(name, name, false, round);
}
@Override
public AggregatorFactory getMergingFactory(AggregatorFactory other) throws AggregatorFactoryNotMergeableException
{
if (other.getName().equals(this.getName()) && this.getClass() == other.getClass()) {
return getCombiningFactory();
} else {
throw new AggregatorFactoryNotMergeableException(this, other);
}
}
@Override
public List<AggregatorFactory> getRequiredColumns()
{
return Collections.singletonList(new HyperUniquesAggregatorFactory(
fieldName,
fieldName,
isInputHyperUnique,
round
));
}
@Override
public Object deserialize(Object object)
{
final ByteBuffer buffer;
if (object instanceof byte[]) {
buffer = ByteBuffer.wrap((byte[]) object);
} else if (object instanceof ByteBuffer) {
// Be conservative, don't assume we own this buffer.
buffer = ((ByteBuffer) object).duplicate();
} else if (object instanceof String) {
buffer = ByteBuffer.wrap(StringUtils.decodeBase64(StringUtils.toUtf8((String) object)));
} else {
return object;
}
return HyperLogLogCollector.makeCollector(buffer);
}
@Nullable
@Override
public Object finalizeComputation(@Nullable Object object)
{
return estimateCardinality(object, round);
}
@Override
@JsonProperty
public String getName()
{
return name;
}
@Override
public List<String> requiredFields()
{
return Collections.singletonList(fieldName);
}
@JsonProperty
public String getFieldName()
{
return fieldName;
}
@JsonProperty
public boolean getIsInputHyperUnique()
{
return isInputHyperUnique;
}
@JsonProperty
public boolean isRound()
{
return round;
}
@Override
public byte[] getCacheKey()
{
return new CacheKeyBuilder(AggregatorUtil.HYPER_UNIQUE_CACHE_TYPE_ID)
.appendString(fieldName)
.appendBoolean(round)
.build();
}
@Override
public String getTypeName()
{
if (isInputHyperUnique) {
return "preComputedHyperUnique";
} else {
return "hyperUnique";
}
}
@Override
public int getMaxIntermediateSize()
{
return HyperLogLogCollector.getLatestNumBytesForDenseStorage();
}
@Override
public String toString()
{
return "HyperUniquesAggregatorFactory{" +
"name='" + name + '\'' +
", fieldName='" + fieldName + '\'' +
", isInputHyperUnique=" + isInputHyperUnique +
", round=" + round +
'}';
}
@Override
public boolean equals(final Object o)
{
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final HyperUniquesAggregatorFactory that = (HyperUniquesAggregatorFactory) o;
return isInputHyperUnique == that.isInputHyperUnique &&
round == that.round &&
Objects.equals(name, that.name) &&
Objects.equals(fieldName, that.fieldName);
}
@Override
public int hashCode()
{
return Objects.hash(name, fieldName, isInputHyperUnique, round);
}
}
| |
/*
* Copyright 2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openehealth.ipf.commons.ihe.xds.core.transform.ebxml;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.openehealth.ipf.commons.ihe.xds.core.ebxml.EbXMLClassification;
import org.openehealth.ipf.commons.ihe.xds.core.ebxml.EbXMLExternalIdentifier;
import org.openehealth.ipf.commons.ihe.xds.core.ebxml.EbXMLInternationalString;
import org.openehealth.ipf.commons.ihe.xds.core.ebxml.EbXMLRegistryObject;
import org.openehealth.ipf.commons.ihe.xds.core.ebxml.EbXMLSlot;
import org.openehealth.ipf.commons.ihe.xds.core.metadata.*;
/**
* Test framework methods for ebXML related classes.
* @author Jens Riemschneider
*/
public abstract class EbrsTestUtils {
private EbrsTestUtils() {
throw new UnsupportedOperationException("Utility class");
}
/**
* Asserts that a single external identifier matching the scheme is contained in the list.
* @param scheme
* the scheme to look for.
* @param regEntry
* the registry entry containing the list of identifiers to check..
* @param expectedValue
* the expected value of the identifier.
* @param expectedName
* the expected name of the identifier.
*/
public static void assertExternalIdentifier(
String scheme,
EbXMLRegistryObject regEntry,
String expectedValue,
String expectedName) {
int found = 0;
for (EbXMLExternalIdentifier identifier : regEntry.getExternalIdentifiers()) {
if (identifier.getIdentificationScheme().equals(scheme)) {
++found;
assertEquals(expectedValue, identifier.getValue());
assertEquals(expectedName, toLocal(identifier.getName()).getValue());
}
}
assertEquals(1, found);
}
/**
* Asserts that a classification matching the given scheme is in the list.
* @param scheme
* the scheme to look for.
* @param regEntry
* registry entry whose classifications are checked.
* @param occurrence
* the index of the classification to check. The scheme can be matched
* multiple times. The occurrence is the index of the classification
* in the list of classification that match the scheme (not in the
* list given by the parameter classification).
* @param expectedNodeRepresentation
* the expected node representation.
* @param expectedLocalizedIdxName
* the expected localized index of the name.
* @return the classification that matched the assertion.
*/
public static EbXMLClassification assertClassification(String scheme, EbXMLRegistryObject regEntry, int occurrence, String expectedNodeRepresentation, int expectedLocalizedIdxName) {
List<EbXMLClassification> filtered = regEntry.getClassifications(scheme);
assertTrue("Not enough classification matching the scheme: " + scheme, filtered.size() > occurrence);
EbXMLClassification classification = filtered.get(occurrence);
assertSame(regEntry.getId(), classification.getClassifiedObject());
assertEquals(expectedNodeRepresentation, classification.getNodeRepresentation());
if (expectedLocalizedIdxName > 0) {
assertEquals(
createLocal(expectedLocalizedIdxName),
toLocal(classification.getNameAsInternationalString()));
}
return classification;
}
/**
* Asserts that a single slot matching the slot name has the expected values.
* @param slotName
* the name of the slot to check.
* @param slots
* the slot list to check.
* @param expectedSlotValues
* the expected values of the slot.
*/
public static void assertSlot(String slotName, List<EbXMLSlot> slots, String... expectedSlotValues) {
int found = 0;
for (EbXMLSlot slot : slots) {
if (slot.getName().equals(slotName)) {
List<String> values = slot.getValueList();
for (String expectedValue : expectedSlotValues) {
assertTrue("Not found: " + expectedValue + ", was: " + values, values.contains(expectedValue));
}
assertEquals(values.size(), expectedSlotValues.length);
++found;
}
}
assertEquals(1, found);
}
/**
* Retrieves the localized string from an international string and asserts
* that this string is available.
* @param international
* the international string.
* @return the localized string.
*/
public static LocalizedString toLocal(EbXMLInternationalString international) {
assertEquals(1, international.getLocalizedStrings().size());
return international.getSingleLocalizedString();
}
/**
* Creates a standard person.
* @param idx
* the index of the person. This index is used in all attributes of the
* person and any sub structures.
* @return the new person instance.
*/
public static Person createPerson(int idx) {
Person person = new Person();
person.setId(createIdentifiable(idx));
person.setName(createName(idx));
return person;
}
/**
* Creates a standard organization.
* @param idx
* the index of the organization. This index is used in all attributes of the
* organization and any sub structures.
* @return the new organization instance.
*/
public static Organization createOrganization(int idx) {
Organization organization = new Organization();
organization.setAssigningAuthority(createAssigningAuthority(idx));
organization.setIdNumber("id " + idx);
organization.setOrganizationName("orgName " + idx);
return organization;
}
/**
* Creates a standard name.
* @param idx
* the index of the name. This index is used in all attributes of the
* name.
* @return the new name instance.
*/
public static Name createName(int idx) {
return new XpnName("familyName " + idx, "givenName " + idx, "prefix " + idx, "second " + idx, "suffix " + idx, "degree " + idx);
}
/**
* Creates a standard identifiable.
* @param idx
* the index of the identifiable. This index is used in all attributes
* of the identifiable and its sub structures.
* @return the new identifiable.
*/
public static Identifiable createIdentifiable(int idx) {
return new Identifiable("id " + idx, createAssigningAuthority(idx));
}
/**
* Creates a standard assigning authority.
* @param idx
* the index of the assigning authority. This index is used in all
* attributes of the assigning authority.
* @return the new assigning authority instance.
*/
public static AssigningAuthority createAssigningAuthority(int idx) {
return new AssigningAuthority("uni " + idx, "uniType " + idx);
}
/**
* Creates a standard code.
* @param idx
* the index of the code. This index is used in all attributes of the code
* and its sub structure.
* @return the new code instance.
*/
public static Code createCode(int idx) {
return new Code("code " + idx, createLocal(idx), "scheme " + idx);
}
/**
* Creates a standard localized string.
* @param idx
* the index of the localized string. This index is used in all attributes
* of the localized string.
* @return the new localized string instance.
*/
public static LocalizedString createLocal(int idx) {
return new LocalizedString("value " + idx, "lang " + idx, "charset " + idx);
}
}
| |
/* ====================================================================
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.poi.poifs.filesystem;
import java.io.*;
import java.util.*;
import junit.framework.*;
import org.apache.poi.poifs.property.DirectoryProperty;
import org.apache.poi.poifs.property.DocumentProperty;
/**
* Class to test DirectoryNode functionality
*
* @author Marc Johnson
*/
public final class TestDirectoryNode extends TestCase {
/**
* test trivial constructor (a DirectoryNode with no children)
*/
public void testEmptyConstructor() {
POIFSFileSystem fs = new POIFSFileSystem();
DirectoryProperty property1 = new DirectoryProperty("parent");
DirectoryProperty property2 = new DirectoryProperty("child");
DirectoryNode parent = new DirectoryNode(property1, fs, null);
DirectoryNode node = new DirectoryNode(property2, fs,
parent);
assertEquals(0, parent.getPath().length());
assertEquals(1, node.getPath().length());
assertEquals("child", node.getPath().getComponent(0));
// verify that getEntries behaves correctly
int count = 0;
Iterator iter = node.getEntries();
while (iter.hasNext())
{
count++;
iter.next();
}
assertEquals(0, count);
// verify behavior of isEmpty
assertTrue(node.isEmpty());
// verify behavior of getEntryCount
assertEquals(0, node.getEntryCount());
// verify behavior of getEntry
try
{
node.getEntry("foo");
fail("should have caught FileNotFoundException");
}
catch (FileNotFoundException ignored)
{
// as expected
}
// verify behavior of isDirectoryEntry
assertTrue(node.isDirectoryEntry());
// verify behavior of getName
assertEquals(property2.getName(), node.getName());
// verify behavior of isDocumentEntry
assertTrue(!node.isDocumentEntry());
// verify behavior of getParent
assertEquals(parent, node.getParent());
}
/**
* test non-trivial constructor (a DirectoryNode with children)
*/
public void testNonEmptyConstructor() throws IOException {
DirectoryProperty property1 = new DirectoryProperty("parent");
DirectoryProperty property2 = new DirectoryProperty("child1");
property1.addChild(property2);
property1.addChild(new DocumentProperty("child2", 2000));
property2.addChild(new DocumentProperty("child3", 30000));
DirectoryNode node = new DirectoryNode(property1,
new POIFSFileSystem(), null);
// verify that getEntries behaves correctly
int count = 0;
Iterator iter = node.getEntries();
while (iter.hasNext())
{
count++;
iter.next();
}
assertEquals(2, count);
// verify behavior of isEmpty
assertTrue(!node.isEmpty());
// verify behavior of getEntryCount
assertEquals(2, node.getEntryCount());
// verify behavior of getEntry
DirectoryNode child1 = ( DirectoryNode ) node.getEntry("child1");
child1.getEntry("child3");
node.getEntry("child2");
try
{
node.getEntry("child3");
fail("should have caught FileNotFoundException");
}
catch (FileNotFoundException ignored)
{
// as expected
}
// verify behavior of isDirectoryEntry
assertTrue(node.isDirectoryEntry());
// verify behavior of getName
assertEquals(property1.getName(), node.getName());
// verify behavior of isDocumentEntry
assertTrue(!node.isDocumentEntry());
// verify behavior of getParent
assertNull(node.getParent());
}
/**
* test deletion methods
*/
public void testDeletion() throws IOException {
POIFSFileSystem fs = new POIFSFileSystem();
DirectoryEntry root = fs.getRoot();
// verify cannot delete the root directory
assertTrue(!root.delete());
DirectoryEntry dir = fs.createDirectory("myDir");
assertTrue(!root.isEmpty());
// verify can delete empty directory
assertTrue(dir.delete());
dir = fs.createDirectory("NextDir");
DocumentEntry doc =
dir.createDocument("foo",
new ByteArrayInputStream(new byte[ 1 ]));
assertTrue(!dir.isEmpty());
// verify cannot delete empty directory
assertTrue(!dir.delete());
assertTrue(doc.delete());
// verify now we can delete it
assertTrue(dir.delete());
assertTrue(root.isEmpty());
}
/**
* test change name methods
*/
public void testRename() throws IOException {
POIFSFileSystem fs = new POIFSFileSystem();
DirectoryEntry root = fs.getRoot();
// verify cannot rename the root directory
assertTrue(!root.renameTo("foo"));
DirectoryEntry dir = fs.createDirectory("myDir");
assertTrue(dir.renameTo("foo"));
assertEquals("foo", dir.getName());
DirectoryEntry dir2 = fs.createDirectory("myDir");
assertTrue(!dir2.renameTo("foo"));
assertEquals("myDir", dir2.getName());
assertTrue(dir.renameTo("FirstDir"));
assertTrue(dir2.renameTo("foo"));
assertEquals("foo", dir2.getName());
}
}
| |
/*
* Copyright 2011 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.yammer.httptunnel.server;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.AbstractChannel;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelSink;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.socket.SocketChannel;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.logging.InternalLogger;
import org.jboss.netty.logging.InternalLoggerFactory;
import com.yammer.httptunnel.state.SaturationStateChange;
import com.yammer.httptunnel.util.ChannelFutureAggregator;
import com.yammer.httptunnel.util.ForwardingFutureListener;
import com.yammer.httptunnel.util.HttpTunnelMessageUtils;
import com.yammer.httptunnel.util.IncomingBuffer;
import com.yammer.httptunnel.util.QueuedResponse;
import com.yammer.httptunnel.util.SaturationManager;
import com.yammer.httptunnel.util.WriteFragmenter;
import com.yammer.metrics.Metrics;
import com.yammer.metrics.core.Gauge;
/**
* Represents the server end of an HTTP tunnel, created after a legal tunnel
* creation request is received from a client. The server end of a tunnel does
* not have any directly related TCP connections - the connections used by a
* client are likely to change over the lifecycle of a tunnel, especially when
* an HTTP proxy is in use.
*
* @author The Netty Project (netty-dev@lists.jboss.org)
* @author Iain McGinniss (iain.mcginniss@onedrum.com)
* @author Jamie Furness (jamie@onedrum.com)
* @author OneDrum Ltd.
*/
public class HttpTunnelAcceptedChannel extends AbstractChannel implements SocketChannel {
private static final InternalLogger LOG = InternalLoggerFactory.getInstance(HttpTunnelAcceptedChannel.class);
private final HttpTunnelServerChannel parent;
private final HttpTunnelAcceptedChannelConfig config;
private final SaturationManager saturationManager;
private final InetSocketAddress remoteAddress;
private final InetSocketAddress localAddress;
private final String tunnelId;
private final AtomicBoolean opened;
private final AtomicReference<Channel> pollChannel;
private final Queue<QueuedResponse> queuedResponses;
private final IncomingBuffer<ChannelBuffer> incomingBuffer;
private final ScheduledExecutorService pingExecutor;
private final Runnable pingResponder;
private final Runnable pingTimeout;
private final Object pingLock;
private ScheduledFuture<?> pingTimeoutFuture;
protected HttpTunnelAcceptedChannel(HttpTunnelServerChannel parent, ChannelFactory factory, ChannelPipeline pipeline, ChannelSink sink, InetSocketAddress remoteAddress, String tunnelId) {
super(parent, factory, pipeline, sink);
this.parent = parent;
this.remoteAddress = remoteAddress;
this.tunnelId = tunnelId;
localAddress = parent.getLocalAddress();
config = new HttpTunnelAcceptedChannelConfig();
saturationManager = new SaturationManager(config.getWriteBufferLowWaterMark(), config.getWriteBufferHighWaterMark());
opened = new AtomicBoolean(true);
pollChannel = new AtomicReference<Channel>(null);
queuedResponses = new ConcurrentLinkedQueue<QueuedResponse>();
incomingBuffer = new IncomingBuffer<ChannelBuffer>(this);
Metrics.newGauge(HttpTunnelAcceptedChannel.class, "incomingBuffer", new Gauge<Integer>() {
@Override
public Integer value() {
return incomingBuffer.size();
}
});
pingExecutor = Executors.newSingleThreadScheduledExecutor();
pingResponder = new PingResponder();
pingTimeout = new PingTimeout();
pingLock = new Object();
pingTimeoutFuture = null;
}
String getTunnelId() {
return tunnelId;
}
@Override
public HttpTunnelAcceptedChannelConfig getConfig() {
return config;
}
@Override
public InetSocketAddress getLocalAddress() {
return this.isBound() ? localAddress : null;
}
@Override
public InetSocketAddress getRemoteAddress() {
return this.isConnected() ? remoteAddress : null;
}
@Override
public boolean isBound() {
return parent.getTunnel(tunnelId) != null;
}
@Override
public boolean isConnected() {
return parent.getTunnel(tunnelId) != null;
}
@Override
public boolean setClosed() {
final boolean success = super.setClosed();
Channels.fireChannelClosed(this);
return success;
}
synchronized ChannelFuture internalClose(boolean sendCloseRequest, ChannelFuture future) {
if (!opened.getAndSet(false)) {
future.setSuccess();
return future;
}
// Closed from the server end - we should notify the client
if (sendCloseRequest) {
final Channel channel = pollChannel.getAndSet(null);
// response channel is already in use, client will be notified of
// close at next opportunity
if (channel != null && channel.isOpen())
Channels.write(channel, HttpTunnelMessageUtils.createTunnelCloseResponse());
}
Channels.fireChannelDisconnected(this);
Channels.fireChannelUnbound(this);
parent.removeTunnel(tunnelId);
this.setClosed();
future.setSuccess();
return future;
}
synchronized ChannelFuture internalSetInterestOps(int ops, ChannelFuture future) {
if (this.getInterestOps() != ops)
this.setAndNotifyInterestedOpsChange(ops);
future.setSuccess();
return future;
}
private void setAndNotifyInterestedOpsChange(int ops) {
super.setInterestOpsNow(ops);
Channels.fireChannelInterestChanged(this);
// Update the incoming buffer
incomingBuffer.onInterestOpsChanged();
}
void internalReceiveMessage(ChannelBuffer message) {
if (!opened.get()) {
if (LOG.isWarnEnabled())
LOG.warn("Received message while channel is closed");
return;
}
// Attempt to queue this message in the incoming buffer
if (!incomingBuffer.offer(message)) {
if (LOG.isWarnEnabled())
LOG.warn("Incoming buffer rejected message, dropping");
return;
}
// If the buffer is over capacity start congestion control
if (incomingBuffer.overCapacity()) {
// TODO: Send a "stop sending shit" message!
// TODO: What about when to send the "start sending shit again"
// message?
}
}
synchronized ChannelFuture sendMessage(MessageEvent message) {
final ChannelFuture messageFuture = message.getFuture();
if (!this.isConnected()) {
final Exception error = new IllegalStateException("Unable to send message when not connected");
messageFuture.setFailure(error);
return messageFuture;
}
saturationManager.updateThresholds(config.getWriteBufferLowWaterMark(), config.getWriteBufferHighWaterMark());
// Deliver the message using the underlying channel
final ChannelBuffer messageBuffer = (ChannelBuffer) message.getMessage();
final int messageSize = messageBuffer.readableBytes();
updateSaturationStatus(messageSize);
messageFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
updateSaturationStatus(-messageSize);
}
});
final ChannelFutureAggregator aggregator = new ChannelFutureAggregator(messageFuture);
final List<ChannelBuffer> fragments = WriteFragmenter.split(messageBuffer, HttpTunnelMessageUtils.MAX_BODY_SIZE);
if (LOG.isDebugEnabled())
LOG.debug("routing outbound data for tunnel " + tunnelId);
for (ChannelBuffer fragment : fragments) {
final ChannelFuture fragmentFuture = Channels.future(this);
aggregator.addFuture(fragmentFuture);
queuedResponses.offer(new QueuedResponse(fragment, fragmentFuture));
}
this.sendQueuedData();
return messageFuture;
}
synchronized void pollQueuedData(Channel channel) {
if (!this.pollChannel.compareAndSet(null, channel))
throw new IllegalStateException("Only one poll request at a time per tunnel allowed");
this.sendQueuedData();
}
synchronized void sendQueuedData() {
final Channel channel = pollChannel.getAndSet(null);
// no response channel, or another thread has already used it
if (channel == null || !channel.isOpen())
return;
final QueuedResponse messageToSend = queuedResponses.poll();
// no data to send, restore the response channel and bail out
if (messageToSend == null) {
pollChannel.set(channel);
// Schedule a timeout that will respond with a ping and trigger a
// new poll request
pingExecutor.schedule(pingResponder, config.getPingDelay(), TimeUnit.SECONDS);
return;
}
if (LOG.isDebugEnabled())
LOG.debug("sending response for tunnel id " + tunnelId + " to " + channel.getRemoteAddress());
final HttpResponse response = HttpTunnelMessageUtils.createRecvDataResponse(messageToSend.getData());
final ChannelFuture future = messageToSend.getFuture();
Channels.write(channel, response).addListener(new ForwardingFutureListener(future) {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
// Fire a write complete event
Channels.fireWriteComplete(HttpTunnelAcceptedChannel.this, messageToSend.getLength());
}
super.operationComplete(future);
}
});
}
void updateSaturationStatus(int queueSizeDelta) {
final SaturationStateChange transition = saturationManager.queueSizeChanged(queueSizeDelta);
switch (transition) {
case SATURATED: {
this.fireWriteEnabled(false);
break;
}
case DESATURATED: {
this.fireWriteEnabled(true);
break;
}
}
}
private void fireWriteEnabled(boolean enabled) {
int ops = OP_READ;
if (!enabled)
ops |= OP_WRITE;
this.internalSetInterestOps(ops, Channels.future(this));
}
void ping() {
synchronized (pingLock) {
// Cancel the existing timeout
if (pingTimeoutFuture != null)
pingTimeoutFuture.cancel(false);
// Schedule the next timeout for 2 * ping delay seconds
pingTimeoutFuture = pingExecutor.schedule(pingTimeout, config.getPingDelay() * 2, TimeUnit.SECONDS);
}
}
private class PingResponder implements Runnable {
@Override
public void run() {
final Channel channel = pollChannel.getAndSet(null);
// no response channel, or another thread has already used it
if (channel == null || !channel.isOpen())
return;
if (LOG.isDebugEnabled())
LOG.debug("sending ping for tunnel id " + tunnelId + " to " + channel.getRemoteAddress());
final HttpResponse response = HttpTunnelMessageUtils.createTunnelPingResponse(tunnelId);
Channels.write(channel, response);
}
}
private class PingTimeout implements Runnable {
@Override
public void run() {
// We haven't received any poll in 2 * the ping delay, the channel
// is dead
internalClose(true, Channels.future(HttpTunnelAcceptedChannel.this));
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.ozone.client.io;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import org.apache.hadoop.fs.FSExceptionMessages;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.Result;
import org.apache.hadoop.hdds.scm.container.common.helpers.ContainerInfo;
import org.apache.hadoop.hdds.client.BlockID;
import org.apache.hadoop.hdds.scm.container.common.helpers.ContainerWithPipeline;
import org.apache.hadoop.io.retry.RetryPolicy;
import org.apache.hadoop.ozone.om.helpers.OmKeyLocationInfoGroup;
import org.apache.hadoop.hdds.protocol.proto.HddsProtos.ReplicationType;
import org.apache.hadoop.hdds.protocol.proto.HddsProtos.ReplicationFactor;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
import org.apache.hadoop.hdds.protocol.proto.StorageContainerLocationProtocolProtos.ObjectStageChangeRequestProto;
import org.apache.hadoop.ozone.om.helpers.OmKeyArgs;
import org.apache.hadoop.ozone.om.helpers.OmKeyInfo;
import org.apache.hadoop.ozone.om.helpers.OmKeyLocationInfo;
import org.apache.hadoop.ozone.om.helpers.OpenKeySession;
import org.apache.hadoop.ozone.om.protocolPB.OzoneManagerProtocolClientSideTranslatorPB;
import org.apache.hadoop.hdds.scm.XceiverClientManager;
import org.apache.hadoop.hdds.scm.XceiverClientSpi;
import org.apache.hadoop.hdds.scm.container.common.helpers
.StorageContainerException;
import org.apache.hadoop.hdds.scm.protocolPB
.StorageContainerLocationProtocolClientSideTranslatorPB;
import org.apache.hadoop.hdds.scm.storage.ChunkOutputStream;
import org.apache.hadoop.hdds.scm.storage.ContainerProtocolCalls;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* Maintaining a list of ChunkInputStream. Write based on offset.
*
* Note that this may write to multiple containers in one write call. In case
* that first container succeeded but later ones failed, the succeeded writes
* are not rolled back.
*
* TODO : currently not support multi-thread access.
*/
public class ChunkGroupOutputStream extends OutputStream {
public static final Logger LOG =
LoggerFactory.getLogger(ChunkGroupOutputStream.class);
// array list's get(index) is O(1)
private final ArrayList<ChunkOutputStreamEntry> streamEntries;
private int currentStreamIndex;
private long byteOffset;
private final OzoneManagerProtocolClientSideTranslatorPB omClient;
private final
StorageContainerLocationProtocolClientSideTranslatorPB scmClient;
private final OmKeyArgs keyArgs;
private final long openID;
private final XceiverClientManager xceiverClientManager;
private final int chunkSize;
private final String requestID;
private boolean closed;
private List<OmKeyLocationInfo> locationInfoList;
private final RetryPolicy retryPolicy;
/**
* A constructor for testing purpose only.
*/
@VisibleForTesting
public ChunkGroupOutputStream() {
streamEntries = new ArrayList<>();
omClient = null;
scmClient = null;
keyArgs = null;
openID = -1;
xceiverClientManager = null;
chunkSize = 0;
requestID = null;
closed = false;
locationInfoList = null;
retryPolicy = null;
}
/**
* For testing purpose only. Not building output stream from blocks, but
* taking from externally.
*
* @param outputStream
* @param length
*/
@VisibleForTesting
public void addStream(OutputStream outputStream, long length) {
streamEntries.add(new ChunkOutputStreamEntry(outputStream, length));
}
@VisibleForTesting
public List<ChunkOutputStreamEntry> getStreamEntries() {
return streamEntries;
}
@VisibleForTesting
public long getOpenID() {
return openID;
}
public ChunkGroupOutputStream(
OpenKeySession handler, XceiverClientManager xceiverClientManager,
StorageContainerLocationProtocolClientSideTranslatorPB scmClient,
OzoneManagerProtocolClientSideTranslatorPB omClient,
int chunkSize, String requestId, ReplicationFactor factor,
ReplicationType type, RetryPolicy retryPolicy) throws IOException {
this.streamEntries = new ArrayList<>();
this.currentStreamIndex = 0;
this.byteOffset = 0;
this.omClient = omClient;
this.scmClient = scmClient;
OmKeyInfo info = handler.getKeyInfo();
this.keyArgs = new OmKeyArgs.Builder()
.setVolumeName(info.getVolumeName())
.setBucketName(info.getBucketName())
.setKeyName(info.getKeyName())
.setType(type)
.setFactor(factor)
.setDataSize(info.getDataSize()).build();
this.openID = handler.getId();
this.xceiverClientManager = xceiverClientManager;
this.chunkSize = chunkSize;
this.requestID = requestId;
this.locationInfoList = new ArrayList<>();
this.retryPolicy = retryPolicy;
LOG.debug("Expecting open key with one block, but got" +
info.getKeyLocationVersions().size());
}
/**
* When a key is opened, it is possible that there are some blocks already
* allocated to it for this open session. In this case, to make use of these
* blocks, we need to add these blocks to stream entries. But, a key's version
* also includes blocks from previous versions, we need to avoid adding these
* old blocks to stream entries, because these old blocks should not be picked
* for write. To do this, the following method checks that, only those
* blocks created in this particular open version are added to stream entries.
*
* @param version the set of blocks that are pre-allocated.
* @param openVersion the version corresponding to the pre-allocation.
* @throws IOException
*/
public void addPreallocateBlocks(OmKeyLocationInfoGroup version,
long openVersion) throws IOException {
// server may return any number of blocks, (0 to any)
// only the blocks allocated in this open session (block createVersion
// equals to open session version)
for (OmKeyLocationInfo subKeyInfo : version.getLocationList()) {
if (subKeyInfo.getCreateVersion() == openVersion) {
checkKeyLocationInfo(subKeyInfo);
}
}
}
private void checkKeyLocationInfo(OmKeyLocationInfo subKeyInfo)
throws IOException {
ContainerWithPipeline containerWithPipeline = scmClient
.getContainerWithPipeline(subKeyInfo.getContainerID());
ContainerInfo container = containerWithPipeline.getContainerInfo();
XceiverClientSpi xceiverClient =
xceiverClientManager.acquireClient(containerWithPipeline.getPipeline(),
container.getContainerID());
// create container if needed
if (subKeyInfo.getShouldCreateContainer()) {
try {
ContainerProtocolCalls.createContainer(xceiverClient,
container.getContainerID(), requestID);
scmClient.notifyObjectStageChange(
ObjectStageChangeRequestProto.Type.container,
subKeyInfo.getContainerID(),
ObjectStageChangeRequestProto.Op.create,
ObjectStageChangeRequestProto.Stage.complete);
} catch (StorageContainerException ex) {
if (ex.getResult().equals(Result.CONTAINER_EXISTS)) {
//container already exist, this should never happen
LOG.debug("Container {} already exists.",
container.getContainerID());
} else {
LOG.error("Container creation failed for {}.",
container.getContainerID(), ex);
throw ex;
}
}
}
streamEntries.add(new ChunkOutputStreamEntry(subKeyInfo.getBlockID(),
keyArgs.getKeyName(), xceiverClientManager, xceiverClient, requestID,
chunkSize, subKeyInfo.getLength()));
// reset the original length to zero here. It will be updated as and when
// the data gets written.
subKeyInfo.setLength(0);
locationInfoList.add(subKeyInfo);
}
private void incrementBlockLength(int index, long length) {
if (locationInfoList != null) {
OmKeyLocationInfo locationInfo = locationInfoList.get(index);
long originalLength = locationInfo.getLength();
locationInfo.setLength(originalLength + length);
}
}
@VisibleForTesting
public long getByteOffset() {
return byteOffset;
}
@Override
public void write(int b) throws IOException {
byte[] buf = new byte[1];
buf[0] = (byte) b;
write(buf, 0, 1);
}
/**
* Try to write the bytes sequence b[off:off+len) to streams.
*
* NOTE: Throws exception if the data could not fit into the remaining space.
* In which case nothing will be written.
* TODO:May need to revisit this behaviour.
*
* @param b byte data
* @param off starting offset
* @param len length to write
* @throws IOException
*/
@Override
public void write(byte[] b, int off, int len)
throws IOException {
checkNotClosed();
handleWrite(b, off, len);
}
private void handleWrite(byte[] b, int off, int len) throws IOException {
if (b == null) {
throw new NullPointerException();
}
if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) > b.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
}
if (len == 0) {
return;
}
int succeededAllocates = 0;
while (len > 0) {
if (streamEntries.size() <= currentStreamIndex) {
Preconditions.checkNotNull(omClient);
// allocate a new block, if a exception happens, log an error and
// throw exception to the caller directly, and the write fails.
try {
allocateNewBlock(currentStreamIndex);
succeededAllocates += 1;
} catch (IOException ioe) {
LOG.error("Try to allocate more blocks for write failed, already " +
"allocated " + succeededAllocates + " blocks for this write.");
throw ioe;
}
}
// in theory, this condition should never violate due the check above
// still do a sanity check.
Preconditions.checkArgument(currentStreamIndex < streamEntries.size());
ChunkOutputStreamEntry current = streamEntries.get(currentStreamIndex);
int writeLen = Math.min(len, (int) current.getRemaining());
try {
current.write(b, off, writeLen);
} catch (IOException ioe) {
if (checkIfContainerIsClosed(ioe)) {
handleCloseContainerException(current, currentStreamIndex);
continue;
} else {
throw ioe;
}
}
incrementBlockLength(currentStreamIndex, writeLen);
if (current.getRemaining() <= 0) {
// since the current block is already written close the stream.
handleFlushOrClose(true);
currentStreamIndex += 1;
}
len -= writeLen;
off += writeLen;
byteOffset += writeLen;
}
}
private long getCommittedBlockLength(ChunkOutputStreamEntry streamEntry)
throws IOException {
long blockLength;
ContainerProtos.GetCommittedBlockLengthResponseProto responseProto;
RetryPolicy.RetryAction action;
int numRetries = 0;
// TODO : At this point of time, we also need to allocate new blocks
// from a different container and may need to nullify
// all the remaining pre-allocated blocks in case they were
// pre-allocated on the same container which got closed now.This needs
// caching the closed container list on the client itself.
while (true) {
try {
responseProto = ContainerProtocolCalls
.getCommittedBlockLength(streamEntry.xceiverClient,
streamEntry.blockID, requestID);
blockLength = responseProto.getBlockLength();
return blockLength;
} catch (StorageContainerException sce) {
try {
action = retryPolicy.shouldRetry(sce, numRetries, 0, true);
} catch (Exception e) {
throw e instanceof IOException ? (IOException) e : new IOException(e);
}
if (action.action == RetryPolicy.RetryAction.RetryDecision.FAIL) {
if (action.reason != null) {
LOG.error(
"GetCommittedBlockLength request failed. " + action.reason,
sce);
}
throw sce;
}
// Throw the exception if the thread is interrupted
if (Thread.currentThread().isInterrupted()) {
LOG.warn("Interrupted while trying for connection");
throw sce;
}
Preconditions.checkArgument(
action.action == RetryPolicy.RetryAction.RetryDecision.RETRY);
try {
Thread.sleep(action.delayMillis);
} catch (InterruptedException e) {
throw (IOException) new InterruptedIOException(
"Interrupted: action=" + action + ", retry policy=" + retryPolicy)
.initCause(e);
}
numRetries++;
LOG.trace("Retrying GetCommittedBlockLength request. Already tried "
+ numRetries + " time(s); retry policy is " + retryPolicy);
continue;
}
}
}
/**
* It performs following actions :
* a. Updates the committed length at datanode for the current stream in
* datanode.
* b. Reads the data from the underlying buffer and writes it the next stream.
*
* @param streamEntry StreamEntry
* @param streamIndex Index of the entry
* @throws IOException Throws IOexception if Write fails
*/
private void handleCloseContainerException(ChunkOutputStreamEntry streamEntry,
int streamIndex) throws IOException {
long committedLength = 0;
ByteBuffer buffer = streamEntry.getBuffer();
if (buffer == null) {
// the buffer here will be null only when closeContainerException is
// hit while calling putKey during close on chunkOutputStream.
// Since closeContainer auto commit pending keys, no need to do
// anything here.
return;
}
// In case where not a single chunk of data has been written to the Datanode
// yet. This block does not yet exist on the datanode but cached on the
// outputStream buffer. No need to call GetCommittedBlockLength here
// for this block associated with the stream here.
if (streamEntry.currentPosition >= chunkSize
|| streamEntry.currentPosition != buffer.position()) {
committedLength = getCommittedBlockLength(streamEntry);
// update the length of the current stream
locationInfoList.get(streamIndex).setLength(committedLength);
}
if (buffer.position() > 0) {
// If the data is still cached in the underlying stream, we need to
// allocate new block and write this data in the datanode. The cached
// data in the buffer does not exceed chunkSize.
Preconditions.checkState(buffer.position() < chunkSize);
currentStreamIndex += 1;
// readjust the byteOffset value to the length actually been written.
byteOffset -= buffer.position();
handleWrite(buffer.array(), 0, buffer.position());
}
// just clean up the current stream. Since the container is already closed,
// it will be auto committed. No need to call close again here.
streamEntry.cleanup();
// This case will arise when while writing the first chunk itself fails.
// In such case, the current block associated with the stream has no data
// written. Remove it from the current stream list.
if (committedLength == 0) {
streamEntries.remove(streamIndex);
locationInfoList.remove(streamIndex);
Preconditions.checkArgument(currentStreamIndex != 0);
currentStreamIndex -= 1;
}
}
private boolean checkIfContainerIsClosed(IOException ioe) {
return Optional.of(ioe.getCause())
.filter(e -> e instanceof StorageContainerException)
.map(e -> (StorageContainerException) e)
.filter(sce -> sce.getResult() == Result.CLOSED_CONTAINER_IO)
.isPresent();
}
private long getKeyLength() {
return locationInfoList.parallelStream().mapToLong(e -> e.getLength())
.sum();
}
/**
* Contact OM to get a new block. Set the new block with the index (e.g.
* first block has index = 0, second has index = 1 etc.)
*
* The returned block is made to new ChunkOutputStreamEntry to write.
*
* @param index the index of the block.
* @throws IOException
*/
private void allocateNewBlock(int index) throws IOException {
OmKeyLocationInfo subKeyInfo = omClient.allocateBlock(keyArgs, openID);
checkKeyLocationInfo(subKeyInfo);
}
@Override
public void flush() throws IOException {
checkNotClosed();
handleFlushOrClose(false);
}
/**
* Close or Flush the latest outputStream.
* @param close Flag which decides whether to call close or flush on the
* outputStream.
* @throws IOException In case, flush or close fails with exception.
*/
private void handleFlushOrClose(boolean close) throws IOException {
if (streamEntries.size() == 0) {
return;
}
int size = streamEntries.size();
int streamIndex =
currentStreamIndex >= size ? size - 1 : currentStreamIndex;
ChunkOutputStreamEntry entry = streamEntries.get(streamIndex);
if (entry != null) {
try {
if (close) {
entry.close();
} else {
entry.flush();
}
} catch (IOException ioe) {
if (checkIfContainerIsClosed(ioe)) {
// This call will allocate a new streamEntry and write the Data.
// Close needs to be retried on the newly allocated streamEntry as
// as well.
handleCloseContainerException(entry, streamIndex);
handleFlushOrClose(close);
} else {
throw ioe;
}
}
}
}
/**
* Commit the key to OM, this will add the blocks as the new key blocks.
*
* @throws IOException
*/
@Override
public void close() throws IOException {
if (closed) {
return;
}
closed = true;
handleFlushOrClose(true);
if (keyArgs != null) {
// in test, this could be null
Preconditions.checkState(streamEntries.size() == locationInfoList.size());
Preconditions.checkState(byteOffset == getKeyLength());
keyArgs.setDataSize(byteOffset);
keyArgs.setLocationInfoList(locationInfoList);
omClient.commitKey(keyArgs, openID);
locationInfoList = null;
} else {
LOG.warn("Closing ChunkGroupOutputStream, but key args is null");
}
}
/**
* Builder class of ChunkGroupOutputStream.
*/
public static class Builder {
private OpenKeySession openHandler;
private XceiverClientManager xceiverManager;
private StorageContainerLocationProtocolClientSideTranslatorPB scmClient;
private OzoneManagerProtocolClientSideTranslatorPB omClient;
private int chunkSize;
private String requestID;
private ReplicationType type;
private ReplicationFactor factor;
private RetryPolicy retryPolicy;
public Builder setHandler(OpenKeySession handler) {
this.openHandler = handler;
return this;
}
public Builder setXceiverClientManager(XceiverClientManager manager) {
this.xceiverManager = manager;
return this;
}
public Builder setScmClient(
StorageContainerLocationProtocolClientSideTranslatorPB client) {
this.scmClient = client;
return this;
}
public Builder setOmClient(
OzoneManagerProtocolClientSideTranslatorPB client) {
this.omClient = client;
return this;
}
public Builder setChunkSize(int size) {
this.chunkSize = size;
return this;
}
public Builder setRequestID(String id) {
this.requestID = id;
return this;
}
public Builder setType(ReplicationType replicationType) {
this.type = replicationType;
return this;
}
public Builder setFactor(ReplicationFactor replicationFactor) {
this.factor = replicationFactor;
return this;
}
public ChunkGroupOutputStream build() throws IOException {
return new ChunkGroupOutputStream(openHandler, xceiverManager, scmClient,
omClient, chunkSize, requestID, factor, type, retryPolicy);
}
public Builder setRetryPolicy(RetryPolicy rPolicy) {
this.retryPolicy = rPolicy;
return this;
}
}
private static class ChunkOutputStreamEntry extends OutputStream {
private OutputStream outputStream;
private final BlockID blockID;
private final String key;
private final XceiverClientManager xceiverClientManager;
private final XceiverClientSpi xceiverClient;
private final String requestId;
private final int chunkSize;
// total number of bytes that should be written to this stream
private final long length;
// the current position of this stream 0 <= currentPosition < length
private long currentPosition;
ChunkOutputStreamEntry(BlockID blockID, String key,
XceiverClientManager xceiverClientManager,
XceiverClientSpi xceiverClient, String requestId, int chunkSize,
long length) {
this.outputStream = null;
this.blockID = blockID;
this.key = key;
this.xceiverClientManager = xceiverClientManager;
this.xceiverClient = xceiverClient;
this.requestId = requestId;
this.chunkSize = chunkSize;
this.length = length;
this.currentPosition = 0;
}
/**
* For testing purpose, taking a some random created stream instance.
* @param outputStream a existing writable output stream
* @param length the length of data to write to the stream
*/
ChunkOutputStreamEntry(OutputStream outputStream, long length) {
this.outputStream = outputStream;
this.blockID = null;
this.key = null;
this.xceiverClientManager = null;
this.xceiverClient = null;
this.requestId = null;
this.chunkSize = -1;
this.length = length;
this.currentPosition = 0;
}
long getLength() {
return length;
}
long getRemaining() {
return length - currentPosition;
}
private void checkStream() {
if (this.outputStream == null) {
this.outputStream = new ChunkOutputStream(blockID,
key, xceiverClientManager, xceiverClient,
requestId, chunkSize);
}
}
@Override
public void write(int b) throws IOException {
checkStream();
outputStream.write(b);
this.currentPosition += 1;
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
checkStream();
outputStream.write(b, off, len);
this.currentPosition += len;
}
@Override
public void flush() throws IOException {
if (this.outputStream != null) {
this.outputStream.flush();
}
}
@Override
public void close() throws IOException {
if (this.outputStream != null) {
this.outputStream.close();
}
}
ByteBuffer getBuffer() throws IOException {
if (this.outputStream instanceof ChunkOutputStream) {
ChunkOutputStream out = (ChunkOutputStream) this.outputStream;
return out.getBuffer();
}
throw new IOException("Invalid Output Stream for Key: " + key);
}
public void cleanup() {
checkStream();
if (this.outputStream instanceof ChunkOutputStream) {
ChunkOutputStream out = (ChunkOutputStream) this.outputStream;
out.cleanup();
}
}
}
/**
* Verify that the output stream is open. Non blocking; this gives
* the last state of the volatile {@link #closed} field.
* @throws IOException if the connection is closed.
*/
private void checkNotClosed() throws IOException {
if (closed) {
throw new IOException(
": " + FSExceptionMessages.STREAM_IS_CLOSED + " Key: " + keyArgs
.getKeyName());
}
}
}
| |
/*
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.cordova;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.codec.binary.Base64;
import org.apache.cordova.api.LOG;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.provider.MediaStore;
/**
* This class launches the camera view, allows the user to take a picture, closes the camera view,
* and returns the captured image. When the camera view is closed, the screen displayed before
* the camera view was shown is redisplayed.
*/
public class CameraLauncher extends Plugin {
private static final int DATA_URL = 0; // Return base64 encoded string
private static final int FILE_URI = 1; // Return file uri (content://media/external/images/media/2 for Android)
private static final int PHOTOLIBRARY = 0; // Choose image from picture library (same as SAVEDPHOTOALBUM for Android)
private static final int CAMERA = 1; // Take picture from camera
private static final int SAVEDPHOTOALBUM = 2; // Choose image from picture library (same as PHOTOLIBRARY for Android)
private static final int PICTURE = 0; // allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType
private static final int VIDEO = 1; // allow selection of video only, ONLY RETURNS URL
private static final int ALLMEDIA = 2; // allow selection from all media types
private static final int JPEG = 0; // Take a picture of type JPEG
private static final int PNG = 1; // Take a picture of type PNG
private static final String GET_PICTURE = "Get Picture";
private static final String GET_VIDEO = "Get Video";
private static final String GET_All = "Get All";
private static final String LOG_TAG = "CameraLauncher";
private int mQuality; // Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality)
private int targetWidth; // desired width of the image
private int targetHeight; // desired height of the image
private Uri imageUri; // Uri of captured image
private int encodingType; // Type of encoding to use
private int mediaType; // What type of media to retrieve
public String callbackId;
private int numPics;
/**
* Constructor.
*/
public CameraLauncher() {
}
/**
* Executes the request and returns PluginResult.
*
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackId The callback id used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
*/
public PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
this.callbackId = callbackId;
try {
if (action.equals("takePicture")) {
int srcType = CAMERA;
int destType = FILE_URI;
this.targetHeight = 0;
this.targetWidth = 0;
this.encodingType = JPEG;
this.mediaType = PICTURE;
this.mQuality = 80;
this.mQuality = args.getInt(0);
destType = args.getInt(1);
srcType = args.getInt(2);
this.targetWidth = args.getInt(3);
this.targetHeight = args.getInt(4);
this.encodingType = args.getInt(5);
if (srcType == CAMERA) {
this.takePicture(destType, encodingType);
}
else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {
this.getImage(srcType, destType);
}
PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
r.setKeepCallback(true);
return r;
}
return new PluginResult(status, result);
} catch (JSONException e) {
e.printStackTrace();
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
}
}
//--------------------------------------------------------------------------
// LOCAL METHODS
//--------------------------------------------------------------------------
/**
* Take a picture with the camera.
* When an image is captured or the camera view is cancelled, the result is returned
* in CordovaActivity.onActivityResult, which forwards the result to this.onActivityResult.
*
* The image can either be returned as a base64 string or a URI that points to the file.
* To display base64 string in an img tag, set the source to:
* img.src="data:image/jpeg;base64,"+result;
* or to display URI in an img tag
* img.src=result;
*
* @param quality Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality)
* @param returnType Set the type of image to return.
*/
public void takePicture(int returnType, int encodingType) {
// Save the number of images currently on disk for later
this.numPics = queryImgDB().getCount();
// Display camera
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
// Specify file so that large image is captured and returned
// TODO: What if there isn't any external storage?
File photo = createCaptureFile(encodingType);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
this.imageUri = Uri.fromFile(photo);
this.ctx.startActivityForResult((Plugin) this, intent, (CAMERA+1)*16 + returnType+1);
}
/**
* Create a file in the applications temporary directory based upon the supplied encoding.
*
* @param encodingType of the image to be taken
* @return a File object pointing to the temporary picture
*/
private File createCaptureFile(int encodingType) {
File photo = null;
if (encodingType == JPEG) {
photo = new File(DirectoryManager.getTempDirectoryPath(ctx.getContext()), "Pic.jpg");
} else if (encodingType == PNG) {
photo = new File(DirectoryManager.getTempDirectoryPath(ctx.getContext()), "Pic.png");
} else {
throw new IllegalArgumentException("Invalid Encoding Type: " + encodingType);
}
return photo;
}
/**
* Get image from photo library.
*
* @param quality Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality)
* @param srcType The album to get image from.
* @param returnType Set the type of image to return.
*/
// TODO: Images selected from SDCARD don't display correctly, but from CAMERA ALBUM do!
public void getImage(int srcType, int returnType) {
Intent intent = new Intent();
String title = GET_PICTURE;
if (this.mediaType == PICTURE) {
intent.setType("image/*");
}
else if (this.mediaType == VIDEO) {
intent.setType("video/*");
title = GET_VIDEO;
}
else if (this.mediaType == ALLMEDIA) {
// I wanted to make the type 'image/*, video/*' but this does not work on all versions
// of android so I had to go with the wildcard search.
intent.setType("*/*");
title = GET_All;
}
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
this.ctx.startActivityForResult((Plugin) this, Intent.createChooser(intent,
new String(title)), (srcType+1)*16 + returnType + 1);
}
/**
* Scales the bitmap according to the requested size.
*
* @param bitmap The bitmap to scale.
* @return Bitmap A new Bitmap object of the same bitmap after scaling.
*/
public Bitmap scaleBitmap(Bitmap bitmap) {
int newWidth = this.targetWidth;
int newHeight = this.targetHeight;
int origWidth = bitmap.getWidth();
int origHeight = bitmap.getHeight();
// If no new width or height were specified return the original bitmap
if (newWidth <= 0 && newHeight <= 0) {
return bitmap;
}
// Only the width was specified
else if (newWidth > 0 && newHeight <= 0) {
newHeight = (newWidth * origHeight) / origWidth;
}
// only the height was specified
else if (newWidth <= 0 && newHeight > 0) {
newWidth = (newHeight * origWidth) / origHeight;
}
// If the user specified both a positive width and height
// (potentially different aspect ratio) then the width or height is
// scaled so that the image fits while maintaining aspect ratio.
// Alternatively, the specified width and height could have been
// kept and Bitmap.SCALE_TO_FIT specified when scaling, but this
// would result in whitespace in the new image.
else {
double newRatio = newWidth / (double)newHeight;
double origRatio = origWidth / (double)origHeight;
if (origRatio > newRatio) {
newHeight = (newWidth * origHeight) / origWidth;
} else if (origRatio < newRatio) {
newWidth = (newHeight * origWidth) / origHeight;
}
}
return Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
}
/**
* Called when the camera view exits.
*
* @param requestCode The request code originally supplied to startActivityForResult(),
* allowing you to identify who this result came from.
* @param resultCode The integer result code returned by the child activity through its setResult().
* @param intent An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
*/
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
// Get src and dest types from request code
int srcType = (requestCode/16) - 1;
int destType = (requestCode % 16) - 1;
// If CAMERA
if (srcType == CAMERA) {
// If image available
if (resultCode == Activity.RESULT_OK) {
try {
// Create an ExifHelper to save the exif data that is lost during compression
ExifHelper exif = new ExifHelper();
if (this.encodingType == JPEG) {
exif.createInFile(DirectoryManager.getTempDirectoryPath(ctx.getContext()) + "/Pic.jpg");
exif.readExifData();
}
// Read in bitmap of captured image
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media.getBitmap(this.ctx.getContentResolver(), imageUri);
} catch (FileNotFoundException e) {
Uri uri = intent.getData();
android.content.ContentResolver resolver = this.ctx.getContentResolver();
bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
}
bitmap = scaleBitmap(bitmap);
// If sending base64 image back
if (destType == DATA_URL) {
this.processPicture(bitmap);
checkForDuplicateImage(DATA_URL);
}
// If sending filename back
else if (destType == FILE_URI){
// Create entry in media store for image
// (Don't use insertImage() because it uses default compression setting of 50 - no way to change it)
ContentValues values = new ContentValues();
values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
Uri uri = null;
try {
uri = this.ctx.getContentResolver().insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} catch (UnsupportedOperationException e) {
LOG.d(LOG_TAG, "Can't write to external media storage.");
try {
uri = this.ctx.getContentResolver().insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
} catch (UnsupportedOperationException ex) {
LOG.d(LOG_TAG, "Can't write to internal media storage.");
this.failPicture("Error capturing image - no media storage found.");
return;
}
}
// Add compressed version of captured image to returned media store Uri
OutputStream os = this.ctx.getContentResolver().openOutputStream(uri);
bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
os.close();
// Restore exif data to file
if (this.encodingType == JPEG) {
exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.ctx));
exif.writeExifData();
}
// Send Uri back to JavaScript for viewing image
this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
}
bitmap.recycle();
bitmap = null;
System.gc();
checkForDuplicateImage(FILE_URI);
} catch (IOException e) {
e.printStackTrace();
this.failPicture("Error capturing image.");
}
}
// If cancelled
else if (resultCode == Activity.RESULT_CANCELED) {
this.failPicture("Camera cancelled.");
}
// If something else
else {
this.failPicture("Did not complete!");
}
}
// If retrieving photo from library
else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {
if (resultCode == Activity.RESULT_OK) {
Uri uri = intent.getData();
android.content.ContentResolver resolver = this.ctx.getContentResolver();
// If you ask for video or all media type you will automatically get back a file URI
// and there will be no attempt to resize any returned data
if (this.mediaType != PICTURE) {
this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
}
else {
// If sending base64 image back
if (destType == DATA_URL) {
try {
Bitmap bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
bitmap = scaleBitmap(bitmap);
this.processPicture(bitmap);
bitmap.recycle();
bitmap = null;
System.gc();
} catch (FileNotFoundException e) {
e.printStackTrace();
this.failPicture("Error retrieving image.");
}
}
// If sending filename back
else if (destType == FILE_URI) {
// Do we need to scale the returned file
if (this.targetHeight > 0 && this.targetWidth > 0) {
try {
Bitmap bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
bitmap = scaleBitmap(bitmap);
String fileName = DirectoryManager.getTempDirectoryPath(ctx.getContext()) + "/resize.jpg";
OutputStream os = new FileOutputStream(fileName);
bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
os.close();
bitmap.recycle();
bitmap = null;
// The resized image is cached by the app in order to get around this and not have to delete you
// application cache I'm adding the current system time to the end of the file url.
this.success(new PluginResult(PluginResult.Status.OK, ("file://" + fileName + "?" + System.currentTimeMillis())), this.callbackId);
System.gc();
} catch (Exception e) {
e.printStackTrace();
this.failPicture("Error retrieving image.");
}
}
else {
this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
}
}
}
}
else if (resultCode == Activity.RESULT_CANCELED) {
this.failPicture("Selection cancelled.");
}
else {
this.failPicture("Selection did not complete!");
}
}
}
/**
* Creates a cursor that can be used to determine how many images we have.
*
* @return a cursor
*/
private Cursor queryImgDB() {
return this.ctx.getContentResolver().query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Images.Media._ID },
null,
null,
null);
}
/**
* Used to find out if we are in a situation where the Camera Intent adds to images
* to the content store. If we are using a FILE_URI and the number of images in the DB
* increases by 2 we have a duplicate, when using a DATA_URL the number is 1.
*
* @param type FILE_URI or DATA_URL
*/
private void checkForDuplicateImage(int type) {
int diff = 1;
Cursor cursor = queryImgDB();
int currentNumOfImages = cursor.getCount();
if (type == FILE_URI) {
diff = 2;
}
// delete the duplicate file if the difference is 2 for file URI or 1 for Data URL
if ((currentNumOfImages - numPics) == diff) {
cursor.moveToLast();
int id = Integer.valueOf(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media._ID))) - 1;
Uri uri = Uri.parse(MediaStore.Images.Media.EXTERNAL_CONTENT_URI + "/" + id);
this.ctx.getContentResolver().delete(uri, null, null);
}
}
/**
* Compress bitmap using jpeg, convert to Base64 encoded string, and return to JavaScript.
*
* @param bitmap
*/
public void processPicture(Bitmap bitmap) {
ByteArrayOutputStream jpeg_data = new ByteArrayOutputStream();
try {
if (bitmap.compress(CompressFormat.JPEG, mQuality, jpeg_data)) {
byte[] code = jpeg_data.toByteArray();
byte[] output = Base64.encodeBase64(code);
String js_out = new String(output);
this.success(new PluginResult(PluginResult.Status.OK, js_out), this.callbackId);
js_out = null;
output = null;
code = null;
}
}
catch(Exception e) {
this.failPicture("Error compressing image.");
}
jpeg_data = null;
}
/**
* Send error message to JavaScript.
*
* @param err
*/
public void failPicture(String err) {
this.error(new PluginResult(PluginResult.Status.ERROR, err), this.callbackId);
}
}
| |
/*
* Copyright (c) 2016 Nova Ordis 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
*
* 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.novaordis.events.core;
import io.novaordis.events.api.event.EndOfStreamEvent;
import io.novaordis.events.api.event.Event;
import io.novaordis.events.core.impl.ComponentBase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.InputStream;
import java.util.List;
import java.util.concurrent.BlockingQueue;
/**
* Initiates an event stream by converting bytes it reads from its input stream into events that are placed on the
* output queue.
*
* @author Ovidiu Feodorov <ovidiu@novaordis.com>
* @since 1/24/16
*/
public class InputStreamInitiator extends ComponentBase implements Initiator {
// Constants -------------------------------------------------------------------------------------------------------
private static final Logger log = LoggerFactory.getLogger(InputStreamInitiator.class);
// Static ----------------------------------------------------------------------------------------------------------
// Attributes ------------------------------------------------------------------------------------------------------
private InputStream inputStream;
private InputStreamConversionLogic conversionLogic;
private BlockingQueue<Event> outputQueue;
// this is another way of saying "stopped" - we have a "stopped" variable in the super class and we don't want
// those to clash
private volatile boolean subStopped;
// Constructors ----------------------------------------------------------------------------------------------------
public InputStreamInitiator() {
this(null, null, null, null);
}
public InputStreamInitiator(String name) {
this(name, null, null, null);
}
public InputStreamInitiator(
String name, InputStream inputStream, ConversionLogic conversionLogic, BlockingQueue<Event> outputQueue) {
super(name);
this.subStopped = false;
setInputStream(inputStream);
setConversionLogic(conversionLogic);
setOutputQueue(outputQueue);
log.debug(this + " constructed");
}
// Initiator implementation ----------------------------------------------------------------------------------------
@Override
public BlockingQueue<Event> getOutputQueue() {
return outputQueue;
}
@Override
public BlockingQueue<Event> setOutputQueue(BlockingQueue<Event> outputQueue) {
this.outputQueue = outputQueue;
return this.outputQueue;
}
/**
* @exception IllegalArgumentException if the conversion logic being fed is not an InputStreamConversionLogic
*/
@Override
public void setConversionLogic(ConversionLogic conversionLogic) {
if (conversionLogic != null && !(conversionLogic instanceof InputStreamConversionLogic)) {
throw new IllegalArgumentException(this + " only accepts InputStreamConversionLogic instances");
}
this.conversionLogic = (InputStreamConversionLogic)conversionLogic;
}
@Override
public InputStreamConversionLogic getConversionLogic() {
return conversionLogic;
}
// Public ----------------------------------------------------------------------------------------------------------
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
// Package protected -----------------------------------------------------------------------------------------------
// Protected -------------------------------------------------------------------------------------------------------
@Override
protected void insureReadyForStart() throws IllegalStateException {
//
// we need the input stream, the conversion logic and the output queue in place
//
if (inputStream == null) {
throw new IllegalStateException(this + " not properly configured, it is missing its input stream");
}
if (conversionLogic == null) {
throw new IllegalStateException(this + " not properly configured, it is missing its conversion logic");
}
if (outputQueue == null) {
throw new IllegalStateException(this + " not properly configured, it is missing its output queue");
}
}
@Override
protected Runnable getRunnable() {
//noinspection Convert2Lambda
return new Runnable() {
@Override
public void run() {
try {
boolean eos = false;
boolean conversionLogicIssuedEoSEvent = false;
for(; !subStopped; ) {
try {
int b = inputStream.read();
if (subStopped) {
//
// if we have been decommissioned after we entered the blocking read, drop everything
// on the floor and exit
//
return;
}
if (b == -1) {
log.debug(this + " received End-Of-Stream");
eos = true;
}
conversionLogic.process(b);
List<Event> events = conversionLogic.getEvents();
for(Event e: events) {
outputQueue.put(e);
if (e instanceof EndOfStreamEvent) {
conversionLogicIssuedEoSEvent = true;
}
}
if (eos) {
log.debug(this + " reached the end of the input stream and it is now stopping ...");
if (!conversionLogicIssuedEoSEvent) {
//
// the conversion logic did not issue an EndOfStreamEvent, we do it ourselves
//
outputQueue.put(new EndOfStreamEvent());
}
//
// at this point we voluntarily stop, and since we are not blocked on read and we don't
// care what comes on the input stream, there's no point in waiting on the stop latch
// after attempting to stop - release it in advance, since the finally block, where we
// normally release the latch, will execute only after stop() invocation
releaseTheStopLatch();
stop();
break;
}
}
catch(Throwable t) {
//
// any exception thrown by the conversion logic will be handled as irrecoverable - we
// release the resources, we put the component in a stopped state and exit. The
// recommended method to deal with recoverable processing faults in the conversion logic
// is to generate specific fault events, not to throw exceptions.
//
log.error(InputStreamInitiator.this + " failed and it will irrecoverably shut down", t);
//
// we let downstream know that no more events will come from us - if we can
//
boolean endOfStreamSent = outputQueue.offer(new EndOfStreamEvent());
if (!endOfStreamSent) {
log.error(InputStreamInitiator.this + " attempted to sent and EndOfStream event but the output queue did not accept it");
}
//
// cleanup
//
stopSuperclass();
}
}
}
finally {
//
// no matter how we exit the processing loop, release the stop latch
//
releaseTheStopLatch();
}
}
@Override
public String toString() {
return InputStreamInitiator.this.toString() + "$Runnable";
}
};
}
/**
* @see ComponentBase#initiateShutdown()
*/
@Override
protected boolean initiateShutdown() {
try {
log.debug(this + " closing the input stream " + inputStream);
inputStream.close();
log.debug(this + " successfully closed the input stream");
return true;
}
catch (Exception e) {
log.error(this + " failed to close the input stream");
return false;
}
}
/**
* @see ComponentBase#stopSubclass()
*/
@Override
protected void stopSubclass() {
//
// this puts the component in an unoperable state even if the read unblocks after shutdown
//
this.subStopped = true;
//
// do not nullify the input stream, conversion logic and the output queue, external clients may still need those
// references even after the component was stopped
//
}
// Private ---------------------------------------------------------------------------------------------------------
// Inner classes ---------------------------------------------------------------------------------------------------
}
| |
/**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.financial.analytics;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.internal.junit.ArrayAsserts.assertArrayEquals;
import java.util.Arrays;
import org.testng.annotations.Test;
import com.opengamma.util.test.TestGroup;
/**
*
*/
@Test(groups = TestGroup.UNIT)
public class DoubleLabelledMatrix1DTest {
private static final Double[] TIMES1 = new Double[] {1. / 365, 2. / 365, 7. / 365, 1. / 12, 2. / 12, 0.5, 1., 1.5, 2., 3., 4., 5., 6., 7., 8., 9., 10.};
private static final Object[] LABELS1 = new Object[] {"1D", "2D", "1W", "1M", "2M", "6M", "1Y", "18M", "2Y", "3Y", "4Y", "5Y", "6Y", "7Y", "8Y", "9Y", "10Y"};
private static final double[] VALUES1 = new double[] {0, 1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0};
private static final Double[] TIMES2 = new Double[] {1. / 365, 2. / 365, 7. / 365, 1. / 12, 2. / 12, 0.5, 1., 1.5, 2., 3., 4., 5., 6., 7., 8., 9., 10.};
private static final Object[] LABELS2 = new Object[] {"1D", "2D", "1W", "1M", "2M", "6M", "1Y", "18M", "2Y", "3Y", "4Y", "5Y", "6Y", "7Y", "8Y", "9Y", "10Y"};
private static final double[] VALUES2 = new double[] {0, 4, 0, 5, 0, 0, 6, 0, 0, 0, 0, 7, 0, 0, 0, 8, 0};
private static final Double[] TIMES3 = new Double[] {3. / 365, 4. / 365, 6. / 365};
private static final Object[] LABELS3 = new Object[] {"3D", "4D", "5D"};
private static final double[] VALUES3 = new double[] {9, 10, 11};
private static final Double[] TIMES4 = new Double[] {1. / 365, 2. / 365, 7. / 365, 1. / 12, 2. / 12, 3. / 12};
private static final Object[] LABELS4 = new Object[] {"1D", "2D", "1W", "1M", "2M", "3M"};
private static final double[] VALUES4 = new double[] {0, 12, 0, 13, 14, 0};
private static final double HIGH_TOLERANCE = 0.25 / 365;
private static final Double[] TIMES5 = new Double[TIMES1.length];
private static final Double[] TIMES6 = new Double[TIMES4.length];
static {
for (int i = 0; i < TIMES1.length; i++) {
TIMES5[i] = TIMES1[i] + HIGH_TOLERANCE * Math.random();
}
for (int i = 0; i < TIMES4.length; i++) {
TIMES6[i] = TIMES4[i] - HIGH_TOLERANCE * Math.random();
}
}
private static final double[] VALUES5 = new double[] {0, 15, 0, 16, 0, 17, 0, 0, 18, 0, 0, 0, 0, 0, 0, 0, 0};
private static final double[] VALUES6 = new double[] {19, 20, 0, 0, 0, 21};
private static final DoubleLabelledMatrix1D M1 = new DoubleLabelledMatrix1D(TIMES1, LABELS1, VALUES1);
private static final DoubleLabelledMatrix1D M2 = new DoubleLabelledMatrix1D(TIMES2, LABELS2, VALUES2);
private static final DoubleLabelledMatrix1D M3 = new DoubleLabelledMatrix1D(TIMES3, LABELS3, VALUES3);
private static final DoubleLabelledMatrix1D M4 = new DoubleLabelledMatrix1D(TIMES4, LABELS4, VALUES4);
private static final DoubleLabelledMatrix1D M5 = new DoubleLabelledMatrix1D(TIMES5, LABELS1, VALUES5);
private static final DoubleLabelledMatrix1D M6 = new DoubleLabelledMatrix1D(TIMES6, LABELS4, VALUES6);
private static final double EPS = 1e-15;
@Test
public void testAddSingleValueAlreadyPresent() {
final double x = 0.4;
LabelledMatrix1D<Double, Double> m = M1.add(1., "1Y", x);
Double[] newTimes = m.getKeys();
Object[] newLabels = m.getLabels();
double[] newValues = m.getValues();
int n = TIMES1.length;
assertEquals(newTimes.length, n);
assertArrayEquals(newTimes, TIMES1);
assertArrayEquals(newLabels, LABELS1);
for (int i = 0; i < n; i++) {
if (i == 6) {
assertEquals(newValues[i], VALUES1[i] + x, EPS);
} else {
assertEquals(newValues[i], VALUES1[i], EPS);
}
}
m = M1.add(1. + HIGH_TOLERANCE / 2, "1Y", x, HIGH_TOLERANCE);
newTimes = m.getKeys();
newLabels = m.getLabels();
newValues = m.getValues();
n = TIMES1.length;
assertEquals(newTimes.length, n);
assertArrayEquals(newTimes, TIMES1);
assertArrayEquals(newLabels, LABELS1);
for (int i = 0; i < n; i++) {
if (i == 6) {
assertEquals(newValues[i], VALUES1[i] + x, EPS);
} else {
assertEquals(newValues[i], VALUES1[i], EPS);
}
}
}
@Test
public void testAddSingleValueNotPresent() {
final double x = 0.4;
LabelledMatrix1D<Double, Double> m = M1.add(2.5, "30M", x);
Double[] newTimes = m.getKeys();
Object[] newLabels = m.getLabels();
double[] newValues = m.getValues();
int n = TIMES1.length;
assertEquals(newTimes.length, n + 1);
for (int i = 0; i < n + 1; i++) {
if (i < 9) {
assertEquals(newTimes[i], TIMES1[i], EPS);
assertEquals(newLabels[i], LABELS1[i]);
assertEquals(newValues[i], VALUES1[i], EPS);
} else if (i == 9) {
assertEquals(newTimes[i], 2.5, EPS);
assertEquals(newLabels[i], "30M");
assertEquals(newValues[i], x, EPS);
} else {
assertEquals(newTimes[i], TIMES1[i - 1], EPS);
assertEquals(newLabels[i], LABELS1[i - 1]);
assertEquals(newValues[i], VALUES1[i - 1], EPS);
}
}
m = M1.add(1. + 1.5 * HIGH_TOLERANCE, "1+Y", x, HIGH_TOLERANCE);
newTimes = m.getKeys();
newLabels = m.getLabels();
newValues = m.getValues();
n = TIMES1.length;
assertEquals(newTimes.length, n + 1);
for (int i = 0; i < n; i++) {
if (i < 7) {
assertEquals(newTimes[i], TIMES1[i], EPS);
assertEquals(newLabels[i], LABELS1[i]);
assertEquals(newValues[i], VALUES1[i], EPS);
} else if (i == 7) {
assertEquals(newTimes[i], 1. + 1.5 * HIGH_TOLERANCE, EPS);
assertEquals(newLabels[i], "1+Y");
assertEquals(newValues[i], x, EPS);
} else {
assertEquals(newTimes[i], TIMES1[i - 1], EPS);
assertEquals(newLabels[i], LABELS1[i - 1]);
assertEquals(newValues[i], VALUES1[i - 1], EPS);
}
}
}
@Test
public void testAddSingleValueAlreadyPresentWithError() {
final double x = 0.4;
final LabelledMatrix1D<Double, Double> m1 = M1.add(1. + HIGH_TOLERANCE / 2, "1Y", x, HIGH_TOLERANCE);
final Double[] newTimes1 = m1.getKeys();
final Object[] newLabels1 = m1.getLabels();
final double[] newValues1 = m1.getValues();
final int n = TIMES1.length;
assertEquals(newTimes1.length, n);
assertArrayEquals(newTimes1, TIMES1);
assertArrayEquals(newLabels1, LABELS1);
for (int i = 0; i < n; i++) {
if (i == 6) {
assertEquals(newValues1[i], VALUES1[i] + x, EPS);
} else {
assertEquals(newValues1[i], VALUES1[i], EPS);
}
}
}
@Test
public void testAddSameTimes() {
LabelledMatrix1D<Double, Double> sum = M1.add(M2);
Double[] times = sum.getKeys();
Object[] labels = sum.getLabels();
double[] values = sum.getValues();
int n = times.length;
assertArrayEquals(times, TIMES1);
assertArrayEquals(labels, LABELS1);
for (int i = 0; i < n; i++) {
assertEquals(values[i], VALUES1[i] + VALUES2[i], EPS);
}
sum = M1.add(M5, HIGH_TOLERANCE);
times = sum.getKeys();
labels = sum.getLabels();
values = sum.getValues();
n = times.length;
assertArrayEquals(times, TIMES1);
assertArrayEquals(labels, LABELS1);
for (int i = 0; i < n; i++) {
assertEquals(values[i], VALUES1[i] + VALUES5[i], EPS);
}
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testAddSameTimesNoTolerance() {
final LabelledMatrix1D<Double, Double> sum = M1.addIgnoringLabel(M5);
final Double[] times = sum.getKeys();
Object[] labels = sum.getLabels();
final int n = TIMES1.length;
final int m = TIMES5.length;
assertEquals(times.length, n + m);
labels = Arrays.copyOf(LABELS1, n);
labels[0] = "O/N";
M1.add(new DoubleLabelledMatrix1D(TIMES2, labels, VALUES2));
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testAddNewTimes() {
LabelledMatrix1D<Double, Double> sum = M1.add(M3);
Double[] times = sum.getKeys();
Object[] labels = sum.getLabels();
double[] values = sum.getValues();
final int n = TIMES1.length;
final int m = TIMES3.length;
assertEquals(times.length, n + m);
for (int i = 0; i < n + m; i++) {
if (i < 2) {
assertEquals(times[i], TIMES1[i], EPS);
assertEquals(labels[i], LABELS1[i]);
assertEquals(values[i], VALUES1[i], EPS);
} else if (i < 5) {
assertEquals(times[i], TIMES3[i - 2], EPS);
assertEquals(labels[i], LABELS3[i - 2]);
assertEquals(values[i], VALUES3[i - 2], EPS);
} else {
assertEquals(times[i], TIMES1[i - 3], EPS);
assertEquals(labels[i], LABELS1[i - 3]);
assertEquals(values[i], VALUES1[i - 3], EPS);
}
}
sum = M1.addIgnoringLabel(M3, 1.5 / 365);
times = sum.getKeys();
labels = sum.getLabels();
values = sum.getValues();
assertEquals(times.length, n + 1);
assertEquals(times[0], TIMES1[0], EPS);
assertEquals(labels[0], LABELS1[0]);
assertEquals(values[0], VALUES1[0], EPS);
assertEquals(times[1], TIMES1[1], EPS);
assertEquals(labels[1], LABELS1[1]);
assertEquals(values[1], VALUES1[1] + VALUES3[0], EPS);
assertEquals(times[2], TIMES3[1], EPS);
assertEquals(labels[2], LABELS3[1]);
assertEquals(values[2], VALUES3[1], EPS);
assertEquals(times[3], TIMES1[2], EPS);
assertEquals(labels[3], LABELS1[2]);
assertEquals(values[3], VALUES1[2] + VALUES3[2], EPS);
for (int i = 4; i < n + 1; i++) {
assertEquals(times[i], TIMES1[i - 1], EPS);
assertEquals(labels[i], LABELS1[i - 1]);
assertEquals(values[i], VALUES1[i - 1], EPS);
}
sum = M1.add(M3, 1.5 / 365);
}
@Test
public void testSomeIdenticalTimes() {
LabelledMatrix1D<Double, Double> sum = M1.add(M4);
Double[] times = sum.getKeys();
Object[] labels = sum.getLabels();
double[] values = sum.getValues();
final int n = TIMES1.length;
assertEquals(times.length, n + 1);
for (int i = 0; i < n + 1; i++) {
if (i < 5) {
assertEquals(times[i], TIMES1[i], EPS);
assertEquals(labels[i], LABELS1[i]);
assertEquals(values[i], VALUES1[i] + VALUES4[i], EPS);
} else if (i == 5) {
assertEquals(times[i], TIMES4[i], EPS);
assertEquals(labels[i], LABELS4[i]);
assertEquals(values[i], VALUES4[i], EPS);
} else {
assertEquals(times[i], TIMES1[i - 1], EPS);
assertEquals(labels[i], LABELS1[i - 1]);
assertEquals(values[i], VALUES1[i - 1], EPS);
}
}
sum = M1.addIgnoringLabel(M6, HIGH_TOLERANCE);
times = sum.getKeys();
labels = sum.getLabels();
values = sum.getValues();
assertEquals(times.length, n + 1);
for (int i = 0; i < n + 1; i++) {
if (i < 5) {
assertEquals(times[i], TIMES1[i], EPS);
assertEquals(labels[i], LABELS1[i]);
assertEquals(values[i], VALUES1[i] + VALUES6[i], EPS);
} else if (i == 5) {
assertEquals(times[i], TIMES6[i], EPS);
assertEquals(labels[i], LABELS4[i]);
assertEquals(values[i], VALUES6[i], EPS);
} else {
assertEquals(times[i], TIMES1[i - 1], EPS);
assertEquals(labels[i], LABELS1[i - 1]);
assertEquals(values[i], VALUES1[i - 1], EPS);
}
}
}
}
| |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package SimpleJBurn;
import gnu.io.CommPortIdentifier;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Toolkit;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashSet;
import java.util.Iterator;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;
/**
*
* @author mario
*/
public class MainFrame extends javax.swing.JFrame implements PropertyChangeListener {
static private final String revision = "$Revision: 1.5 $";
static private final String date = "$Date: 2013/07/19 05:44:46 $";
//used to end a line in the output window
static private final String newline = "\n";
private static final String[] EEPROMTYPES = {"28C64 (8k) ", "28C128 (16k)", "28C256 (32k)"};
private static final String[] OFFSETS = {"---", " 1k", " 2k", " 3k", " 4k", " 5k", " 6k",
" 7k", " 8k", " 9k", "10k", "11k", "12k", "13k", "14k", "15k", "16k", "17k",
"18k", "19k", "20k", "21k", "22k", "23k", "24k", "25k", "26k", "27k",
"28k", "29k", "30k", "31k"};
private ReadTask readTask;
private WriteTask writeTask;
MySerial mySerial = new MySerial();
String selectedComPort;
byte[] data = new byte[32768];
byte[] eeprom = new byte[32768];
int maxAddress = 8192;
int offset = 0;
long filesize = 0;
int readwrite = 0;
int serialSpeed = 115200;
//int serialSpeed = 57600;
class ReadTask extends SwingWorker<Void, Void> {
public int done = 0;
boolean diff = false;
long start, end = 0;
int readProgress = 0;
public ReadTask(boolean d) {
this.diff = d;
}
/*
* Main task. Executed in background thread.
*/
@Override
public Void doInBackground() {
//check if eeprom should be read or written
try {
try {
//remove old data from input stream to prevent them "poisening" our
//data
mySerial.in.skip(mySerial.in.available());
//take time to read the eeprom
start = System.currentTimeMillis();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(mySerial.out));
String line = "";
log.insertString(log.getLength(), "sending command." + newline,null);
bw.write("r,0000," + Utility.wordToHex(maxAddress) + ",20" + newline);
bw.flush();
log.insertString(log.getLength(), "command sent." + newline,null);
log.insertString(log.getLength(), "trying to read." + newline,null);
int counter = 0;
byte c = ' ';
do {
eeprom[counter++] = (byte) mySerial.in.read();
if (counter % 100 == 0) {
readProgress = 100 * counter / maxAddress;
setProgress(readProgress);
}
} while (counter < maxAddress);
end = System.currentTimeMillis();
setProgress(100);
} catch (Exception e) {
log.insertString(log.getLength(), "Error: " + e.getMessage() + newline,null);
}
} catch (BadLocationException e) {
System.err.println("Output Error");
}
/**
* Random random = new Random(); int progress = 0; int steps = 100 /
* (maxAddress / 1024); //Initialize progress property.
* setProgress(0); for (int i = offset; i < maxAddress; i += 1024) {
* try { Thread.sleep(random.nextInt(300)); } catch
* (InterruptedException ignore) { } progress = i * 100 /
* maxAddress; done = i; setProgress(Math.min(progress, 100)); }
* setProgress(100); return null; *
*/
return null;
}
/*
* Executed in event dispatching thread
*/
@Override
public void done() {
try{
Toolkit.getDefaultToolkit().beep();
clearButton.setEnabled(true);
writeButton.setEnabled(true);
readButton.setEnabled(true);
setCursor(null); //turn off the wait cursor
log.insertString(log.getLength(), maxAddress + " bytes read in " + (float) (end - start) / 1000
+ " seconds " + newline,null);
textPane.setCaretPosition(textPane.getDocument().getLength());
if (this.diff) {
log.insertString(log.getLength(), "Checking difference between loaded ROM file and data on EEPROM"
+ newline,null);
int byteCount = 0;
//this.readEEPROM();
for (int i = 0; i < filesize; i++) {
if (data[i] != eeprom[i + offset]) {
byteCount++;
}
}
log.insertString(log.getLength(), filesize + " bytes checked from 0x" + Utility.wordToHex(offset)
+ " to 0x" + Utility.wordToHex(offset + (int) filesize - 1) + ", " + byteCount
+ " byte are different." + newline,null);
textPane.setCaretPosition(textPane.getDocument().getLength());
}
} catch (BadLocationException e) {
System.err.println("Output Error");
}
}
}
class WriteTask extends SwingWorker<Void, Void> {
public int done = 0;
int len;
int address;
long start, end = 0;
int writeProgress = 0;
public WriteTask(int a, int l) {
this.len = l;
this.address = a;
}
/*
* Main task. Executed in background thread.
*/
@Override
public Void doInBackground() {
try{
try {
//take time to read the eeprom
start = System.currentTimeMillis();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(mySerial.out));
String line = "";
log.insertString(log.getLength(), "sending command." + newline,null);
for (int i = 0; i < len; i += 1024) {
bw.write("w," + Utility.wordToHex(address + i) + "," + Utility.wordToHex(1024) + newline);
bw.flush();
writeProgress = i * 100 / len;
setProgress(writeProgress);
mySerial.out.write(data, i, 1024);
log.insertString(log.getLength(), "wrote data from 0x" + Utility.wordToHex(address + i)
+ " to 0x" + Utility.wordToHex(address + i + 1023) + newline,null);
textPane.setCaretPosition(textPane.getDocument().getLength());
byte c = ' ';
do {
c = (byte) mySerial.in.read();
} while (c != '%');
}
end = System.currentTimeMillis();
setProgress(100);
} catch (Exception e) {
log.insertString(log.getLength(), "Error: " + e.getMessage() + newline,null);
}
/**
* Random random = new Random(); int progress = 0; int steps = 100 /
* (maxAddress / 1024); //Initialize progress property.
* setProgress(0); for (int i = offset; i < maxAddress; i += 1024) {
* try { Thread.sleep(random.nextInt(300)); } catch
* (InterruptedException ignore) { } progress = i * 100 /
* maxAddress; done = i; setProgress(Math.min(progress, 100)); }
* setProgress(100); return null; *
*/
} catch (BadLocationException e) {
System.err.println("Output Error");
}
return null;
}
/*
* Executed in event dispatching thread
*/
@Override
public void done() {
Toolkit.getDefaultToolkit().beep();
clearButton.setEnabled(true);
writeButton.setEnabled(true);
readButton.setEnabled(true);
setCursor(null); //turn off the wait cursor
try{
log.insertString(log.getLength(), "data sent." + newline,null);
log.insertString(log.getLength(), "wrote " + len + " bytes from 0x"
+ Utility.wordToHex(address) + " to 0x"
+ Utility.wordToHex(address + (int) len - 1) + " in "
+ (float) (end - start) / 1000
+ " seconds " + newline,null);
textPane.setCaretPosition(textPane.getDocument().getLength());
} catch (BadLocationException e) {
System.err.println("Output Error");
}
}
}
/**
* Invoked when task's progress property changes.
*/
public void propertyChange(PropertyChangeEvent evt) {
if ("progress" == evt.getPropertyName()) {
int progress = (Integer) evt.getNewValue();
progressBar.setValue(progress);
//log.replaceSelection(readTask.getProgress() + "% completed, " + task.done + " bytes written " + newline,null);
}
}
/**
* Creates new form MainFrame
*/
public MainFrame() {
initComponents();
//Create a file chooser
fc = new JFileChooser();
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.BLACK);
aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console");
aset = sc.addAttribute(aset, StyleConstants.Alignment, StyleConstants.ALIGN_JUSTIFIED);
int len = textPane.getDocument().getLength();
textPane.setCaretPosition(len);
textPane.setCharacterAttributes(aset, false);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
progressBar = new javax.swing.JProgressBar();
writeButton = new javax.swing.JButton();
serialSelect = new javax.swing.JComboBox();
readButton = new javax.swing.JButton();
clearButton = new javax.swing.JButton();
loadButton = new javax.swing.JButton();
saveButton = new javax.swing.JButton();
versionButton = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
eepromTypeSelect = new javax.swing.JComboBox();
jLabel3 = new javax.swing.JLabel();
offsetSelect = new javax.swing.JComboBox();
showImageButton = new javax.swing.JButton();
showDataButton = new javax.swing.JButton();
showDiffButton = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
textPane = new javax.swing.JTextPane();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Simple JBurn 2");
setBounds(new java.awt.Rectangle(0, 0, 0, 0));
setMinimumSize(new java.awt.Dimension(800, 600));
writeButton.setText("Write EEPROM");
writeButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
writeButtonActionPerformed(evt);
}
});
HashSet h = mySerial.getAvailableSerialPorts();
Iterator<CommPortIdentifier> thePorts = h.iterator();
while (thePorts.hasNext()) {
serialSelect.addItem(thePorts.next().getName());
}
serialSelect.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
serialSelectActionPerformed(evt);
}
});
readButton.setText("Read EEPROM");
readButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
readButtonActionPerformed(evt);
}
});
clearButton.setText("Clear EEPROM");
clearButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
clearButtonActionPerformed(evt);
}
});
loadButton.setText("Load Image");
loadButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
loadButtonActionPerformed(evt);
}
});
saveButton.setText("Save Image");
saveButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saveButtonActionPerformed(evt);
}
});
versionButton.setText("Version");
versionButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
versionButtonActionPerformed(evt);
}
});
jLabel1.setText("Serial :");
jLabel2.setText("EEPROM Type :");
eepromTypeSelect.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "28C64 (8k) ", "28C128 (16k)", "28C256 (32k)" }));
eepromTypeSelect.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
eepromTypeSelectActionPerformed(evt);
}
});
jLabel3.setText("Offset :");
offsetSelect.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "---", " 1k", " 2k", " 3k", " 4k", " 5k", " 6k", " 7k", " 8k", " 9k", "10k", "11k", "12k", "13k", "14k", "15k", "16k", "17k", "18k", "19k", "20k", "21k", "22k", "23k", "24k", "25k", "26k", "27k", "28k", "29k", "30k", "31k" }));
offsetSelect.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
offsetSelectActionPerformed(evt);
}
});
showImageButton.setText("Show Image");
showImageButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showImageButtonActionPerformed(evt);
}
});
showDataButton.setText("Show Data");
showDataButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showDataButtonActionPerformed(evt);
}
});
showDiffButton.setText("Show Diff");
showDiffButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showDiffButtonActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel1Layout.createSequentialGroup()
.add(25, 25, 25)
.add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel1Layout.createSequentialGroup()
.add(clearButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(readButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(writeButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 298, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.add(jPanel1Layout.createSequentialGroup()
.add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel1Layout.createSequentialGroup()
.add(jLabel1)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(serialSelect, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 245, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(jLabel2)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(eepromTypeSelect, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 135, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(jLabel3)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED))
.add(jPanel1Layout.createSequentialGroup()
.add(loadButton)
.add(18, 18, 18)
.add(saveButton)
.add(18, 18, 18)
.add(versionButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(showImageButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 125, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(18, 18, 18)
.add(showDataButton)
.add(24, 24, 24)))
.add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(offsetSelect, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(showDiffButton))
.add(18, 18, 18))))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(12, Short.MAX_VALUE)
.add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(showDataButton)
.add(showDiffButton)
.add(showImageButton))
.add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(loadButton)
.add(saveButton)
.add(versionButton)))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(serialSelect, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(jLabel1))
.add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(offsetSelect, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(jLabel3))
.add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(eepromTypeSelect, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(jLabel2)))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
.add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(5, 5, 5))
.add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(writeButton)
.add(readButton)
.add(clearButton))))
);
textPane.setEditable(false);
textPane.setFont(new java.awt.Font("Monospaced", 0, 12)); // NOI18N
jScrollPane2.setViewportView(textPane);
log = textPane.getStyledDocument();
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 800, Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 493, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void appendToLog(String text) {
try {
log.insertString(log.getLength(),text,null);
} catch (BadLocationException e) {
System.err.println("Output Error" + e.getMessage() + newline);
}
}
private void serialSelectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_serialSelectActionPerformed
appendToLog("now selected: " + serialSelect.getSelectedItem() + newline);
selectedComPort = (String) serialSelect.getSelectedItem();
try {
mySerial.disconnect();
mySerial.connect(selectedComPort, serialSpeed);
log.insertString(log.getLength(), selectedComPort + " is now connected." + newline,null);
Thread.sleep(1000);
} catch (Exception ex) {
appendToLog( "Error : " + ex.getMessage() + newline);
}
}//GEN-LAST:event_serialSelectActionPerformed
private void writeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_writeButtonActionPerformed
writeButton.setEnabled(false);
progressBar.setValue(0);
readwrite = 1;
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
//Instances of javax.swing.SwingWorker are not reusuable, so
//we create new instances as needed.
writeTask = new WriteTask(offset, (int) filesize);
writeTask.addPropertyChangeListener(this);
writeTask.execute();
}//GEN-LAST:event_writeButtonActionPerformed
private void loadButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadButtonActionPerformed
int returnVal = fc.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//This is where a real application would open the file.
appendToLog( "Opening: " + file.getAbsolutePath() + "."
+ newline);
if (file.length() <= 32768) {
loadFile(file);
} else {
appendToLog( "Error: " + file.getName()
+ "is too big to load.");
}
} else {
appendToLog( "Open command cancelled by user." + newline);
}
}//GEN-LAST:event_loadButtonActionPerformed
private void eepromTypeSelectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_eepromTypeSelectActionPerformed
switch (eepromTypeSelect.getSelectedIndex()) {
case 0:
maxAddress = 8192;
break;
case 1:
maxAddress = 16384;
break;
case 2:
maxAddress = 32768;
break;
default:
maxAddress = 8192;
break;
}
int len = textPane.getDocument().getLength();
textPane.setCaretPosition(len);
appendToLog( "now selected: " + eepromTypeSelect.getSelectedItem()
+ ", address range = 0x0000 to 0x"
+ Utility.wordToHex(maxAddress - 1) + newline);
}//GEN-LAST:event_eepromTypeSelectActionPerformed
private void offsetSelectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_offsetSelectActionPerformed
offset = offsetSelect.getSelectedIndex() * 1024;
appendToLog("Offset is now set to : " + offsetSelect.getSelectedItem() + newline);
appendToLog("data will be written from 0x" + Utility.wordToHex(offset) + newline);
if (offset + filesize > maxAddress) {
JOptionPane.showMessageDialog(this, "The offset you choose will cause the current file not to fit in the choosen EEPROM anymore", "Warning", JOptionPane.WARNING_MESSAGE);
textPane.setForeground(Color.red);
appendToLog("WARNING!! The offset you choose will cause the current file not to fit in the choosen EEPROM anymore " + newline);
textPane.setForeground(Color.black);
textPane.setCaretPosition(textPane.getDocument().getLength());
}
}//GEN-LAST:event_offsetSelectActionPerformed
private void versionButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_versionButtonActionPerformed
appendToLog("Simple JBurn - Revision : " + revision + ", " + date + newline);
if (mySerial.isConnected()) {
try {
mySerial.out.write('V');
mySerial.out.write('\n');
String line = "";
byte c = ' ';
do {
c = (byte) mySerial.in.read();
line = line + (char) c;
if (c == '\n') {
appendToLog( line);
line = "";
}
} while (c != '\n');
} catch (Exception e) {
appendToLog("Error: " + e.getMessage() + newline);
}
} else {
appendToLog("Error: Not connected to any Programmer!" + newline);
}
}//GEN-LAST:event_versionButtonActionPerformed
private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
int returnVal = fc.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//This is where a real application would open the file.
appendToLog("Saving: " + file.getAbsolutePath() + "."
+ newline);
try {
FileOutputStream fout = new FileOutputStream(file.getAbsolutePath());
fout.write(eeprom, 0, maxAddress);
appendToLog( maxAddress + " bytes saved to \"" + file.getName() + "\"" + newline);
} catch (IOException e) {
appendToLog( "Error while saving file");
}
} else {
appendToLog( "Save command cancelled by user." + newline);
}
}//GEN-LAST:event_saveButtonActionPerformed
private void showImageButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showImageButtonActionPerformed
String line = "";
for (int i = 0; i < maxAddress; i++) {
if (i % 32 == 0) {
line = line + "0x" + Utility.wordToHex(i) + " ";
}
line = line + Utility.byteToHex(data[i]) + " ";
if (i % 32 == 31) {
appendToLog( line + newline);
line = "";
}
}
}//GEN-LAST:event_showImageButtonActionPerformed
private void showDataButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showDataButtonActionPerformed
String line = "";
for (int i = 0; i < maxAddress; i++) {
if (i % 32 == 0) {
line = line + "0x" + Utility.wordToHex(i) + " ";
}
line = line + Utility.byteToHex(eeprom[i]) + " ";
if (i % 32 == 31) {
appendToLog(line + newline);
line = "";
}
}
}//GEN-LAST:event_showDataButtonActionPerformed
private void showDiffButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showDiffButtonActionPerformed
readButton.setEnabled(false);
readwrite = 2;
progressBar.setValue(0);
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
//Instances of javax.swing.SwingWorker are not reusuable, so
//we create new instances as needed.
readTask = new ReadTask(true);
readTask.addPropertyChangeListener(this);
readTask.execute();
}//GEN-LAST:event_showDiffButtonActionPerformed
private void readButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_readButtonActionPerformed
readButton.setEnabled(false);
readwrite = 2;
progressBar.setValue(0);
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
//Instances of javax.swing.SwingWorker are not reusuable, so
//we create new instances as needed.
readTask = new ReadTask(false);
readTask.addPropertyChangeListener(this);
readTask.execute();
}//GEN-LAST:event_readButtonActionPerformed
private void clearButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearButtonActionPerformed
appendToLog("Clearing EEPROM. setting " + maxAddress + " bytes to 0xff"
+ newline);
for (int i = 0; i < maxAddress; i++) {
data[i] = (byte)(0xff);
}
clearButton.setEnabled(false);
readwrite = 0;
progressBar.setValue(0);
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
//Instances of javax.swing.SwingWorker are not reusuable, so
//we create new instances as needed.
writeTask = new WriteTask(0, maxAddress);
writeTask.addPropertyChangeListener(this);
writeTask.execute();
}//GEN-LAST:event_clearButtonActionPerformed
public void loadFile(File file) {
try {
FileInputStream fin = new FileInputStream(file.getAbsolutePath());
filesize = file.length();
for (int i = 0; i < file.length(); i++) {
data[i] = (byte) fin.read();
}
appendToLog( filesize + " bytes loaded from \"" + file.getName() + "\"" + newline);
} catch (IOException e) {
appendToLog( "Error: File not found");
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton clearButton;
private javax.swing.JComboBox eepromTypeSelect;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JButton loadButton;
private javax.swing.JComboBox offsetSelect;
private javax.swing.JProgressBar progressBar;
private javax.swing.JButton readButton;
private javax.swing.JButton saveButton;
private javax.swing.JComboBox serialSelect;
private javax.swing.JButton showDataButton;
private javax.swing.JButton showDiffButton;
private javax.swing.JButton showImageButton;
public javax.swing.JTextPane textPane;
private javax.swing.JButton versionButton;
private javax.swing.JButton writeButton;
// End of variables declaration//GEN-END:variables
private JFileChooser fc;
private StyledDocument log;
}
| |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yunos.alicontacts.quickcontact;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.provider.ContactsContract.CommonDataKinds.SipAddress;
import android.text.TextUtils;
import com.google.common.collect.Sets;
import com.yunos.alicontacts.util.PhoneCapabilityTester;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
/**
* Internally hold a cache of scaled icons based on {@link PackageManager}
* queries, keyed internally on MIME-type.
*/
public class ResolveCache {
/**
* Specific list {@link ApplicationInfo#packageName} of apps that are
* prefered <strong>only</strong> for the purposes of default icons when
* multiple {@link ResolveInfo} are found to match. This only happens when
* the user has not selected a default app yet, and they will still be
* presented with the system disambiguation dialog.
* If several of this list match (e.g. Android Browser vs. Chrome), we will pick either one
*/
private static final HashSet<String> sPreferResolve = Sets.newHashSet(
"com.android.email",
"com.google.android.email",
"com.android.phone",
"com.google.android.apps.maps",
"com.android.chrome",
"com.google.android.browser",
"com.android.browser");
private final Context mContext;
private final PackageManager mPackageManager;
private static ResolveCache sInstance;
/**
* Returns an instance of the ResolveCache. Only one internal instance is kept, so
* the argument packageManagers is ignored for all but the first call
*/
public synchronized static ResolveCache getInstance(Context context) {
if (sInstance == null) {
final Context applicationContext = context.getApplicationContext();
sInstance = new ResolveCache(applicationContext);
// Register for package-changes so that we can flush our cache
final IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
filter.addDataScheme("package");
applicationContext.registerReceiver(sInstance.mPackageIntentReceiver, filter);
}
return sInstance;
}
private synchronized static void flush() {
sInstance = null;
}
/**
* Called anytime a package is installed, uninstalled etc, so that we can wipe our cache
*/
private BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
flush();
}
};
/**
* Cached entry holding the best {@link ResolveInfo} for a specific
* MIME-type, along with a {@link SoftReference} to its icon.
*/
private static class Entry {
public ResolveInfo bestResolve;
public Drawable icon;
}
private HashMap<String, Entry> mCache = new HashMap<String, Entry>();
private ResolveCache(Context context) {
mContext = context;
mPackageManager = context.getPackageManager();
}
/**
* Get the {@link Entry} best associated with the given {@link Action},
* or create and populate a new one if it doesn't exist.
*/
protected Entry getEntry(Action action) {
final String mimeType = action.getMimeType();
Entry entry = mCache.get(mimeType);
if (entry != null) return entry;
entry = new Entry();
Intent intent = action.getIntent();
if (SipAddress.CONTENT_ITEM_TYPE.equals(mimeType)
&& !PhoneCapabilityTester.isSipPhone(mContext)) {
intent = null;
}
if (intent != null) {
final List<ResolveInfo> matches = mPackageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
// Pick first match, otherwise best found
ResolveInfo bestResolve = null;
final int size = matches.size();
if (size == 1) {
bestResolve = matches.get(0);
} else if (size > 1) {
bestResolve = getBestResolve(intent, matches);
}
if (bestResolve != null) {
final Drawable icon = bestResolve.loadIcon(mPackageManager);
entry.bestResolve = bestResolve;
entry.icon = icon;
}
}
mCache.put(mimeType, entry);
return entry;
}
/**
* Best {@link ResolveInfo} when multiple found. Ties are broken by
* selecting first from the {@link QuickContactActivity#sPreferResolve} list of
* preferred packages, second by apps that live on the system partition,
* otherwise the app from the top of the list. This is
* <strong>only</strong> used for selecting a default icon for
* displaying in the track, and does not shortcut the system
* {@link Intent} disambiguation dialog.
*/
protected ResolveInfo getBestResolve(Intent intent, List<ResolveInfo> matches) {
// Try finding preferred activity, otherwise detect disambig
final ResolveInfo foundResolve = mPackageManager.resolveActivity(intent,
PackageManager.MATCH_DEFAULT_ONLY);
final boolean foundDisambig = (foundResolve.match &
IntentFilter.MATCH_CATEGORY_MASK) == 0;
if (!foundDisambig) {
// Found concrete match, so return directly
return foundResolve;
}
// Accept any package from prefer list, otherwise first system app
ResolveInfo firstSystem = null;
for (ResolveInfo info : matches) {
final boolean isSystem = (info.activityInfo.applicationInfo.flags
& ApplicationInfo.FLAG_SYSTEM) != 0;
final boolean isPrefer = sPreferResolve
.contains(info.activityInfo.applicationInfo.packageName);
if (isPrefer) return info;
if (isSystem && firstSystem == null) firstSystem = info;
}
// Return first system found, otherwise first from list
return firstSystem != null ? firstSystem : matches.get(0);
}
/**
* Check {@link PackageManager} to see if any apps offer to handle the
* given {@link Action}.
*/
public boolean hasResolve(Action action) {
return getEntry(action).bestResolve != null;
}
/**
* Find the best description for the given {@link Action}, usually used
* for accessibility purposes.
*/
public CharSequence getDescription(Action action) {
final CharSequence actionSubtitle = action.getSubtitle();
final ResolveInfo info = getEntry(action).bestResolve;
if (info != null) {
return info.loadLabel(mPackageManager);
} else if (!TextUtils.isEmpty(actionSubtitle)) {
return actionSubtitle;
} else {
return null;
}
}
/**
* Return the best icon for the given {@link Action}, which is usually
* based on the {@link ResolveInfo} found through a
* {@link PackageManager} query.
*/
public Drawable getIcon(Action action) {
return getEntry(action).icon;
}
public void clear() {
mCache.clear();
}
}
| |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.execution.actions;
import com.intellij.execution.Location;
import com.intellij.execution.PsiLocation;
import com.intellij.execution.RunManager;
import com.intellij.execution.RunnerAndConfigurationSettings;
import com.intellij.execution.configurations.ConfigurationType;
import com.intellij.execution.configurations.ConfigurationTypeUtil;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.execution.junit.RuntimeConfigurationProducer;
import com.intellij.ide.DataManager;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.util.List;
/**
* Context for creating run configurations from a location in the source code.
*
* @see RunConfigurationProducer
*/
public class ConfigurationContext {
private static final Logger LOG = Logger.getInstance("#com.intellij.execution.actions.ConfigurationContext");
private final Location<PsiElement> myLocation;
private RunnerAndConfigurationSettings myConfiguration;
private Ref<RunnerAndConfigurationSettings> myExistingConfiguration;
private final Module myModule;
private final RunConfiguration myRuntimeConfiguration;
private final Component myContextComponent;
public static Key<ConfigurationContext> SHARED_CONTEXT = Key.create("SHARED_CONTEXT");
private List<RuntimeConfigurationProducer> myPreferredProducers;
private List<ConfigurationFromContext> myConfigurationsFromContext;
public static ConfigurationContext getFromContext(DataContext dataContext) {
final ConfigurationContext context = new ConfigurationContext(dataContext);
final DataManager dataManager = DataManager.getInstance();
ConfigurationContext sharedContext = dataManager.loadFromDataContext(dataContext, SHARED_CONTEXT);
if (sharedContext == null ||
sharedContext.getLocation() == null ||
context.getLocation() == null ||
!Comparing.equal(sharedContext.getLocation().getPsiElement(), context.getLocation().getPsiElement())) {
sharedContext = context;
dataManager.saveInDataContext(dataContext, SHARED_CONTEXT, sharedContext);
}
return sharedContext;
}
private ConfigurationContext(final DataContext dataContext) {
myRuntimeConfiguration = RunConfiguration.DATA_KEY.getData(dataContext);
myContextComponent = PlatformDataKeys.CONTEXT_COMPONENT.getData(dataContext);
myModule = LangDataKeys.MODULE.getData(dataContext);
@SuppressWarnings({"unchecked"})
final Location<PsiElement> location = (Location<PsiElement>)Location.DATA_KEY.getData(dataContext);
if (location != null) {
myLocation = location;
return;
}
final Project project = CommonDataKeys.PROJECT.getData(dataContext);
if (project == null) {
myLocation = null;
return;
}
final PsiElement element = getSelectedPsiElement(dataContext, project);
if (element == null) {
myLocation = null;
return;
}
myLocation = new PsiLocation<PsiElement>(project, myModule, element);
}
/**
* Returns the configuration created from this context.
*
* @return the configuration, or null if none of the producers were able to create a configuration from this context.
*/
@Nullable
public RunnerAndConfigurationSettings getConfiguration() {
if (myConfiguration == null) createConfiguration();
return myConfiguration;
}
private void createConfiguration() {
LOG.assertTrue(myConfiguration == null);
final Location location = getLocation();
myConfiguration = location != null && !DumbService.isDumb(location.getProject()) ?
PreferredProducerFind.createConfiguration(location, this) :
null;
}
public void setConfiguration(RunnerAndConfigurationSettings configuration) {
myConfiguration = configuration;
}
@Deprecated
@Nullable
public RunnerAndConfigurationSettings updateConfiguration(final RuntimeConfigurationProducer producer) {
myConfiguration = producer.getConfiguration();
return myConfiguration;
}
/**
* Returns the source code location for this context.
*
* @return the source code location, or null if no source code fragment is currently selected.
*/
@Nullable
public Location getLocation() {
return myLocation;
}
/**
* Returns the PSI element at caret for this context.
*
* @return the PSI element, or null if no source code fragment is currently selected.
*/
@Nullable
public PsiElement getPsiLocation() {
return myLocation != null ? myLocation.getPsiElement() : null;
}
/**
* Finds an existing run configuration matching the context.
*
* @return an existing configuration, or null if none was found.
*/
@Nullable
public RunnerAndConfigurationSettings findExisting() {
if (myExistingConfiguration != null) return myExistingConfiguration.get();
myExistingConfiguration = new Ref<RunnerAndConfigurationSettings>();
if (myLocation == null) {
return null;
}
final PsiElement psiElement = myLocation.getPsiElement();
if (!psiElement.isValid()) {
return null;
}
final List<RuntimeConfigurationProducer> producers = findPreferredProducers();
if (myRuntimeConfiguration != null) {
if (producers != null) {
for (RuntimeConfigurationProducer producer : producers) {
final RunnerAndConfigurationSettings configuration = producer.findExistingConfiguration(myLocation, this);
if (configuration != null && configuration.getConfiguration() == myRuntimeConfiguration) {
myExistingConfiguration.set(configuration);
}
}
}
for (RunConfigurationProducer producer : RunConfigurationProducer.getProducers(getProject())) {
RunnerAndConfigurationSettings configuration = producer.findExistingConfiguration(this);
if (configuration != null && configuration.getConfiguration() == myRuntimeConfiguration) {
myExistingConfiguration.set(configuration);
}
}
}
if (producers != null) {
for (RuntimeConfigurationProducer producer : producers) {
final RunnerAndConfigurationSettings configuration = producer.findExistingConfiguration(myLocation, this);
if (configuration != null) {
myExistingConfiguration.set(configuration);
}
}
}
for (RunConfigurationProducer producer : RunConfigurationProducer.getProducers(getProject())) {
RunnerAndConfigurationSettings configuration = producer.findExistingConfiguration(this);
if (configuration != null) {
myExistingConfiguration.set(configuration);
}
}
return myExistingConfiguration.get();
}
@Nullable
private static PsiElement getSelectedPsiElement(final DataContext dataContext, final Project project) {
PsiElement element = null;
final Editor editor = CommonDataKeys.EDITOR.getData(dataContext);
if (editor != null){
final PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
if (psiFile != null) {
final int offset = editor.getCaretModel().getOffset();
element = psiFile.findElementAt(offset);
if (element == null && offset > 0 && offset == psiFile.getTextLength()) {
element = psiFile.findElementAt(offset-1);
}
}
}
if (element == null) {
final PsiElement[] elements = LangDataKeys.PSI_ELEMENT_ARRAY.getData(dataContext);
element = elements != null && elements.length > 0 ? elements[0] : null;
}
if (element == null) {
final VirtualFile[] files = CommonDataKeys.VIRTUAL_FILE_ARRAY.getData(dataContext);
if (files != null && files.length > 0) {
element = PsiManager.getInstance(project).findFile(files[0]);
}
}
return element;
}
public RunManager getRunManager() {
return RunManager.getInstance(getProject());
}
public Project getProject() {
return myLocation.getProject();
}
public Module getModule() {
return myModule;
}
public DataContext getDataContext() {
return DataManager.getInstance().getDataContext(myContextComponent);
}
/**
* Returns original {@link RunConfiguration} from this context.
* For example, it could be some test framework runtime configuration that had been launched
* and that had brought a result test tree on which a right-click action was performed.
*
* @param type {@link ConfigurationType} instance to filter original runtime configuration by its type
* @return {@link RunConfiguration} instance, it could be null
*/
@Nullable
public RunConfiguration getOriginalConfiguration(@Nullable ConfigurationType type) {
if (type == null) {
return myRuntimeConfiguration;
}
if (myRuntimeConfiguration != null
&& ConfigurationTypeUtil.equals(myRuntimeConfiguration.getType(), type)) {
return myRuntimeConfiguration;
}
return null;
}
@Deprecated
@Nullable
public List<RuntimeConfigurationProducer> findPreferredProducers() {
if (myPreferredProducers == null) {
myPreferredProducers = PreferredProducerFind.findPreferredProducers(myLocation, this, true);
}
return myPreferredProducers;
}
public List<ConfigurationFromContext> getConfigurationsFromContext() {
if (myConfigurationsFromContext == null) {
myConfigurationsFromContext = PreferredProducerFind.getConfigurationsFromContext(myLocation, this, true);
}
return myConfigurationsFromContext;
}
}
| |
/*
* Copyright 2013 Gregory Graham.
*
* 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 nz.co.gregs.dbvolution.expressions;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import nz.co.gregs.dbvolution.DBQuery;
import nz.co.gregs.dbvolution.DBQueryRow;
import nz.co.gregs.dbvolution.annotations.DBColumn;
import nz.co.gregs.dbvolution.datatypes.DBNumber;
import nz.co.gregs.dbvolution.datatypes.DBString;
import nz.co.gregs.dbvolution.example.CarCompany;
import nz.co.gregs.dbvolution.example.Marque;
import nz.co.gregs.dbvolution.generic.AbstractTest;
import org.hamcrest.Matchers;
import static org.hamcrest.Matchers.is;
import org.junit.Assert;
import org.junit.Test;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.is;
public class NumberExpressionTest extends AbstractTest {
public NumberExpressionTest(Object testIterationName, Object db) {
super(testIterationName, db);
}
@Test
public void testSimpleEquation() throws SQLException {
// database.setPrintSQLBeforeExecuting(true);
Marque marq = new Marque();
DBQuery dbQuery = database.getDBQuery(marq);
dbQuery.addCondition(marq.column(marq.uidMarque).mod(2).is(0));
List<DBQueryRow> allRows = dbQuery.getAllRows();
// database.print(allRows);
Assert.assertThat(allRows.size(), is(11));
for (Marque marque : dbQuery.getAllInstancesOf(marq)) {
Assert.assertThat(marque.uidMarque.getValue().intValue() % 2, is(0));
}
}
@Test
public void testSimpleEquationWithValue() throws SQLException {
Marque marq = new Marque();
DBQuery dbQuery = database.getDBQuery(marq);
dbQuery.addCondition(marq.column(marq.uidMarque).mod(2).is(0));
// dbQuery.addCondition(NumberExpression.value(0).is(marq.column(marq.uidMarque).mod(2)));
List<DBQueryRow> allRows = dbQuery.getAllRows();
Assert.assertThat(allRows.size(), is(11));
for (Marque marque : dbQuery.getAllInstancesOf(marq)) {
Assert.assertThat(marque.uidMarque.getValue().intValue() % 2, is(0));
}
}
@Test
public void testIfThenElse() throws SQLException {
Marque marq = new Marque();
DBQuery dbQuery = database.getDBQuery(marq);
dbQuery.addCondition(marq.column(marq.uidMarque).mod(2).is(0).ifThenElse(2, 1).is(2));
List<DBQueryRow> allRows = dbQuery.getAllRows();
Assert.assertThat(allRows.size(), is(11));
for (Marque marque : dbQuery.getAllInstancesOf(marq)) {
Assert.assertThat(marque.uidMarque.getValue().intValue() % 2, is(0));
}
}
@Test
public void testBooleanConvertToInteger() throws SQLException {
Marque marq = new Marque();
DBQuery dbQuery = database.getDBQuery(marq);
dbQuery.addCondition(marq.column(marq.uidMarque).mod(2).is(0).convertToInteger().is(1));
List<DBQueryRow> allRows = dbQuery.getAllRows();
Assert.assertThat(allRows.size(), is(11));
for (Marque marque : dbQuery.getAllInstancesOf(marq)) {
Assert.assertThat(marque.uidMarque.getValue().intValue() % 2, is(0));
}
}
@Test
public void testAllArithmetic() throws SQLException {
Marque marq = new Marque();
DBQuery dbQuery = database.getDBQuery(marq);
dbQuery.addCondition(
marq.column(marq.uidMarque)
.plus(2)
.minus(4)
.times(6)
.dividedBy(3)
.mod(5)
.is(0));
List<DBQueryRow> allRows = dbQuery.getAllRows();
database.print(allRows);
Assert.assertThat(allRows.size(), is(2));
for (DBQueryRow dBQueryRow : allRows) {
Marque marque = dBQueryRow.get(marq);
Assert.assertThat(
marque.uidMarque.getValue().intValue(),
Matchers.anyOf(
is(1),
is(4893101)
)
);
}
}
@Test
public void testBrackets() throws SQLException {
Marque marq = new Marque();
DBQuery dbQuery = database.getDBQuery(marq);
dbQuery.addCondition(
marq.column(marq.uidMarque)
.plus(2)
.minus(4)
.bracket()
.times(6)
.bracket()
.dividedBy(3)
.is(-2));
List<DBQueryRow> allRows = dbQuery.getAllRows();
// database.print(allRows);
Assert.assertThat(allRows.size(), is(1));
Marque marque = allRows.get(0).get(marq);
Assert.assertThat(marque.uidMarque.getValue().intValue(), is(1));
dbQuery = database.getDBQuery(marq);
dbQuery.addCondition(
marq.column(marq.uidMarque)
.plus(2)
.minus(4)
.bracket()
.times(6)
.bracket()
.dividedBy(3)
.is(-2));
allRows = dbQuery.getAllRows();
// database.print(allRows);
Assert.assertThat(allRows.size(), is(1));
marque = allRows.get(0).get(marq);
Assert.assertThat(marque.uidMarque.getValue().intValue(), is(1));
}
@Test
public void testBracketsInCondition() throws SQLException {
Marque marq = new Marque();
DBQuery dbQuery = database.getDBQuery(marq);
dbQuery.addCondition(
marq.column(marq.uidMarque).plus(2).minus(4).bracket().times(6).bracket().dividedBy(3).is(-2));
List<DBQueryRow> allRows = dbQuery.getAllRows();
// database.print(allRows);
Assert.assertThat(allRows.size(), is(1));
Marque marque = allRows.get(0).get(marq);
Assert.assertThat(marque.uidMarque.getValue().intValue(), is(1));
dbQuery = database.getDBQuery(marq);
dbQuery.addCondition(
marq.column(marq.uidMarque)
.plus(2)
.minus(4)
.bracket()
.times(6)
.bracket()
.dividedBy(3)
.is(-2));
allRows = dbQuery.getAllRows();
// database.print(allRows);
Assert.assertThat(allRows.size(), is(1));
marque = allRows.get(0).get(marq);
Assert.assertThat(marque.uidMarque.getValue().intValue(), is(1));
}
@Test
public void testACOS() throws SQLException {
Marque marq = new Marque();
DBQuery dbQuery = database.getDBQuery(marq);
dbQuery.addCondition(
marq.column(marq.uidMarque)
.isBetween(-1, 1)
);
dbQuery.addCondition(
marq.column(marq.uidMarque)
.arccos()
.is(0)
);
List<DBQueryRow> allRows = dbQuery.getAllRows();
// database.print(allRows);
Assert.assertThat(allRows.size(), is(1));
Marque marque = allRows.get(0).get(marq);
Assert.assertThat(marque.uidMarque.getValue().intValue(), is(1));
}
@Test
public void testASIN() throws SQLException {
Marque marq = new Marque();
DBQuery dbQuery = database.getDBQuery(marq);
dbQuery.addCondition(
marq.column(marq.uidMarque)
.isBetween(-1, 10)
);
dbQuery.addCondition(
marq.column(marq.uidMarque)
.times(0.3)
.arcsin()
.isBetween(0.3, 0.31)
);
List<DBQueryRow> allRows = dbQuery.getAllRows();
// database.print(allRows);
Assert.assertThat(allRows.size(), is(1));
Marque marque = allRows.get(0).get(marq);
Assert.assertThat(marque.uidMarque.getValue().intValue(), is(1));
}
@Test
public void testATAN() throws SQLException {
Marque marq = new Marque();
DBQuery dbQuery = database.getDBQuery(marq);
dbQuery.addCondition(
marq.column(marq.uidMarque)
.isBetween(-1, 10)
);
dbQuery.addCondition(
marq.column(marq.uidMarque)
.arctan()
.isBetween(0.78, 0.79)
);
List<DBQueryRow> allRows = dbQuery.getAllRows();
// database.print(allRows);
Assert.assertThat(allRows.size(), is(1));
Marque marque = allRows.get(0).get(marq);
Assert.assertThat(marque.uidMarque.getValue().intValue(), is(1));
}
@Test
public void testATAN2() throws SQLException {
Marque marq = new Marque();
DBQuery dbQuery = database.getDBQuery(marq);
dbQuery.addCondition(
marq.column(marq.uidMarque)
.isBetween(-1, 10)
);
dbQuery.addCondition(
marq.column(marq.uidMarque)
.arctan2(NumberExpression.value(2))
.isBetween(0.46, 0.47)
);
List<DBQueryRow> allRows = dbQuery.getAllRows();
// database.print(allRows);
Assert.assertThat(allRows.size(), is(1));
Marque marque = allRows.get(0).get(marq);
Assert.assertThat(marque.uidMarque.getValue().intValue(), is(1));
}
@Test
public void testCotangent() throws SQLException {
Marque marq = new Marque();
DBQuery dbQuery = database.getDBQuery(marq);
dbQuery.addCondition(
marq.column(marq.uidMarque)
.isBetween(-1, 10)
);
dbQuery.addCondition(
marq.column(marq.uidMarque)
.cotangent()
.isBetween(0.64, 0.65)
);
List<DBQueryRow> allRows = dbQuery.getAllRows();
// database.print(allRows);
Assert.assertThat(allRows.size(), is(1));
Marque marque = allRows.get(0).get(marq);
Assert.assertThat(marque.uidMarque.getValue().intValue(), is(1));
}
@Test
public void testCOSH() throws SQLException {
Marque marq = new Marque();
DBQuery dbQuery = database.getDBQuery(marq);
dbQuery.addCondition(
marq.column(marq.uidMarque)
.isBetween(-1, 10)
);
dbQuery.addCondition(
marq.column(marq.uidMarque)
.cosh()
.isBetween(1.54, 1.55)
);
List<DBQueryRow> allRows = dbQuery.getAllRows();
// database.print(allRows);
Assert.assertThat(allRows.size(), is(1));
Marque marque = allRows.get(0).get(marq);
Assert.assertThat(marque.uidMarque.getValue().intValue(), is(1));
}
@Test
public void testTANH() throws SQLException {
Marque marq = new Marque();
DBQuery dbQuery = database.getDBQuery(marq);
dbQuery.addCondition(
marq.column(marq.uidMarque)
.isBetween(-1, 10)
);
dbQuery.addCondition(
marq.column(marq.uidMarque)
.tanh()
.isLessThan(1)
);
List<DBQueryRow> allRows = dbQuery.getAllRows();
// database.print(allRows);
Assert.assertThat(allRows.size(), is(2));
Marque marque = allRows.get(0).get(marq);
Assert.assertThat(marque.uidMarque.getValue().intValue(), is(1));
}
@Test
public void testGreatestOf() throws SQLException {
Marque marq = new Marque();
DBQuery dbQuery = database.getDBQuery(marq);
dbQuery.addCondition(
NumberExpression.greatestOf(marq.column(marq.uidMarque), NumberExpression.value(900000), NumberExpression.value(800000))
.is(marq.column(marq.uidMarque))
);
List<DBQueryRow> allRows = dbQuery.getAllRows();
// database.print(allRows);
Assert.assertThat(allRows.size(), is(20));
Marque marque = allRows.get(0).get(marq);
Assert.assertThat(marque.uidMarque.getValue().intValue(), is(4893059));
}
@Test
public void testLeastOf() throws SQLException {
Marque marq = new Marque();
DBQuery dbQuery = database.getDBQuery(marq);
ArrayList<NumberExpression> arrayList = new ArrayList<NumberExpression>();
arrayList.add(marq.column(marq.uidMarque));
arrayList.add(NumberExpression.value(900000));
arrayList.add(NumberExpression.value(800000));
dbQuery.addCondition(
NumberExpression.leastOf(arrayList)
.is(marq.column(marq.uidMarque))
);
List<DBQueryRow> allRows = dbQuery.getAllRows();
// database.print(allRows);
Assert.assertThat(allRows.size(), is(2));
Marque marque = allRows.get(0).get(marq);
Assert.assertThat(marque.uidMarque.getValue().intValue(), is(1));
}
@Test
public void testAppend() throws SQLException {
Marque marq = new Marque();
DBQuery dbQuery = database.getDBQuery(marq);
dbQuery.addCondition(
marq.column(marq.uidMarque)
.append("$")
.isLike("%2$")
);
List<DBQueryRow> allRows = dbQuery.getAllRows();
// database.print(allRows);
Assert.assertThat(allRows.size(), is(3));
dbQuery = database.getDBQuery(marq);
dbQuery.addCondition(
marq.column(marq.uidMarque)
.append(StringExpression.value("$"))
.isLike("%2$")
);
allRows = dbQuery.getAllRows();
// database.print(allRows);
Assert.assertThat(allRows.size(), is(3));
}
@Test
public void testIsEven() throws SQLException {
Marque marq = new Marque();
DBQuery dbQuery = database.getDBQuery(marq);
dbQuery.addCondition(
marq.column(marq.uidMarque)
.isEven()
);
List<DBQueryRow> allRows = dbQuery.getAllRows();
database.print(allRows);
Assert.assertThat(allRows.size(), is(11));
}
@Test
public void testAbs() throws SQLException {
Marque marq = new Marque();
DBQuery dbQuery = database.getDBQuery(marq);
dbQuery.addCondition(
marq.column(marq.uidMarque)
.times(-2).abs().is(4)
);
List<DBQueryRow> allRows = dbQuery.getAllRows();
database.print(allRows);
Assert.assertThat(allRows.size(), is(1));
}
@Test
public void testDecimalPart() throws SQLException {
Marque marq = new Marque();
DBQuery dbQuery = database.getDBQuery(marq);
dbQuery.addCondition(
marq.column(marq.uidMarque)
.dividedBy(2).bracket().decimalPart().is(0.5)
);
List<DBQueryRow> allRows = dbQuery.getAllRows();
database.print(allRows);
Assert.assertThat(allRows.size(), is(11));
}
@Test
public void testIntegerPart() throws SQLException {
Marque marq = new Marque();
DBQuery dbQuery = database.getDBQuery(marq);
dbQuery.addCondition(
marq.column(marq.uidMarque)
.dividedBy(2).integerPart().is(1)
);
List<DBQueryRow> allRows = dbQuery.getAllRows();
database.print(allRows);
Assert.assertThat(allRows.size(), is(1));
}
@Test
public void testIsOdd() throws SQLException {
Marque marq = new Marque();
DBQuery dbQuery = database.getDBQuery(marq);
dbQuery.addCondition(
marq.column(marq.uidMarque)
.isOdd()
);
List<DBQueryRow> allRows = dbQuery.getAllRows();
database.print(allRows);
Assert.assertThat(allRows.size(), is(11));
}
@Test
public void testIsNotNull() throws SQLException {
Marque marq = new Marque();
DBQuery dbQuery = database.getDBQuery(marq);
dbQuery.addCondition(
marq.column(marq.updateCount)
.isNotNull()
);
List<DBQueryRow> allRows = dbQuery.getAllRows();
database.print(allRows);
Assert.assertThat(allRows.size(), is(20));
}
@Test
public void testIsNull() throws SQLException {
Marque marq = new Marque();
DBQuery dbQuery = database.getDBQuery(marq);
dbQuery.addCondition(
marq.column(marq.updateCount)
.isNull()
);
List<DBQueryRow> allRows = dbQuery.getAllRows();
database.print(allRows);
Assert.assertThat(allRows.size(), is(2));
}
@Test
public void testLeastOfNumberArray() throws SQLException {
Marque marq = new Marque();
DBQuery dbQuery = database.getDBQuery(marq);
dbQuery.addCondition(
NumberExpression.leastOf(1, 2, 3, 4, 5)
.is(marq.column(marq.uidMarque))
);
List<DBQueryRow> allRows = dbQuery.getAllRows();
// database.print(allRows);
Assert.assertThat(allRows.size(), is(1));
Marque marque = allRows.get(0).get(marq);
Assert.assertThat(marque.uidMarque.getValue().intValue(), is(1));
}
@Test
public void testCOS() throws SQLException {
Marque marq = new Marque();
DBQuery dbQuery = database.getDBQuery(marq);
dbQuery.addCondition(
marq.column(marq.uidMarque).minus(1).cos().is(1));
List<DBQueryRow> allRows = dbQuery.getAllRows();
// database.print(allRows);
Assert.assertThat(allRows.size(), is(1));
Marque marque = allRows.get(0).get(marq);
Assert.assertThat(marque.uidMarque.getValue().intValue(), is(1));
}
@Test
public void testEXP() throws SQLException {
CarCompany carCo = new CarCompany();
DBQuery dbQuery = database.getDBQuery(carCo);
dbQuery.addCondition(
carCo.column(carCo.uidCarCompany).exp().times(1000).trunc().is(7389));
List<DBQueryRow> allRows = dbQuery.getAllRows();
database.print(allRows);
Assert.assertThat(allRows.size(), is(1));
CarCompany carCompany = allRows.get(0).get(carCo);
Assert.assertThat(carCompany.uidCarCompany.getValue().intValue(), is(2));
}
public static class degreeRow extends CarCompany {
private static final long serialVersionUID = 1L;
@DBColumn
DBNumber degrees = new DBNumber(this.column(this.uidCarCompany).degrees());
@DBColumn
DBNumber radians = new DBNumber(this.column(this.uidCarCompany).degrees().radians());
@DBColumn
DBNumber tangent = new DBNumber(this.column(this.uidCarCompany).degrees().tan());
}
@Test
public void testDegrees() throws SQLException {
degreeRow carCo = new degreeRow();
DBQuery dbQuery = database.getDBQuery(carCo).setBlankQueryAllowed(true);
List<DBQueryRow> allRows = dbQuery.getAllRows();
database.print(allRows);
dbQuery.addCondition(
carCo.column(carCo.uidCarCompany).degrees().tan().isGreaterThan(0));
allRows = dbQuery.getAllRows();
database.print(allRows);
Assert.assertThat(allRows.size(), is(2));
for (CarCompany carCompany : dbQuery.getAllInstancesOf(carCo)) {
Assert.assertThat(Math.tan(Math.toDegrees(carCompany.uidCarCompany.getValue().doubleValue())) > 0,
is(true));
}
}
@Test
public void testRadians() throws SQLException {
CarCompany carCo = new CarCompany();
DBQuery dbQuery = database.getDBQuery(carCo);
dbQuery.addCondition(carCo.column(carCo.uidCarCompany).degrees().radians().degrees().tan().isGreaterThan(0));
List<DBQueryRow> allRows = dbQuery.getAllRows();
database.print(allRows);
Assert.assertThat(allRows.size(), is(2));
for (CarCompany carCompany : dbQuery.getAllInstancesOf(carCo)) {
Assert.assertThat(Math.tan(Math.toDegrees(carCompany.uidCarCompany.getValue().doubleValue())) > 0,
is(true));
}
}
@Test
public void testLength() throws SQLException {
CarCompany carCo = new CarCompany();
carCo.uidCarCompany.permittedValues(carCo.column(carCo.name).length().minus(1));
DBQuery dbQuery = database.getDBQuery(carCo);
List<DBQueryRow> allRows = dbQuery.getAllRows();
database.print(allRows);
Assert.assertThat(allRows.size(), is(1));
for (CarCompany carCompany : dbQuery.getAllInstancesOf(carCo)) {
Assert.assertThat(carCompany.uidCarCompany.getValue().intValue(),
is(4));
}
}
@Test
public void testLocationOf() throws SQLException {
CarCompany carCo = new CarCompany();
carCo.uidCarCompany.permittedValues(carCo.column(carCo.name).locationOf("ord"));
DBQuery dbQuery = database.getDBQuery(carCo);
List<DBQueryRow> allRows = dbQuery.getAllRows();
database.print(allRows);
Assert.assertThat(allRows.size(), is(1));
for (CarCompany carCompany : dbQuery.getAllInstancesOf(carCo)) {
Assert.assertThat(carCompany.uidCarCompany.getValue().intValue(),
is(2));
}
}
@Test
public void testLocationOfAsDBRowField() throws SQLException {
ExtendedCarCompany carCo = new ExtendedCarCompany();
// carCo.uidCarCompany.permittedValues(carCo.column(carCo.name).locationOf("ord"));
DBQuery dbQuery = database.getDBQuery(carCo);
dbQuery.setBlankQueryAllowed(true);
List<DBQueryRow> allRows = dbQuery.getAllRows();
database.print(allRows);
Assert.assertThat(allRows.size(), is(4));
for (ExtendedCarCompany carCompany : dbQuery.getAllInstancesOf(carCo)) {
System.out.println("LOCATION OF 'ORD': " + carCompany.locationOfORD.getValue().intValue() + " == " + carCompany.name.stringValue().indexOf("ord"));
Assert.assertThat(carCompany.locationOfORD.getValue().intValue(),
is(Matchers.isOneOf(0, carCompany.name.stringValue().indexOf("ord") + 1)));
}
}
public static class ExtendedCarCompany extends CarCompany {
public static final long serialVersionUID = 1L;
@DBColumn
DBNumber locationOfORD = new DBNumber(this.column(this.name).locationOf("ord"));
public ExtendedCarCompany() {
super();
}
}
@Test
public void testChoose() throws SQLException {
CarCompanyWithChoose carCo = new CarCompanyWithChoose();
DBQuery dbQuery = database.getDBQuery(carCo);
List<DBQueryRow> allRows = dbQuery.setBlankQueryAllowed(true).getAllRows();
database.print(allRows);
for (CarCompanyWithChoose carCompany : dbQuery.getAllInstancesOf(carCo)) {
if (carCompany.uidCarCompany.intValue() <= 0) {
Assert.assertThat(carCompany.chooseOnID.getValue(), is("too low"));
} else if (carCompany.uidCarCompany.intValue() == 1) {
Assert.assertThat(carCompany.chooseOnID.getValue(), is("ok"));
} else if (carCompany.uidCarCompany.intValue() == 2) {
Assert.assertThat(carCompany.chooseOnID.getValue(), is("high"));
} else {
Assert.assertThat(carCompany.chooseOnID.getValue(), is("too high"));
}
}
}
public static class CarCompanyWithChoose extends CarCompany {
public static final long serialVersionUID = 1L;
@DBColumn
DBString chooseOnID = new DBString(this.column(this.uidCarCompany).choose("too low", "ok", "high", "too high"));
public CarCompanyWithChoose() {
super();
}
}
}
| |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.common.settings;
import org.elasticsearch.cli.Command;
import org.elasticsearch.cli.ExitCodes;
import org.elasticsearch.cli.UserException;
import org.elasticsearch.core.Tuple;
import org.elasticsearch.env.Environment;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.containsString;
public class AddFileKeyStoreCommandTests extends KeyStoreCommandTestCase {
@Override
protected Command newCommand() {
return new AddFileKeyStoreCommand() {
@Override
protected Environment createEnv(Map<String, String> settings) throws UserException {
return env;
}
};
}
private Path createRandomFile() throws IOException {
int length = randomIntBetween(10, 20);
byte[] bytes = new byte[length];
for (int i = 0; i < length; ++i) {
bytes[i] = randomByte();
}
Path file = env.configFile().resolve(randomAlphaOfLength(16));
Files.write(file, bytes);
return file;
}
private void addFile(KeyStoreWrapper keystore, String setting, Path file, String password) throws Exception {
keystore.setFile(setting, Files.readAllBytes(file));
keystore.save(env.configFile(), password.toCharArray());
}
public void testMissingCreateWithEmptyPasswordWhenPrompted() throws Exception {
assumeFalse("Cannot create unprotected keystore on FIPS JVM", inFipsJvm());
String password = "";
Path file1 = createRandomFile();
terminal.addTextInput("y");
execute("foo", file1.toString());
assertSecureFile("foo", file1, password);
}
public void testMissingCreateWithEmptyPasswordWithoutPromptIfForced() throws Exception {
assumeFalse("Cannot create unprotected keystore on FIPS JVM", inFipsJvm());
String password = "";
Path file1 = createRandomFile();
execute("-f", "foo", file1.toString());
assertSecureFile("foo", file1, password);
}
public void testMissingNoCreate() throws Exception {
terminal.addSecretInput(randomFrom("", "keystorepassword"));
terminal.addTextInput("n"); // explicit no
execute("foo");
assertNull(KeyStoreWrapper.load(env.configFile()));
}
public void testOverwritePromptDefault() throws Exception {
String password = "keystorepassword";
Path file = createRandomFile();
KeyStoreWrapper keystore = createKeystore(password);
addFile(keystore, "foo", file, password);
terminal.addSecretInput(password);
terminal.addSecretInput(password);
terminal.addTextInput("");
execute("foo", "path/dne");
assertSecureFile("foo", file, password);
}
public void testOverwritePromptExplicitNo() throws Exception {
String password = "keystorepassword";
Path file = createRandomFile();
KeyStoreWrapper keystore = createKeystore(password);
addFile(keystore, "foo", file, password);
terminal.addSecretInput(password);
terminal.addTextInput("n"); // explicit no
execute("foo", "path/dne");
assertSecureFile("foo", file, password);
}
public void testOverwritePromptExplicitYes() throws Exception {
String password = "keystorepassword";
Path file1 = createRandomFile();
KeyStoreWrapper keystore = createKeystore(password);
addFile(keystore, "foo", file1, password);
terminal.addSecretInput(password);
terminal.addSecretInput(password);
terminal.addTextInput("y");
Path file2 = createRandomFile();
execute("foo", file2.toString());
assertSecureFile("foo", file2, password);
}
public void testOverwriteForceShort() throws Exception {
String password = "keystorepassword";
Path file1 = createRandomFile();
KeyStoreWrapper keystore = createKeystore(password);
addFile(keystore, "foo", file1, password);
Path file2 = createRandomFile();
terminal.addSecretInput(password);
terminal.addSecretInput(password);
execute("-f", "foo", file2.toString());
assertSecureFile("foo", file2, password);
}
public void testOverwriteForceLong() throws Exception {
String password = "keystorepassword";
Path file1 = createRandomFile();
KeyStoreWrapper keystore = createKeystore(password);
addFile(keystore, "foo", file1, password);
Path file2 = createRandomFile();
terminal.addSecretInput(password);
execute("--force", "foo", file2.toString());
assertSecureFile("foo", file2, password);
}
public void testForceDoesNotAlreadyExist() throws Exception {
String password = "keystorepassword";
createKeystore(password);
Path file = createRandomFile();
terminal.addSecretInput(password);
execute("--force", "foo", file.toString());
assertSecureFile("foo", file, password);
}
public void testMissingSettingName() throws Exception {
String password = "keystorepassword";
createKeystore(password);
terminal.addSecretInput(password);
UserException e = expectThrows(UserException.class, this::execute);
assertEquals(ExitCodes.USAGE, e.exitCode);
assertThat(e.getMessage(), containsString("Missing setting name"));
}
public void testMissingFileName() throws Exception {
String password = "keystorepassword";
createKeystore(password);
terminal.addSecretInput(password);
UserException e = expectThrows(UserException.class, () -> execute("foo"));
assertEquals(ExitCodes.USAGE, e.exitCode);
assertThat(e.getMessage(), containsString("settings and filenames must come in pairs"));
}
public void testFileDNE() throws Exception {
String password = "keystorepassword";
createKeystore(password);
terminal.addSecretInput(password);
UserException e = expectThrows(UserException.class, () -> execute("foo", "path/dne"));
assertEquals(ExitCodes.IO_ERROR, e.exitCode);
assertThat(e.getMessage(), containsString("File [path/dne] does not exist"));
}
public void testExtraArguments() throws Exception {
String password = "keystorepassword";
createKeystore(password);
Path file = createRandomFile();
terminal.addSecretInput(password);
UserException e = expectThrows(UserException.class, () -> execute("foo", file.toString(), "bar"));
assertEquals(e.getMessage(), ExitCodes.USAGE, e.exitCode);
assertThat(e.getMessage(), containsString("settings and filenames must come in pairs"));
}
public void testIncorrectPassword() throws Exception {
String password = "keystorepassword";
createKeystore(password);
Path file = createRandomFile();
terminal.addSecretInput("thewrongkeystorepassword");
UserException e = expectThrows(UserException.class, () -> execute("foo", file.toString()));
assertEquals(e.getMessage(), ExitCodes.DATA_ERROR, e.exitCode);
if (inFipsJvm()) {
assertThat(
e.getMessage(),
anyOf(
containsString("Provided keystore password was incorrect"),
containsString("Keystore has been corrupted or tampered with")
)
);
} else {
assertThat(e.getMessage(), containsString("Provided keystore password was incorrect"));
}
}
public void testAddToUnprotectedKeystore() throws Exception {
assumeFalse("Cannot open unprotected keystore on FIPS JVM", inFipsJvm());
String password = "";
Path file = createRandomFile();
KeyStoreWrapper keystore = createKeystore(password);
addFile(keystore, "foo", file, password);
terminal.addTextInput("");
// will not be prompted for a password
execute("foo", "path/dne");
assertSecureFile("foo", file, password);
}
public void testAddMultipleFiles() throws Exception {
final String password = "keystorepassword";
createKeystore(password);
final int n = randomIntBetween(1, 8);
final List<Tuple<String, Path>> settingFilePairs = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
settingFilePairs.add(Tuple.tuple("foo" + i, createRandomFile()));
}
terminal.addSecretInput(password);
execute(settingFilePairs.stream().flatMap(t -> Stream.of(t.v1(), t.v2().toString())).toArray(String[]::new));
for (int i = 0; i < n; i++) {
assertSecureFile(settingFilePairs.get(i).v1(), settingFilePairs.get(i).v2(), password);
}
}
}
| |
/*******************************************************************************
* Copyright 2011, 2012 Chris Banes.
*
* 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.yuntongxun.ecdemo.photoview;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.widget.ImageView;
public class PhotoView extends ImageView implements IPhotoView {
private final PhotoViewAttacher mAttacher;
private ScaleType mPendingScaleType;
public PhotoView(Context context) {
this(context, null);
}
public PhotoView(Context context, AttributeSet attr) {
this(context, attr, 0);
}
public PhotoView(Context context, AttributeSet attr, int defStyle) {
super(context, attr, defStyle);
super.setScaleType(ScaleType.MATRIX);
mAttacher = new PhotoViewAttacher(this);
if (null != mPendingScaleType) {
setScaleType(mPendingScaleType);
mPendingScaleType = null;
}
}
/**
* @deprecated use {@link #setRotationTo(float)}
*/
@Override
public void setPhotoViewRotation(float rotationDegree) {
mAttacher.setRotationTo(rotationDegree);
}
@Override
public void setRotationTo(float rotationDegree) {
mAttacher.setRotationTo(rotationDegree);
}
@Override
public void setRotationBy(float rotationDegree) {
mAttacher.setRotationBy(rotationDegree);
}
@Override
public boolean canZoom() {
return mAttacher.canZoom();
}
@Override
public RectF getDisplayRect() {
return mAttacher.getDisplayRect();
}
@Override
public Matrix getDisplayMatrix() {
return mAttacher.getDrawMatrix();
}
@Override
public boolean setDisplayMatrix(Matrix finalRectangle) {
return mAttacher.setDisplayMatrix(finalRectangle);
}
@Override
@Deprecated
public float getMinScale() {
return getMinimumScale();
}
@Override
public float getMinimumScale() {
return mAttacher.getMinimumScale();
}
@Override
@Deprecated
public float getMidScale() {
return getMediumScale();
}
@Override
public float getMediumScale() {
return mAttacher.getMediumScale();
}
@Override
@Deprecated
public float getMaxScale() {
return getMaximumScale();
}
@Override
public float getMaximumScale() {
return mAttacher.getMaximumScale();
}
@Override
public float getScale() {
return mAttacher.getScale();
}
@Override
public ScaleType getScaleType() {
return mAttacher.getScaleType();
}
@Override
public void setAllowParentInterceptOnEdge(boolean allow) {
mAttacher.setAllowParentInterceptOnEdge(allow);
}
@Override
@Deprecated
public void setMinScale(float minScale) {
setMinimumScale(minScale);
}
@Override
public void setMinimumScale(float minimumScale) {
mAttacher.setMinimumScale(minimumScale);
}
@Override
@Deprecated
public void setMidScale(float midScale) {
setMediumScale(midScale);
}
@Override
public void setMediumScale(float mediumScale) {
mAttacher.setMediumScale(mediumScale);
}
@Override
@Deprecated
public void setMaxScale(float maxScale) {
setMaximumScale(maxScale);
}
@Override
public void setMaximumScale(float maximumScale) {
mAttacher.setMaximumScale(maximumScale);
}
@Override
// setImageBitmap calls through to this method
public void setImageDrawable(Drawable drawable) {
super.setImageDrawable(drawable);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setImageResource(int resId) {
super.setImageResource(resId);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setImageURI(Uri uri) {
super.setImageURI(uri);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setOnMatrixChangeListener(PhotoViewAttacher.OnMatrixChangedListener listener) {
mAttacher.setOnMatrixChangeListener(listener);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mAttacher.setOnLongClickListener(l);
}
@Override
public void setOnPhotoTapListener(PhotoViewAttacher.OnPhotoTapListener listener) {
mAttacher.setOnPhotoTapListener(listener);
}
@Override
public PhotoViewAttacher.OnPhotoTapListener getOnPhotoTapListener() {
return mAttacher.getOnPhotoTapListener();
}
@Override
public void setOnViewTapListener(PhotoViewAttacher.OnViewTapListener listener) {
mAttacher.setOnViewTapListener(listener);
}
@Override
public PhotoViewAttacher.OnViewTapListener getOnViewTapListener() {
return mAttacher.getOnViewTapListener();
}
@Override
public void setScale(float scale) {
mAttacher.setScale(scale);
}
@Override
public void setScale(float scale, boolean animate) {
mAttacher.setScale(scale, animate);
}
@Override
public void setScale(float scale, float focalX, float focalY, boolean animate) {
mAttacher.setScale(scale, focalX, focalY, animate);
}
@Override
public void setScaleType(ScaleType scaleType) {
if (null != mAttacher) {
mAttacher.setScaleType(scaleType);
} else {
mPendingScaleType = scaleType;
}
}
@Override
public void setZoomable(boolean zoomable) {
mAttacher.setZoomable(zoomable);
}
@Override
public Bitmap getVisibleRectangleBitmap() {
return mAttacher.getVisibleRectangleBitmap();
}
@Override
public void setZoomTransitionDuration(int milliseconds) {
mAttacher.setZoomTransitionDuration(milliseconds);
}
@Override
public IPhotoView getIPhotoViewImplementation() {
return mAttacher;
}
@Override
public void setOnDoubleTapListener(GestureDetector.OnDoubleTapListener newOnDoubleTapListener) {
mAttacher.setOnDoubleTapListener(newOnDoubleTapListener);
}
@Override
protected void onDetachedFromWindow() {
mAttacher.cleanup();
super.onDetachedFromWindow();
}
}
| |
/*
* 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.daemon.support;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import org.apache.commons.daemon.Daemon;
import org.apache.commons.daemon.DaemonContext;
/**
* Implementation of the Daemon that allows running
* standard applications as daemons.
* The applications must have the mechanism to manage
* the application lifecycle.
*
*/
public class DaemonWrapper implements Daemon
{
private final static String ARGS = "args";
private final static String START_CLASS = "start";
private final static String START_METHOD = "start.method";
private final static String STOP_CLASS = "stop";
private final static String STOP_METHOD = "stop.method";
private final static String STOP_ARGS = "stop.args";
private String configFileName;
private final DaemonConfiguration config;
private final Invoker startup;
private final Invoker shutdown;
public DaemonWrapper()
{
config = new DaemonConfiguration();
startup = new Invoker();
shutdown = new Invoker();
}
/**
* Called from DaemonLoader on init stage.
* <p>
* Accepts the following configuration arguments:
* <ul>
* <li>-daemon-properties: - load DaemonConfiguration properties from the specified file to act as defaults</li>
* <li>-start: set start class name</li>
* <li>-start-method: set start method name</li>
* <li>-stop: set stop class name</li>
* <li>-stop-method: set stop method name</li>
* <li>-stop-argument: set optional argument to stop method</li>
* <li>Anything else is treated as a startup argument</li>
* </ul>
* <p>
* The following "-daemon-properties" are recognized:
* <ul>
* <li>args (startup argument)</li>
* <li>start</li>
* <li>start.method</li>
* <li>stop</li>
* <li>stop.method</li>
* <li>stop.args</li>
* </ul>
* These are used to set the corresponding item if it has not already been
* set by the command arguments. <b>However, note that args and stop.args are
* appended to any existing values.</b>
*/
@Override
public void init(final DaemonContext context)
throws Exception
{
final String[] args = context.getArguments();
if (args != null) {
int i;
// Parse our arguments and remove them
// from the final argument array we are
// passing to our child.
for (i = 0; i < args.length; i++) {
if (args[i].equals("--")) {
// Done with argument processing
break;
}
if (args[i].equals("-daemon-properties")) {
if (++i == args.length) {
throw new IllegalArgumentException(args[i - 1]);
}
configFileName = args[i];
}
else if (args[i].equals("-start")) {
if (++i == args.length) {
throw new IllegalArgumentException(args[i - 1]);
}
startup.setClassName(args[i]);
}
else if (args[i].equals("-start-method")) {
if (++i == args.length) {
throw new IllegalArgumentException(args[i - 1]);
}
startup.setMethodName(args[i]);
}
else if (args[i].equals("-stop")) {
if (++i == args.length) {
throw new IllegalArgumentException(args[i - 1]);
}
shutdown.setClassName(args[i]);
}
else if (args[i].equals("-stop-method")) {
if (++i == args.length) {
throw new IllegalArgumentException(args[i - 1]);
}
shutdown.setMethodName(args[i]);
}
else if (args[i].equals("-stop-argument")) {
if (++i == args.length) {
throw new IllegalArgumentException(args[i - 1]);
}
final String[] aa = new String[1];
aa[0] = args[i];
shutdown.addArguments(aa);
}
else {
// This is not our option.
// Everything else will be forwarded to the main
break;
}
}
if (args.length > i) {
final String[] copy = new String[args.length - i];
System.arraycopy(args, i, copy, 0, copy.length);
startup.addArguments(copy);
}
}
if (config.load(configFileName)) {
// Setup params if not set via cmdline.
startup.setClassName(config.getProperty(START_CLASS));
startup.setMethodName(config.getProperty(START_METHOD));
// Merge the config with command line arguments
startup.addArguments(config.getPropertyArray(ARGS));
shutdown.setClassName(config.getProperty(STOP_CLASS));
shutdown.setMethodName(config.getProperty(STOP_METHOD));
shutdown.addArguments(config.getPropertyArray(STOP_ARGS));
}
startup.validate();
shutdown.validate();
}
/**
*/
@Override
public void start()
throws Exception
{
startup.invoke();
}
/**
*/
@Override
public void stop()
throws Exception
{
shutdown.invoke();
}
/**
*/
@Override
public void destroy()
{
// Nothing for the moment
System.err.println("DaemonWrapper: instance " + this.hashCode() + " destroy");
}
// Internal class for wrapping the start/stop methods
static class Invoker
{
private String name;
private String call;
private String[] args;
private Method inst;
private Class<?> main;
protected Invoker()
{
}
protected void setClassName(final String name)
{
if (this.name == null) {
this.name = name;
}
}
protected void setMethodName(final String name)
{
if (this.call == null) {
this.call = name;
}
}
protected void addArguments(final String[] args)
{
if (args != null) {
final ArrayList<String> aa = new ArrayList<>();
if (this.args != null) {
aa.addAll(Arrays.asList(this.args));
}
aa.addAll(Arrays.asList(args));
this.args = aa.toArray(DaemonConfiguration.EMPTY_STRING_ARRAY);
}
}
protected void invoke()
throws Exception
{
if (name.equals("System") && call.equals("exit")) {
// Just call a System.exit()
// The start method was probably installed
// a shutdown hook.
System.exit(0);
}
else {
Object obj = null;
if ((inst.getModifiers() & Modifier.STATIC) == 0) {
// We only need object instance for non-static methods.
obj = main.getConstructor().newInstance();
}
final Object[] arg = new Object[1];
arg[0] = args;
inst.invoke(obj, arg);
}
}
// Load the class using reflection
protected void validate()
throws Exception
{
/* Check the class name */
if (name == null) {
name = "System";
call = "exit";
return;
}
if (args == null) {
args = new String[0];
}
if (call == null) {
call = "main";
}
// Get the ClassLoader loading this class
final ClassLoader cl = DaemonWrapper.class.getClassLoader();
if (cl == null) {
throw new NullPointerException("Cannot retrieve ClassLoader instance");
}
final Class<?>[] ca = new Class[1];
ca[0] = args.getClass();
// Find the required class
main = cl.loadClass(name);
if (main == null) {
throw new ClassNotFoundException(name);
}
// Find the required method.
// NoSuchMethodException will be thrown if matching method
// is not found.
inst = main.getMethod(call, ca);
}
}
}
| |
package net.anotheria.moskito.core.predefined;
import net.anotheria.moskito.core.producers.AbstractStats;
import net.anotheria.moskito.core.stats.Interval;
import net.anotheria.moskito.core.stats.StatValue;
import net.anotheria.moskito.core.stats.TimeUnit;
import net.anotheria.moskito.core.stats.impl.StatValueFactory;
import java.util.ArrayList;
import java.util.List;
/**
* Stats for a QueuingSystem like the Enterpise Queue Processor in ano-prise.
*/
public class QueuingSystemStats extends AbstractStats {
/**
* Stat definition enum.
*/
static enum StatDef{
SERVERS_SIZE("SS"),
/**
* Size of the queue.
*/
QUEUE_SIZE("QS"),
/**
* Number of arrived elements,
*/
ARRIVED("Arr"),
/**
* Number of served elements.
*/
SERVICED("Serv"),
/**
* Number of errors.
*/
ERRORS("Err"),
/**
* Number of waiting times.
*/
WAITED("Wait"),
/**
* Number of thrown away elements.
*/
THROWN_AWAY("Thr"),
/**
* Time spent by item waiting for service.
*/
WAITING_TIME("WT"),
/**
* Min time spent by an item waiting for service.
*/
WAITING_TIME_MIN("WTm"),
/**
* Max time spent by an item waiting for service.
*/
WAITING_TIME_MAX("WTM"),
/**
* Average time spent by an item waiting for service.
*/
WAITING_TIME_AVG("WTA"),
/**
* Time spent by the item in servicing.
*/
SERVICE_TIME("ST"),
/**
* Min time spent by the item in servicing.
*/
SERVICE_TIME_MIN("STm"),
/**
* Max time spent by the item in servicing.
*/
SERVICE_TIME_MAX("STM"),
/**
* Average time spent in service
*/
SERVICE_TIME_AVG("STA");
/**
* Name of the stat object.
*/
private String statName;
private StatDef(String aStatName){
statName = aStatName;
}
public String getStatName(){
return statName;
}
public String getStatLabel(){
return " " + statName + ": ";
}
public static List<String> getStatNames(){
List<String> ret = new ArrayList<String>(StatDef.values().length);
for(StatDef v: StatDef.values())
ret.add(v.getStatName());
return ret;
}
}
/**
* Min size value.
*/
public static final long MIN_SIZE_DEFAULT = Long.MAX_VALUE;
/**
* Max size value.
*/
public static final long MAX_SIZE_DEFAULT = 0L;
/**
* Number of processors that process queue elements.
*/
private StatValue serversSize;
/**
* Size of the queue.
*/
private StatValue queueSize;
/**
* Number of arrived elements.
*/
private StatValue arrived;
/**
* Number of served elements.
*/
private StatValue serviced;
/**
* Number of serving errors.
*/
private StatValue errors;
/**
* Number of waited elements.
*/
private StatValue waited;
/**
* Number of throwed away elements due to overflow.
*/
private StatValue throwedAway;
/**
* Time spent in the queue before processing started.
*/
private StatValue waitingTime;
/**
* Min time spent in the queue before processing started.
*/
private StatValue waitingTimeMin;
/**
* Max time spent in the queue before processing started.
*/
private StatValue waitingTimeMax;
/**
* Time spent in servicing the requests.
*/
private StatValue servicingTime;
/**
* Min time spent in servicing the requests.
*/
private StatValue servicingTimeMin;
/**
* Max time spent in servicing the requests.
*/
private StatValue servicingTimeMax;
/**
* Name of the cache.
*/
private String name;
public QueuingSystemStats(){
this("unnamed", Constants.getDefaultIntervals());
}
public QueuingSystemStats(String name){
this(name, Constants.getDefaultIntervals());
}
public QueuingSystemStats(String aName, Interval[] selectedIntervals){
Long longPattern = Long.valueOf(0);
name = aName;
serversSize = StatValueFactory.createStatValue(longPattern, "serversSize", selectedIntervals);
queueSize = StatValueFactory.createStatValue(longPattern, "queueSize", selectedIntervals);
arrived = StatValueFactory.createStatValue(longPattern, "arrived", selectedIntervals);
serviced = StatValueFactory.createStatValue(longPattern, "serviced", selectedIntervals);
errors = StatValueFactory.createStatValue(longPattern, "errors", selectedIntervals);
waited = StatValueFactory.createStatValue(longPattern, "waited", selectedIntervals);
throwedAway = StatValueFactory.createStatValue(longPattern, "throwedAway", selectedIntervals);
waitingTime = StatValueFactory.createStatValue(longPattern, "waitingTime", selectedIntervals);
waitingTimeMin = StatValueFactory.createStatValue(longPattern, "waitingTimeMin", selectedIntervals);
waitingTimeMin.setDefaultValueAsLong(Constants.MIN_TIME_DEFAULT);
waitingTimeMin.reset();
waitingTimeMax = StatValueFactory.createStatValue(longPattern, "waitingTimeMax", selectedIntervals);
waitingTimeMax.setDefaultValueAsLong(Constants.MAX_TIME_DEFAULT);
waitingTimeMax.reset();
servicingTime = StatValueFactory.createStatValue(longPattern, "servicingTime", selectedIntervals);
servicingTimeMin = StatValueFactory.createStatValue(longPattern, "servicingTimeMin", selectedIntervals);
servicingTimeMin.setDefaultValueAsLong(Constants.MIN_TIME_DEFAULT);
servicingTimeMin.reset();
servicingTimeMax = StatValueFactory.createStatValue(longPattern, "servicingTimeMax", selectedIntervals);
servicingTimeMax.setDefaultValueAsLong(Constants.MAX_TIME_DEFAULT);
servicingTimeMax.reset();
}
public void setServersSize(int size){
serversSize.setValueAsLong(size);
}
public long getServersSize(String intervalName){
return serversSize.getValueAsLong();
}
public void setQueueSize(int size){
queueSize.setValueAsLong(size);
}
public long getQueueSize(String intervalName){
return queueSize.getValueAsLong();
}
public void addArrived(){
arrived.increase();
}
public long getArrived(String intervalName){
return arrived.getValueAsLong(intervalName);
}
public void addServiced(){
serviced.increase();
}
public long getServiced(String intervalName){
return serviced.getValueAsLong(intervalName);
}
public void addError(){
errors.increase();
}
public long getErrors(String intervalName){
return errors.getValueAsLong(intervalName);
}
public void addWaited(){
waited.increase();
}
public long getWaited(String intervalName){
return waited.getValueAsLong(intervalName);
}
public void addThrowedAway(){
throwedAway.increase();
}
public long getThrowedAway(String intervalName){
return throwedAway.getValueAsLong(intervalName);
}
public void addWaitingTime(long time){
waitingTime.increaseByLong(time);
waitingTimeMin.setValueIfLesserThanCurrentAsLong(time);
waitingTimeMax.setValueIfGreaterThanCurrentAsLong(time);
}
public long getWaitingTime(String intervalName){
return waitingTime.getValueAsLong(intervalName);
}
public long getWaitingTimeMin(String intervalName){
return waitingTimeMin.getValueAsLong(intervalName);
}
public long getWaitingTimeMax(String intervalName){
return waitingTimeMax.getValueAsLong(intervalName);
}
public long getWaitingTimeAverage(String intervalName){
long waitedVal = waited.getValueAsLong(intervalName);
return waitedVal > 0? waitingTime.getValueAsLong(intervalName) / waitedVal: Constants.AVERAGE_TIME_DEFAULT;
}
public void addServicingTime(long time){
servicingTime.increaseByLong(time);
servicingTimeMin.setValueIfLesserThanCurrentAsLong(time);
servicingTimeMax.setValueIfGreaterThanCurrentAsLong(time);
}
public long getServicingTime(String intervalName){
return servicingTime.getValueAsLong(intervalName);
}
public long getServicingTimeMin(String intervalName){
return servicingTimeMin.getValueAsLong(intervalName);
}
public long getServicingTimeMax(String intervalName){
return servicingTimeMax.getValueAsLong(intervalName);
}
public long getServicingTimeAverage(String intervalName){
long servicedVal = serviced.getValueAsLong(intervalName);
return servicedVal > 0? servicingTime.getValueAsLong(intervalName) / servicedVal: Constants.AVERAGE_TIME_DEFAULT;
}
public String getName(){
return name;
}
@Override
public List<String> getAvailableValueNames() {
return StatDef.getStatNames();
}
private String transformMinTimeNanos(long minTime, TimeUnit timeUnit){
if (minTime == Constants.MIN_TIME_DEFAULT)
return "NoR";
return "" + timeUnit.transformNanos(minTime);
}
private String transformMaxTimeNanos(long maxTime, TimeUnit timeUnit){
if (maxTime == Constants.MAX_TIME_DEFAULT)
return "NoR";
return "" + timeUnit.transformNanos(maxTime);
}
private String transformAverageTimeNanos(long maxTime, TimeUnit timeUnit){
if (maxTime == Constants.AVERAGE_TIME_DEFAULT)
return "NoR";
return "" + timeUnit.transformNanos(maxTime);
}
@Override public String toStatsString(String intervalName, TimeUnit timeUnit) {
StringBuilder b = new StringBuilder();
b.append(getName()).append(' ');
b.append(StatDef.SERVERS_SIZE.getStatLabel()).append(getServersSize(intervalName));
b.append(StatDef.QUEUE_SIZE.getStatLabel()).append(getQueueSize(intervalName));
b.append(StatDef.ARRIVED.getStatLabel()).append(getArrived(intervalName));
b.append(StatDef.SERVICED.getStatLabel()).append(getServiced(intervalName));
b.append(StatDef.ERRORS.getStatLabel()).append(getErrors(intervalName));
b.append(StatDef.WAITED.getStatLabel()).append(getWaited(intervalName));
b.append(StatDef.THROWN_AWAY.getStatLabel()).append(getThrowedAway(intervalName));
b.append(StatDef.WAITING_TIME.getStatLabel()).append(timeUnit.transformNanos(getWaitingTime(intervalName)));
b.append(StatDef.WAITING_TIME_MIN.getStatLabel()).append(transformMinTimeNanos(getWaitingTimeMin(intervalName), timeUnit));
b.append(StatDef.WAITING_TIME_MAX.getStatLabel()).append(transformMaxTimeNanos(getWaitingTimeMax(intervalName),timeUnit));
b.append(StatDef.WAITING_TIME_AVG.getStatLabel()).append(transformAverageTimeNanos(getWaitingTimeAverage(intervalName), timeUnit));
b.append(StatDef.SERVICE_TIME.getStatLabel()).append(timeUnit.transformNanos(getServicingTime(intervalName)));
b.append(StatDef.SERVICE_TIME_MIN.getStatLabel()).append(transformMinTimeNanos(getServicingTimeMin(intervalName), timeUnit));
b.append(StatDef.SERVICE_TIME_MAX.getStatLabel()).append(transformMaxTimeNanos(getServicingTimeMax(intervalName),timeUnit));
b.append(StatDef.SERVICE_TIME_AVG.getStatLabel()).append(transformAverageTimeNanos(getServicingTimeAverage(intervalName), timeUnit));
return b.toString();
}
@Override public String getValueByNameAsString(String valueName, String intervalName, TimeUnit timeUnit){
if (valueName==null || valueName.equals(""))
throw new AssertionError("Value name can not be empty");
if (valueName.equals(StatDef.SERVERS_SIZE.getStatName()))
return ""+getServersSize(intervalName);
if (valueName.equals(StatDef.QUEUE_SIZE.getStatName()))
return ""+getQueueSize(intervalName);
if (valueName.equals(StatDef.ARRIVED.getStatName()))
return ""+getArrived(intervalName);
if (valueName.equals(StatDef.SERVICED.getStatName()))
return ""+getServiced(intervalName);
if (valueName.equals(StatDef.ERRORS.getStatName()))
return ""+getErrors(intervalName);
if (valueName.equals(StatDef.WAITED.getStatName()))
return ""+getWaited(intervalName);
if (valueName.equals(StatDef.THROWN_AWAY.getStatName()))
return ""+getThrowedAway(intervalName);
if (valueName.equals(StatDef.WAITING_TIME.getStatName()))
return ""+timeUnit.transformNanos(getWaitingTime(intervalName));
if (valueName.equals(StatDef.WAITING_TIME_MIN.getStatName()))
return transformMinTimeNanos(getWaitingTimeMin(intervalName), timeUnit);
if (valueName.equals(StatDef.WAITING_TIME_MAX.getStatName()))
return transformMaxTimeNanos(getWaitingTimeMax(intervalName), timeUnit);
if (valueName.equals(StatDef.WAITING_TIME_AVG.getStatName()))
return transformAverageTimeNanos(getWaitingTimeAverage(intervalName), timeUnit);
if (valueName.equals(StatDef.SERVICE_TIME.getStatName()))
return ""+timeUnit.transformNanos(getServicingTime(intervalName));
if (valueName.equals(StatDef.SERVICE_TIME_MIN.getStatName()))
return transformMinTimeNanos(getServicingTimeMin(intervalName), timeUnit);
if (valueName.equals(StatDef.SERVICE_TIME_MAX.getStatName()))
return transformMaxTimeNanos(getServicingTimeMax(intervalName), timeUnit);
if (valueName.equals(StatDef.SERVICE_TIME_AVG.getStatName()))
return transformAverageTimeNanos(getServicingTimeAverage(intervalName), timeUnit);
return super.getValueByNameAsString(valueName, intervalName, timeUnit);
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.avs.fluent.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.avs.models.ScriptExecutionParameter;
import com.azure.resourcemanager.avs.models.ScriptExecutionProvisioningState;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.Map;
/** Properties of a user-invoked script. */
@Fluent
public final class ScriptExecutionProperties {
@JsonIgnore private final ClientLogger logger = new ClientLogger(ScriptExecutionProperties.class);
/*
* A reference to the script cmdlet resource if user is running a AVS
* script
*/
@JsonProperty(value = "scriptCmdletId")
private String scriptCmdletId;
/*
* Parameters the script will accept
*/
@JsonProperty(value = "parameters")
private List<ScriptExecutionParameter> parameters;
/*
* Parameters that will be hidden/not visible to ARM, such as passwords and
* credentials
*/
@JsonProperty(value = "hiddenParameters")
private List<ScriptExecutionParameter> hiddenParameters;
/*
* Error message if the script was able to run, but if the script itself
* had errors or powershell threw an exception
*/
@JsonProperty(value = "failureReason")
private String failureReason;
/*
* Time limit for execution
*/
@JsonProperty(value = "timeout", required = true)
private String timeout;
/*
* Time to live for the resource. If not provided, will be available for 60
* days
*/
@JsonProperty(value = "retention")
private String retention;
/*
* Time the script execution was submitted
*/
@JsonProperty(value = "submittedAt", access = JsonProperty.Access.WRITE_ONLY)
private OffsetDateTime submittedAt;
/*
* Time the script execution was started
*/
@JsonProperty(value = "startedAt", access = JsonProperty.Access.WRITE_ONLY)
private OffsetDateTime startedAt;
/*
* Time the script execution was finished
*/
@JsonProperty(value = "finishedAt", access = JsonProperty.Access.WRITE_ONLY)
private OffsetDateTime finishedAt;
/*
* The state of the script execution resource
*/
@JsonProperty(value = "provisioningState", access = JsonProperty.Access.WRITE_ONLY)
private ScriptExecutionProvisioningState provisioningState;
/*
* Standard output stream from the powershell execution
*/
@JsonProperty(value = "output")
private List<String> output;
/*
* User-defined dictionary.
*/
@JsonProperty(value = "namedOutputs")
@JsonInclude(value = JsonInclude.Include.NON_NULL, content = JsonInclude.Include.ALWAYS)
private Map<String, Object> namedOutputs;
/*
* Standard information out stream from the powershell execution
*/
@JsonProperty(value = "information", access = JsonProperty.Access.WRITE_ONLY)
private List<String> information;
/*
* Standard warning out stream from the powershell execution
*/
@JsonProperty(value = "warnings", access = JsonProperty.Access.WRITE_ONLY)
private List<String> warnings;
/*
* Standard error output stream from the powershell execution
*/
@JsonProperty(value = "errors", access = JsonProperty.Access.WRITE_ONLY)
private List<String> errors;
/**
* Get the scriptCmdletId property: A reference to the script cmdlet resource if user is running a AVS script.
*
* @return the scriptCmdletId value.
*/
public String scriptCmdletId() {
return this.scriptCmdletId;
}
/**
* Set the scriptCmdletId property: A reference to the script cmdlet resource if user is running a AVS script.
*
* @param scriptCmdletId the scriptCmdletId value to set.
* @return the ScriptExecutionProperties object itself.
*/
public ScriptExecutionProperties withScriptCmdletId(String scriptCmdletId) {
this.scriptCmdletId = scriptCmdletId;
return this;
}
/**
* Get the parameters property: Parameters the script will accept.
*
* @return the parameters value.
*/
public List<ScriptExecutionParameter> parameters() {
return this.parameters;
}
/**
* Set the parameters property: Parameters the script will accept.
*
* @param parameters the parameters value to set.
* @return the ScriptExecutionProperties object itself.
*/
public ScriptExecutionProperties withParameters(List<ScriptExecutionParameter> parameters) {
this.parameters = parameters;
return this;
}
/**
* Get the hiddenParameters property: Parameters that will be hidden/not visible to ARM, such as passwords and
* credentials.
*
* @return the hiddenParameters value.
*/
public List<ScriptExecutionParameter> hiddenParameters() {
return this.hiddenParameters;
}
/**
* Set the hiddenParameters property: Parameters that will be hidden/not visible to ARM, such as passwords and
* credentials.
*
* @param hiddenParameters the hiddenParameters value to set.
* @return the ScriptExecutionProperties object itself.
*/
public ScriptExecutionProperties withHiddenParameters(List<ScriptExecutionParameter> hiddenParameters) {
this.hiddenParameters = hiddenParameters;
return this;
}
/**
* Get the failureReason property: Error message if the script was able to run, but if the script itself had errors
* or powershell threw an exception.
*
* @return the failureReason value.
*/
public String failureReason() {
return this.failureReason;
}
/**
* Set the failureReason property: Error message if the script was able to run, but if the script itself had errors
* or powershell threw an exception.
*
* @param failureReason the failureReason value to set.
* @return the ScriptExecutionProperties object itself.
*/
public ScriptExecutionProperties withFailureReason(String failureReason) {
this.failureReason = failureReason;
return this;
}
/**
* Get the timeout property: Time limit for execution.
*
* @return the timeout value.
*/
public String timeout() {
return this.timeout;
}
/**
* Set the timeout property: Time limit for execution.
*
* @param timeout the timeout value to set.
* @return the ScriptExecutionProperties object itself.
*/
public ScriptExecutionProperties withTimeout(String timeout) {
this.timeout = timeout;
return this;
}
/**
* Get the retention property: Time to live for the resource. If not provided, will be available for 60 days.
*
* @return the retention value.
*/
public String retention() {
return this.retention;
}
/**
* Set the retention property: Time to live for the resource. If not provided, will be available for 60 days.
*
* @param retention the retention value to set.
* @return the ScriptExecutionProperties object itself.
*/
public ScriptExecutionProperties withRetention(String retention) {
this.retention = retention;
return this;
}
/**
* Get the submittedAt property: Time the script execution was submitted.
*
* @return the submittedAt value.
*/
public OffsetDateTime submittedAt() {
return this.submittedAt;
}
/**
* Get the startedAt property: Time the script execution was started.
*
* @return the startedAt value.
*/
public OffsetDateTime startedAt() {
return this.startedAt;
}
/**
* Get the finishedAt property: Time the script execution was finished.
*
* @return the finishedAt value.
*/
public OffsetDateTime finishedAt() {
return this.finishedAt;
}
/**
* Get the provisioningState property: The state of the script execution resource.
*
* @return the provisioningState value.
*/
public ScriptExecutionProvisioningState provisioningState() {
return this.provisioningState;
}
/**
* Get the output property: Standard output stream from the powershell execution.
*
* @return the output value.
*/
public List<String> output() {
return this.output;
}
/**
* Set the output property: Standard output stream from the powershell execution.
*
* @param output the output value to set.
* @return the ScriptExecutionProperties object itself.
*/
public ScriptExecutionProperties withOutput(List<String> output) {
this.output = output;
return this;
}
/**
* Get the namedOutputs property: User-defined dictionary.
*
* @return the namedOutputs value.
*/
public Map<String, Object> namedOutputs() {
return this.namedOutputs;
}
/**
* Set the namedOutputs property: User-defined dictionary.
*
* @param namedOutputs the namedOutputs value to set.
* @return the ScriptExecutionProperties object itself.
*/
public ScriptExecutionProperties withNamedOutputs(Map<String, Object> namedOutputs) {
this.namedOutputs = namedOutputs;
return this;
}
/**
* Get the information property: Standard information out stream from the powershell execution.
*
* @return the information value.
*/
public List<String> information() {
return this.information;
}
/**
* Get the warnings property: Standard warning out stream from the powershell execution.
*
* @return the warnings value.
*/
public List<String> warnings() {
return this.warnings;
}
/**
* Get the errors property: Standard error output stream from the powershell execution.
*
* @return the errors value.
*/
public List<String> errors() {
return this.errors;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (parameters() != null) {
parameters().forEach(e -> e.validate());
}
if (hiddenParameters() != null) {
hiddenParameters().forEach(e -> e.validate());
}
if (timeout() == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
"Missing required property timeout in model ScriptExecutionProperties"));
}
}
}
| |
/**
* Sencha GXT 4.0.1 - Sencha for GWT
* Copyright (c) 2006-2016, Sencha Inc.
*
* licensing@sencha.com
* http://www.sencha.com/products/gxt/license/
*
* ================================================================================
* Evaluation/Trial License
* ================================================================================
* This version of Sencha GXT is licensed commercially for a limited period for
* evaluation purposes only. Production use or use beyond the applicable evaluation
* period is prohibited under this license.
*
* Please see the Sencha GXT Licensing page at:
* http://www.sencha.com/products/gxt/license/
*
* For clarification or additional options, please contact:
* licensing@sencha.com
* ================================================================================
*
*
*
*
*
*
*
* ================================================================================
* Disclaimer
* ================================================================================
* THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND
* REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE
* IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY,
* FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE AND
* THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING.
* ================================================================================
*/
package com.sencha.gxt.explorer.client.forms;
import java.util.Date;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.DateTimeFormat.PredefinedFormat;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;
import com.sencha.gxt.core.client.util.DateWrapper;
import com.sencha.gxt.core.client.util.ToggleGroup;
import com.sencha.gxt.data.shared.ListStore;
import com.sencha.gxt.examples.resources.client.TestData;
import com.sencha.gxt.examples.resources.client.model.Stock;
import com.sencha.gxt.examples.resources.client.model.StockProperties;
import com.sencha.gxt.explorer.client.app.ui.ExampleContainer;
import com.sencha.gxt.explorer.client.model.Example.Detail;
import com.sencha.gxt.widget.core.client.event.ParseErrorEvent;
import com.sencha.gxt.widget.core.client.form.CheckBox;
import com.sencha.gxt.widget.core.client.form.ComboBox;
import com.sencha.gxt.widget.core.client.form.DateField;
import com.sencha.gxt.widget.core.client.form.DoubleSpinnerField;
import com.sencha.gxt.widget.core.client.form.IntegerField;
import com.sencha.gxt.widget.core.client.form.Radio;
import com.sencha.gxt.widget.core.client.form.TextArea;
import com.sencha.gxt.widget.core.client.form.TimeField;
import com.sencha.gxt.widget.core.client.form.validator.MinDateValidator;
import com.sencha.gxt.widget.core.client.form.validator.MinLengthValidator;
import com.sencha.gxt.widget.core.client.info.Info;
@Detail(
name = "Forms Example (UiBinder)",
category = "Forms",
icon = "formsexampleuibinder",
classes = {
Stock.class,
StockProperties.class
},
files = "FormsUiBinderExample.ui.xml",
minHeight = FormsUiBinderExample.MIN_HEIGHT,
minWidth = FormsUiBinderExample.MIN_WIDTH
)
public class FormsUiBinderExample implements IsWidget, EntryPoint {
interface MyUiBinder extends UiBinder<Widget, FormsUiBinderExample> {
}
protected static final int MIN_HEIGHT = 940;
protected static final int MIN_WIDTH = 360;
private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class);
private Widget widget;
StockProperties properties = GWT.create(StockProperties.class);
ListStore<Stock> store = new ListStore<Stock>(properties.key());
@UiField(provided = true)
ComboBox<Stock> combo = new ComboBox<Stock>(store, properties.nameLabel());
@UiField
DateField date;
@UiField
Radio radio;
@UiField
Radio radio2;
@UiField
TextArea description;
@UiField
DoubleSpinnerField spinnerField;
@UiField
IntegerField age;
@UiField(provided = true)
Date minValue = new DateWrapper().clearTime().addHours(8).asDate();
@UiField(provided = true)
Date maxValue = new DateWrapper().clearTime().addHours(18).addSeconds(1).asDate();
@UiField
TimeField time;
@Override
public Widget asWidget() {
if (widget == null) {
store.addAll(TestData.getStocks());
widget = uiBinder.createAndBindUi(this);
time.setFormat(DateTimeFormat.getFormat("hh:mm a"));
combo.addValueChangeHandler(new ValueChangeHandler<Stock>() {
@Override
public void onValueChange(ValueChangeEvent<Stock> event) {
Info.display("Selected", "You selected " + event.getValue());
}
});
date.addValidator(new MinDateValidator(new Date()));
description.addValidator(new MinLengthValidator(10));
spinnerField.setIncrement(.1d);
spinnerField.setMinValue(-10d);
spinnerField.setMaxValue(10d);
spinnerField.getPropertyEditor().setFormat(NumberFormat.getFormat("0.0"));
spinnerField.addValueChangeHandler(new ValueChangeHandler<Double>() {
@Override
public void onValueChange(ValueChangeEvent<Double> event) {
Info.display("Duration Changed",
"Duration changed to " + event.getValue() == null ? "nothing" : event.getValue() + "");
}
});
// set name on radios or use toggle group
ToggleGroup toggle = new ToggleGroup();
toggle.add(radio);
toggle.add(radio2);
toggle.addValueChangeHandler(new ValueChangeHandler<HasValue<Boolean>>() {
@Override
public void onValueChange(ValueChangeEvent<HasValue<Boolean>> event) {
ToggleGroup group = (ToggleGroup) event.getSource();
Radio radio = (Radio) group.getValue();
Info.display("Color Changed", "You selected " + radio.getBoxLabel());
}
});
}
return widget;
}
@UiHandler("firstName")
public void firstNameChanged(ValueChangeEvent<String> event) {
Info.display("Value Changed", "First name changed to " + event.getValue() == null ? "blank" : event.getValue());
}
@UiHandler("age")
public void onAgeParseError(ParseErrorEvent event) {
Info.display("Parse Error", event.getErrorValue() + " could not be parsed as a number");
}
@UiHandler("date")
public void onDateParseError(ParseErrorEvent event) {
Info.display("Parse Error", event.getErrorValue() + " could not be parsed as a date");
}
@UiHandler("date")
public void onDateChanged(ValueChangeEvent<Date> event) {
String v = event.getValue() == null ? "nothing" : DateTimeFormat.getFormat(PredefinedFormat.DATE_MEDIUM).format(
event.getValue());
Info.display("Selected", "You selected " + v);
}
@UiHandler("spinnerField")
public void onSpinChange(SelectionEvent<Double> event) {
String msg = "nothing";
if (event.getSelectedItem() != null) {
msg = spinnerField.getPropertyEditor().render(event.getSelectedItem());
}
Info.display("Spin Change", "Current value changed to " + msg);
}
@UiHandler({"check1", "check2", "check3"})
public void onMusicChange(ValueChangeEvent<Boolean> event) {
CheckBox check = (CheckBox) event.getSource();
Info.display("Music Changed", check.getBoxLabel() + " " + (event.getValue() ? "selected" : "not selected"));
}
@UiHandler("time")
public void onTimeParseError(ParseErrorEvent event) {
Info.display("Parse Error", event.getErrorValue() + " could not be parsed as a valid time.");
}
@Override
public void onModuleLoad() {
new ExampleContainer(this)
.setMinHeight(MIN_HEIGHT)
.setMinWidth(MIN_WIDTH)
.doStandalone();
}
}
| |
/*
* Copyright 2013 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 com.jayway.restassured.config;
import org.apache.commons.lang3.Validate;
import java.util.HashMap;
import java.util.Map;
/**
* Allows you to configure properties of XML and HTML parsing.
*/
public class XmlConfig implements Config {
private final Map<String, Object> properties;
private final Map<String, Boolean> features;
private final Map<String, String> declaredNamespaces;
private final boolean namespaceAware;
private final boolean isUserConfigured;
/**
* Create a new instance of XmlConfig without any features and that is namespace unaware.
*/
public XmlConfig() {
this(new HashMap<String, Boolean>(), new HashMap<String, String>(), new HashMap<String, Object>(), false, false);
}
private XmlConfig(Map<String, Boolean> features, Map<String, String> declaredNamespaces, Map<String, Object> properties,
boolean namespaceAware, boolean isUserConfigured) {
Validate.notNull(features, "Features cannot be null");
Validate.notNull(declaredNamespaces, "Declared namespaces cannot be null");
Validate.notNull(properties, "Properties cannot be null");
this.namespaceAware = namespaceAware;
this.features = features;
this.declaredNamespaces = declaredNamespaces;
this.properties = properties;
this.isUserConfigured = isUserConfigured;
}
/**
* @return A map containing features that will be used by the underlying {@link groovy.util.XmlSlurper}.
* @see org.xml.sax.XMLReader#setFeature(java.lang.String, boolean)
*/
public Map<String, Boolean> features() {
return new HashMap<String, Boolean>(features);
}
/**
* @return A map containing properties that will be used by the underlying {@link groovy.util.XmlSlurper}.
* @see org.xml.sax.XMLReader#setProperty(String, Object)
*/
public Map<String, Object> properties() {
return new HashMap<String, Object>(properties);
}
/**
* Specify features that will be used when parsing XML.
*
* @param features A map containing features that will be used by the underlying {@link groovy.util.XmlSlurper}.
* @return
* @see org.xml.sax.XMLReader#setFeature(java.lang.String, boolean)
*/
public XmlConfig features(Map<String, Boolean> features) {
return new XmlConfig(features, declaredNamespaces, properties, namespaceAware, true);
}
/**
* Specify properties that will be used when parsing XML.
*
* @param properties A map containing properties that will be used by the underlying {@link groovy.util.XmlSlurper}.
* @return
* @see org.xml.sax.XMLReader#setProperty(String, Object)
*/
public XmlConfig properties(Map<String, Object> properties) {
return new XmlConfig(features, declaredNamespaces, this.properties, namespaceAware, true);
}
/**
* Set a value of a feature flag.
*
* @param uri The feature name, which is a fully-qualified URI.
* @param enabled The requested value of the feature (true or false).
* @return A new XmlConfig instance
* @see org.xml.sax.XMLReader#setFeature(java.lang.String, boolean)
*/
public XmlConfig feature(String uri, boolean enabled) {
Validate.notEmpty(uri, "URI cannot be empty");
Map<String, Boolean> newFeatures = new HashMap<String, Boolean>(features);
newFeatures.put(uri, enabled);
return new XmlConfig(newFeatures, declaredNamespaces, properties, namespaceAware, true);
}
/**
* Set a value of a property.
*
* @param name The property name.
* @param value The requested value of the feature (true or false).
* @return A new XmlConfig instance
* @see org.xml.sax.XMLReader#setFeature(java.lang.String, boolean)
*/
public XmlConfig property(String name, Object value) {
Validate.notEmpty(name, "Name cannot be empty");
Map<String, Object> newProperties = new HashMap<String, Object>(properties);
newProperties.put(name, value);
return new XmlConfig(features, declaredNamespaces, newProperties, namespaceAware, true);
}
/**
* @return A map containing namespaces that will be used by the underlying {@link groovy.util.XmlSlurper}.
* @see org.xml.sax.XMLReader#setFeature(java.lang.String, boolean)
*/
public Map<String, String> declaredNamespaces() {
return new HashMap<String, String>(declaredNamespaces);
}
/**
* Specify declared namespaces that will be used when parsing XML. Will also set {@link #namespaceAware(boolean)} to <code>true</code> of namespaces are not empty.
* <p>Note that you cannot use this to add namespaces for the {@link org.hamcrest.xml.HasXPath} matcher.
* This has to be done by providing a {@link javax.xml.namespace.NamespaceContext} to the matcher instance.</p>
*
* @param namespacesToDeclare A map containing features that will be used by the underlying {@link groovy.util.XmlSlurper}.
* @return A new instance of XmlConfig
* @see org.xml.sax.XMLReader#setFeature(java.lang.String, boolean)
*/
public XmlConfig declareNamespaces(Map<String, String> namespacesToDeclare) {
final boolean shouldBeNamespaceAware = namespacesToDeclare == null ? namespaceAware : !namespacesToDeclare.isEmpty();
return new XmlConfig(features, namespacesToDeclare, properties, shouldBeNamespaceAware, true);
}
/**
* Declares a namespace and also sets {@link #namespaceAware(boolean)} to <code>true</code>.
* <p/>
* <p>Note that you cannot use this to add namespaces for the {@link org.hamcrest.xml.HasXPath} matcher.
* This has to be done by providing a {@link javax.xml.namespace.NamespaceContext} to the matcher instance.</p>
*
* @param prefix The feature name, which is a fully-qualified URI.
* @param namespaceURI The requested value of the feature (true or false).
* @return A new XmlConfig instance
* @see org.xml.sax.XMLReader#setFeature(java.lang.String, boolean)
*/
public XmlConfig declareNamespace(String prefix, String namespaceURI) {
Validate.notEmpty(prefix, "Prefix cannot be empty");
Validate.notEmpty(namespaceURI, "Namespace URI cannot be empty");
Map<String, String> updatedNamespaces = new HashMap<String, String>(declaredNamespaces);
updatedNamespaces.put(prefix, namespaceURI);
return new XmlConfig(features, updatedNamespaces, properties, true, true);
}
/**
* Disables external DTD loading.
* <p>
* This is a shortcut for doing:<br>
* <pre>
* setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
* </pre>
* </p>
*
* @return A new XmlConfig instance
* @see #feature(String, boolean)
*/
public XmlConfig disableLoadingOfExternalDtd() {
Map<String, Boolean> newFeatures = new HashMap<String, Boolean>(features);
newFeatures.put("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
return new XmlConfig(newFeatures, declaredNamespaces, properties, namespaceAware, true);
}
/**
* Configure whether or not REST Assured should be aware of namespaces when parsing XML.
*
* @param shouldBeAwareOfNamespaces <code>true</code> if xml parsing should take namespaces into account.
* @return A new XmlConfig instance
*/
public XmlConfig namespaceAware(boolean shouldBeAwareOfNamespaces) {
return new XmlConfig(features, declaredNamespaces, properties, shouldBeAwareOfNamespaces, true);
}
/**
* @return <code>true</code> if REST Assured should be namespace aware.
*/
public boolean isNamespaceAware() {
return namespaceAware;
}
/**
* For syntactic sugar.
*
* @return The same XmlConfig instance
*/
public XmlConfig with() {
return this;
}
/**
* For syntactic sugar.
*
* @return The same XmlConfig instance
*/
public XmlConfig and() {
return this;
}
/**
* @return A static way to create a new XmlConfig instance without calling "new" explicitly. Mainly for syntactic sugar.
*/
public static XmlConfig xmlConfig() {
return new XmlConfig();
}
/**
* {@inheritDoc}
*/
public boolean isUserConfigured() {
return isUserConfigured;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.builder.component.dsl;
import javax.annotation.Generated;
import org.apache.camel.Component;
import org.apache.camel.builder.component.AbstractComponentBuilder;
import org.apache.camel.builder.component.ComponentBuilder;
import org.apache.camel.component.aws2.ddb.Ddb2Component;
/**
* Store and retrieve data from AWS DynamoDB service using AWS SDK version 2.x.
*
* Generated by camel-package-maven-plugin - do not edit this file!
*/
@Generated("org.apache.camel.maven.packaging.ComponentDslMojo")
public interface Aws2DdbComponentBuilderFactory {
/**
* AWS DynamoDB (camel-aws2-ddb)
* Store and retrieve data from AWS DynamoDB service using AWS SDK version
* 2.x.
*
* Category: cloud,database,nosql
* Since: 3.1
* Maven coordinates: org.apache.camel:camel-aws2-ddb
*
* @return the dsl builder
*/
static Aws2DdbComponentBuilder aws2Ddb() {
return new Aws2DdbComponentBuilderImpl();
}
/**
* Builder for the AWS DynamoDB component.
*/
interface Aws2DdbComponentBuilder extends ComponentBuilder<Ddb2Component> {
/**
* To use the AmazonDynamoDB as the client.
*
* The option is a:
* <code>software.amazon.awssdk.services.dynamodb.DynamoDbClient</code> type.
*
* Group: producer
*
* @param amazonDDBClient the value to set
* @return the dsl builder
*/
default Aws2DdbComponentBuilder amazonDDBClient(
software.amazon.awssdk.services.dynamodb.DynamoDbClient amazonDDBClient) {
doSetProperty("amazonDDBClient", amazonDDBClient);
return this;
}
/**
* The component configuration.
*
* The option is a:
* <code>org.apache.camel.component.aws2.ddb.Ddb2Configuration</code> type.
*
* Group: producer
*
* @param configuration the value to set
* @return the dsl builder
*/
default Aws2DdbComponentBuilder configuration(
org.apache.camel.component.aws2.ddb.Ddb2Configuration configuration) {
doSetProperty("configuration", configuration);
return this;
}
/**
* Determines whether or not strong consistency should be enforced when
* data is read.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param consistentRead the value to set
* @return the dsl builder
*/
default Aws2DdbComponentBuilder consistentRead(boolean consistentRead) {
doSetProperty("consistentRead", consistentRead);
return this;
}
/**
* Attribute name when creating table.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param keyAttributeName the value to set
* @return the dsl builder
*/
default Aws2DdbComponentBuilder keyAttributeName(
java.lang.String keyAttributeName) {
doSetProperty("keyAttributeName", keyAttributeName);
return this;
}
/**
* Attribute type when creating table.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param keyAttributeType the value to set
* @return the dsl builder
*/
default Aws2DdbComponentBuilder keyAttributeType(
java.lang.String keyAttributeType) {
doSetProperty("keyAttributeType", keyAttributeType);
return this;
}
/**
* The key scalar type, it can be S (String), N (Number) and B (Bytes).
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param keyScalarType the value to set
* @return the dsl builder
*/
default Aws2DdbComponentBuilder keyScalarType(
java.lang.String keyScalarType) {
doSetProperty("keyScalarType", keyScalarType);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default Aws2DdbComponentBuilder lazyStartProducer(
boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* What operation to perform.
*
* The option is a:
* <code>org.apache.camel.component.aws2.ddb.Ddb2Operations</code> type.
*
* Default: PutItem
* Group: producer
*
* @param operation the value to set
* @return the dsl builder
*/
default Aws2DdbComponentBuilder operation(
org.apache.camel.component.aws2.ddb.Ddb2Operations operation) {
doSetProperty("operation", operation);
return this;
}
/**
* Set the need for overidding the endpoint. This option needs to be
* used in combination with uriEndpointOverride option.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param overrideEndpoint the value to set
* @return the dsl builder
*/
default Aws2DdbComponentBuilder overrideEndpoint(
boolean overrideEndpoint) {
doSetProperty("overrideEndpoint", overrideEndpoint);
return this;
}
/**
* To define a proxy host when instantiating the DDB client.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param proxyHost the value to set
* @return the dsl builder
*/
default Aws2DdbComponentBuilder proxyHost(java.lang.String proxyHost) {
doSetProperty("proxyHost", proxyHost);
return this;
}
/**
* The region in which DynamoDB client needs to work. When using this
* parameter, the configuration will expect the lowercase name of the
* region (for example ap-east-1) You'll need to use the name
* Region.EU_WEST_1.id().
*
* The option is a: <code>java.lang.Integer</code> type.
*
* Group: producer
*
* @param proxyPort the value to set
* @return the dsl builder
*/
default Aws2DdbComponentBuilder proxyPort(java.lang.Integer proxyPort) {
doSetProperty("proxyPort", proxyPort);
return this;
}
/**
* To define a proxy protocol when instantiating the DDB client.
*
* The option is a:
* <code>software.amazon.awssdk.core.Protocol</code> type.
*
* Default: HTTPS
* Group: producer
*
* @param proxyProtocol the value to set
* @return the dsl builder
*/
default Aws2DdbComponentBuilder proxyProtocol(
software.amazon.awssdk.core.Protocol proxyProtocol) {
doSetProperty("proxyProtocol", proxyProtocol);
return this;
}
/**
* The provisioned throughput to reserve for reading resources from your
* table.
*
* The option is a: <code>java.lang.Long</code> type.
*
* Group: producer
*
* @param readCapacity the value to set
* @return the dsl builder
*/
default Aws2DdbComponentBuilder readCapacity(java.lang.Long readCapacity) {
doSetProperty("readCapacity", readCapacity);
return this;
}
/**
* The region in which DDB client needs to work.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param region the value to set
* @return the dsl builder
*/
default Aws2DdbComponentBuilder region(java.lang.String region) {
doSetProperty("region", region);
return this;
}
/**
* If we want to trust all certificates in case of overriding the
* endpoint.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param trustAllCertificates the value to set
* @return the dsl builder
*/
default Aws2DdbComponentBuilder trustAllCertificates(
boolean trustAllCertificates) {
doSetProperty("trustAllCertificates", trustAllCertificates);
return this;
}
/**
* Set the overriding uri endpoint. This option needs to be used in
* combination with overrideEndpoint option.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param uriEndpointOverride the value to set
* @return the dsl builder
*/
default Aws2DdbComponentBuilder uriEndpointOverride(
java.lang.String uriEndpointOverride) {
doSetProperty("uriEndpointOverride", uriEndpointOverride);
return this;
}
/**
* Set whether the S3 client should expect to load credentials through a
* default credentials provider or to expect static credentials to be
* passed in.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param useDefaultCredentialsProvider the value to set
* @return the dsl builder
*/
default Aws2DdbComponentBuilder useDefaultCredentialsProvider(
boolean useDefaultCredentialsProvider) {
doSetProperty("useDefaultCredentialsProvider", useDefaultCredentialsProvider);
return this;
}
/**
* The provisioned throughput to reserved for writing resources to your
* table.
*
* The option is a: <code>java.lang.Long</code> type.
*
* Group: producer
*
* @param writeCapacity the value to set
* @return the dsl builder
*/
default Aws2DdbComponentBuilder writeCapacity(
java.lang.Long writeCapacity) {
doSetProperty("writeCapacity", writeCapacity);
return this;
}
/**
* Whether autowiring is enabled. This is used for automatic autowiring
* options (the option must be marked as autowired) by looking up in the
* registry to find if there is a single instance of matching type,
* which then gets configured on the component. This can be used for
* automatic configuring JDBC data sources, JMS connection factories,
* AWS Clients, etc.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: advanced
*
* @param autowiredEnabled the value to set
* @return the dsl builder
*/
default Aws2DdbComponentBuilder autowiredEnabled(
boolean autowiredEnabled) {
doSetProperty("autowiredEnabled", autowiredEnabled);
return this;
}
/**
* Amazon AWS Access Key.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param accessKey the value to set
* @return the dsl builder
*/
default Aws2DdbComponentBuilder accessKey(java.lang.String accessKey) {
doSetProperty("accessKey", accessKey);
return this;
}
/**
* Amazon AWS Secret Key.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param secretKey the value to set
* @return the dsl builder
*/
default Aws2DdbComponentBuilder secretKey(java.lang.String secretKey) {
doSetProperty("secretKey", secretKey);
return this;
}
}
class Aws2DdbComponentBuilderImpl
extends
AbstractComponentBuilder<Ddb2Component>
implements
Aws2DdbComponentBuilder {
@Override
protected Ddb2Component buildConcreteComponent() {
return new Ddb2Component();
}
private org.apache.camel.component.aws2.ddb.Ddb2Configuration getOrCreateConfiguration(
org.apache.camel.component.aws2.ddb.Ddb2Component component) {
if (component.getConfiguration() == null) {
component.setConfiguration(new org.apache.camel.component.aws2.ddb.Ddb2Configuration());
}
return component.getConfiguration();
}
@Override
protected boolean setPropertyOnComponent(
Component component,
String name,
Object value) {
switch (name) {
case "amazonDDBClient": getOrCreateConfiguration((Ddb2Component) component).setAmazonDDBClient((software.amazon.awssdk.services.dynamodb.DynamoDbClient) value); return true;
case "configuration": ((Ddb2Component) component).setConfiguration((org.apache.camel.component.aws2.ddb.Ddb2Configuration) value); return true;
case "consistentRead": getOrCreateConfiguration((Ddb2Component) component).setConsistentRead((boolean) value); return true;
case "keyAttributeName": getOrCreateConfiguration((Ddb2Component) component).setKeyAttributeName((java.lang.String) value); return true;
case "keyAttributeType": getOrCreateConfiguration((Ddb2Component) component).setKeyAttributeType((java.lang.String) value); return true;
case "keyScalarType": getOrCreateConfiguration((Ddb2Component) component).setKeyScalarType((java.lang.String) value); return true;
case "lazyStartProducer": ((Ddb2Component) component).setLazyStartProducer((boolean) value); return true;
case "operation": getOrCreateConfiguration((Ddb2Component) component).setOperation((org.apache.camel.component.aws2.ddb.Ddb2Operations) value); return true;
case "overrideEndpoint": getOrCreateConfiguration((Ddb2Component) component).setOverrideEndpoint((boolean) value); return true;
case "proxyHost": getOrCreateConfiguration((Ddb2Component) component).setProxyHost((java.lang.String) value); return true;
case "proxyPort": getOrCreateConfiguration((Ddb2Component) component).setProxyPort((java.lang.Integer) value); return true;
case "proxyProtocol": getOrCreateConfiguration((Ddb2Component) component).setProxyProtocol((software.amazon.awssdk.core.Protocol) value); return true;
case "readCapacity": getOrCreateConfiguration((Ddb2Component) component).setReadCapacity((java.lang.Long) value); return true;
case "region": getOrCreateConfiguration((Ddb2Component) component).setRegion((java.lang.String) value); return true;
case "trustAllCertificates": getOrCreateConfiguration((Ddb2Component) component).setTrustAllCertificates((boolean) value); return true;
case "uriEndpointOverride": getOrCreateConfiguration((Ddb2Component) component).setUriEndpointOverride((java.lang.String) value); return true;
case "useDefaultCredentialsProvider": getOrCreateConfiguration((Ddb2Component) component).setUseDefaultCredentialsProvider((boolean) value); return true;
case "writeCapacity": getOrCreateConfiguration((Ddb2Component) component).setWriteCapacity((java.lang.Long) value); return true;
case "autowiredEnabled": ((Ddb2Component) component).setAutowiredEnabled((boolean) value); return true;
case "accessKey": getOrCreateConfiguration((Ddb2Component) component).setAccessKey((java.lang.String) value); return true;
case "secretKey": getOrCreateConfiguration((Ddb2Component) component).setSecretKey((java.lang.String) value); return true;
default: return false;
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.drill.exec.physical.impl.join;
import static org.apache.drill.exec.compile.sig.GeneratorMapping.GM;
import java.io.IOException;
import java.util.List;
import com.google.common.collect.Lists;
import org.apache.calcite.rel.core.JoinRelType;
import org.apache.drill.common.expression.ErrorCollector;
import org.apache.drill.common.expression.ErrorCollectorImpl;
import org.apache.drill.common.expression.LogicalExpression;
import org.apache.drill.common.expression.TypedNullConstant;
import org.apache.drill.common.logical.data.JoinCondition;
import org.apache.drill.common.types.TypeProtos.DataMode;
import org.apache.drill.common.types.TypeProtos.MajorType;
import org.apache.drill.common.types.TypeProtos.MinorType;
import org.apache.drill.common.types.Types;
import org.apache.drill.exec.compile.sig.MappingSet;
import org.apache.drill.exec.exception.ClassTransformationException;
import org.apache.drill.exec.exception.OutOfMemoryException;
import org.apache.drill.exec.exception.SchemaChangeException;
import org.apache.drill.exec.expr.ClassGenerator;
import org.apache.drill.exec.expr.ClassGenerator.HoldingContainer;
import org.apache.drill.exec.expr.CodeGenerator;
import org.apache.drill.exec.expr.ExpressionTreeMaterializer;
import org.apache.drill.exec.expr.fn.FunctionGenerationHelper;
import org.apache.drill.exec.ops.FragmentContext;
import org.apache.drill.exec.physical.config.MergeJoinPOP;
import org.apache.drill.exec.physical.impl.common.Comparator;
import org.apache.drill.exec.record.AbstractRecordBatch;
import org.apache.drill.exec.record.BatchSchema;
import org.apache.drill.exec.record.MaterializedField;
import org.apache.drill.exec.record.RecordBatch;
import org.apache.drill.exec.record.RecordIterator;
import org.apache.drill.exec.record.TypedFieldId;
import org.apache.drill.exec.record.VectorAccessible;
import org.apache.drill.exec.record.VectorContainer;
import org.apache.drill.exec.record.VectorWrapper;
import org.apache.drill.exec.vector.AllocationHelper;
import org.apache.drill.exec.vector.ValueVector;
import org.apache.drill.exec.vector.complex.AbstractContainerVector;
import com.google.common.base.Preconditions;
import com.sun.codemodel.JClass;
import com.sun.codemodel.JConditional;
import com.sun.codemodel.JExpr;
import com.sun.codemodel.JMod;
import com.sun.codemodel.JVar;
/**
* A join operator merges two sorted streams using record iterator.
*/
public class MergeJoinBatch extends AbstractRecordBatch<MergeJoinPOP> {
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(MergeJoinBatch.class);
public final MappingSet setupMapping =
new MappingSet("null", "null",
GM("doSetup", "doSetup", null, null),
GM("doSetup", "doSetup", null, null));
public final MappingSet copyLeftMapping =
new MappingSet("leftIndex", "outIndex",
GM("doSetup", "doSetup", null, null),
GM("doSetup", "doCopyLeft", null, null));
public final MappingSet copyRightMappping =
new MappingSet("rightIndex", "outIndex",
GM("doSetup", "doSetup", null, null),
GM("doSetup", "doCopyRight", null, null));
public final MappingSet compareMapping =
new MappingSet("leftIndex", "rightIndex",
GM("doSetup", "doSetup", null, null),
GM("doSetup", "doCompare", null, null));
public final MappingSet compareRightMapping =
new MappingSet("rightIndex", "null",
GM("doSetup", "doSetup", null, null),
GM("doSetup", "doCompare", null, null));
private final RecordBatch left;
private final RecordBatch right;
private final RecordIterator leftIterator;
private final RecordIterator rightIterator;
private final JoinStatus status;
private final List<JoinCondition> conditions;
private final List<Comparator> comparators;
private final JoinRelType joinType;
private JoinWorker worker;
private static final String LEFT_INPUT = "LEFT INPUT";
private static final String RIGHT_INPUT = "RIGHT INPUT";
protected MergeJoinBatch(MergeJoinPOP popConfig, FragmentContext context, RecordBatch left, RecordBatch right) throws OutOfMemoryException {
super(popConfig, context, true);
if (popConfig.getConditions().size() == 0) {
throw new UnsupportedOperationException("Merge Join currently does not support cartesian join. This join operator was configured with 0 conditions");
}
this.left = left;
this.leftIterator = new RecordIterator(left, this, oContext, 0, false);
this.right = right;
this.rightIterator = new RecordIterator(right, this, oContext, 1);
this.joinType = popConfig.getJoinType();
this.status = new JoinStatus(leftIterator, rightIterator, this);
this.conditions = popConfig.getConditions();
this.comparators = Lists.newArrayListWithExpectedSize(conditions.size());
for (JoinCondition condition : conditions) {
this.comparators.add(JoinUtils.checkAndReturnSupportedJoinComparator(condition));
}
}
public JoinRelType getJoinType() {
return joinType;
}
@Override
public int getRecordCount() {
return status.getOutPosition();
}
@Override
public void buildSchema() {
// initialize iterators
status.initialize();
final IterOutcome leftOutcome = status.getLeftStatus();
final IterOutcome rightOutcome = status.getRightStatus();
if (leftOutcome == IterOutcome.STOP || rightOutcome == IterOutcome.STOP) {
state = BatchState.STOP;
return;
}
if (leftOutcome == IterOutcome.OUT_OF_MEMORY || rightOutcome == IterOutcome.OUT_OF_MEMORY) {
state = BatchState.OUT_OF_MEMORY;
return;
}
allocateBatch(true);
}
@Override
public IterOutcome innerNext() {
// we do this in the here instead of the constructor because don't necessary want to start consuming on construction.
status.prepare();
// loop so we can start over again if we find a new batch was created.
while (true) {
// Check result of last iteration.
switch (status.getOutcome()) {
case BATCH_RETURNED:
allocateBatch(false);
status.resetOutputPos();
break;
case SCHEMA_CHANGED:
allocateBatch(true);
status.resetOutputPos();
break;
case NO_MORE_DATA:
status.resetOutputPos();
logger.debug("NO MORE DATA; returning {} NONE");
return IterOutcome.NONE;
case FAILURE:
status.left.clearInflightBatches();
status.right.clearInflightBatches();
kill(false);
return IterOutcome.STOP;
case WAITING:
return IterOutcome.NOT_YET;
default:
throw new IllegalStateException();
}
boolean first = false;
if (worker == null) {
try {
logger.debug("Creating New Worker");
stats.startSetup();
this.worker = generateNewWorker();
first = true;
} catch (ClassTransformationException | IOException | SchemaChangeException e) {
context.fail(new SchemaChangeException(e));
kill(false);
return IterOutcome.STOP;
} finally {
stats.stopSetup();
}
}
// join until we have a complete outgoing batch
if (!worker.doJoin(status)) {
worker = null;
}
// get the outcome of the last join iteration.
switch (status.getOutcome()) {
case BATCH_RETURNED:
// only return new schema if new worker has been setup.
logger.debug("BATCH RETURNED; returning {}", (first ? "OK_NEW_SCHEMA" : "OK"));
setRecordCountInContainer();
return first ? IterOutcome.OK_NEW_SCHEMA : IterOutcome.OK;
case FAILURE:
status.left.clearInflightBatches();
status.right.clearInflightBatches();
kill(false);
return IterOutcome.STOP;
case NO_MORE_DATA:
logger.debug("NO MORE DATA; returning {}",
(status.getOutPosition() > 0 ? (first ? "OK_NEW_SCHEMA" : "OK") : (first ? "OK_NEW_SCHEMA" : "NONE")));
setRecordCountInContainer();
state = BatchState.DONE;
return (first? IterOutcome.OK_NEW_SCHEMA : (status.getOutPosition() > 0 ? IterOutcome.OK: IterOutcome.NONE));
case SCHEMA_CHANGED:
worker = null;
if (status.getOutPosition() > 0) {
// if we have current data, let's return that.
logger.debug("SCHEMA CHANGED; returning {} ", (first ? "OK_NEW_SCHEMA" : "OK"));
setRecordCountInContainer();
return first ? IterOutcome.OK_NEW_SCHEMA : IterOutcome.OK;
} else{
// loop again to rebuild worker.
continue;
}
case WAITING:
return IterOutcome.NOT_YET;
default:
throw new IllegalStateException();
}
}
}
private void setRecordCountInContainer() {
for (VectorWrapper vw : container) {
Preconditions.checkArgument(!vw.isHyper());
vw.getValueVector().getMutator().setValueCount(getRecordCount());
}
}
@Override
public void close() {
super.close();
leftIterator.close();
rightIterator.close();
}
@Override
protected void killIncoming(boolean sendUpstream) {
left.kill(sendUpstream);
right.kill(sendUpstream);
}
private JoinWorker generateNewWorker() throws ClassTransformationException, IOException, SchemaChangeException{
final ClassGenerator<JoinWorker> cg = CodeGenerator.getRoot(JoinWorker.TEMPLATE_DEFINITION, context.getFunctionRegistry(), context.getOptions());
cg.getCodeGenerator().plainJavaCapable(true);
// Uncomment out this line to debug the generated code.
// cg.getCodeGenerator().saveCodeForDebugging(true);
final ErrorCollector collector = new ErrorCollectorImpl();
// Generate members and initialization code
/////////////////////////////////////////
// declare and assign JoinStatus member
cg.setMappingSet(setupMapping);
JClass joinStatusClass = cg.getModel().ref(JoinStatus.class);
JVar joinStatus = cg.clazz.field(JMod.NONE, joinStatusClass, "status");
cg.getSetupBlock().assign(JExpr._this().ref(joinStatus), JExpr.direct("status"));
// declare and assign outgoing VectorContainer member
JClass vectorContainerClass = cg.getModel().ref(VectorContainer.class);
JVar outgoingVectorContainer = cg.clazz.field(JMod.NONE, vectorContainerClass, "outgoing");
cg.getSetupBlock().assign(JExpr._this().ref(outgoingVectorContainer), JExpr.direct("outgoing"));
// declare and assign incoming left RecordBatch member
JClass recordBatchClass = cg.getModel().ref(RecordIterator.class);
JVar incomingLeftRecordBatch = cg.clazz.field(JMod.NONE, recordBatchClass, "incomingLeft");
cg.getSetupBlock().assign(JExpr._this().ref(incomingLeftRecordBatch), joinStatus.ref("left"));
// declare and assign incoming right RecordBatch member
JVar incomingRightRecordBatch = cg.clazz.field(JMod.NONE, recordBatchClass, "incomingRight");
cg.getSetupBlock().assign(JExpr._this().ref(incomingRightRecordBatch), joinStatus.ref("right"));
// declare 'incoming' member so VVReadExpr generated code can point to the left or right batch
JVar incomingRecordBatch = cg.clazz.field(JMod.NONE, recordBatchClass, "incoming");
/*
* Materialize expressions on both sides of the join condition. Check if both the sides
* have the same return type, if not then inject casts so that comparison function will work as
* expected
*/
LogicalExpression leftExpr[] = new LogicalExpression[conditions.size()];
LogicalExpression rightExpr[] = new LogicalExpression[conditions.size()];
IterOutcome lastLeftStatus = status.getLeftStatus();
IterOutcome lastRightStatus = status.getRightStatus();
for (int i = 0; i < conditions.size(); i++) {
JoinCondition condition = conditions.get(i);
leftExpr[i] = materializeExpression(condition.getLeft(), lastLeftStatus, leftIterator, collector);
rightExpr[i] = materializeExpression(condition.getRight(), lastRightStatus, rightIterator, collector);
}
// if right side is empty, rightExpr will most likely default to NULLABLE INT which may cause the following
// call to throw an exception. In this case we can safely skip adding the casts
if (lastRightStatus != IterOutcome.NONE) {
JoinUtils.addLeastRestrictiveCasts(leftExpr, leftIterator, rightExpr, rightIterator, context);
}
//generate doCompare() method
/////////////////////////////////////////
generateDoCompare(cg, incomingRecordBatch, leftExpr, incomingLeftRecordBatch, rightExpr,
incomingRightRecordBatch, collector);
// generate copyLeft()
//////////////////////
cg.setMappingSet(copyLeftMapping);
int vectorId = 0;
if (worker == null || !status.left.finished()) {
for (VectorWrapper<?> vw : leftIterator) {
MajorType inputType = vw.getField().getType();
MajorType outputType;
if (joinType == JoinRelType.RIGHT && inputType.getMode() == DataMode.REQUIRED) {
outputType = Types.overrideMode(inputType, DataMode.OPTIONAL);
} else {
outputType = inputType;
}
// TODO (DRILL-4011): Factor out CopyUtil and use it here.
JVar vvIn = cg.declareVectorValueSetupAndMember("incomingLeft",
new TypedFieldId(inputType, vectorId));
JVar vvOut = cg.declareVectorValueSetupAndMember("outgoing",
new TypedFieldId(outputType,vectorId));
// todo: check result of copyFromSafe and grow allocation
cg.getEvalBlock().add(vvOut.invoke("copyFromSafe")
.arg(copyLeftMapping.getValueReadIndex())
.arg(copyLeftMapping.getValueWriteIndex())
.arg(vvIn));
cg.rotateBlock();
++vectorId;
}
}
// generate copyRight()
///////////////////////
cg.setMappingSet(copyRightMappping);
int rightVectorBase = vectorId;
if (status.getRightStatus() != IterOutcome.NONE && (worker == null || !status.right.finished())) {
for (VectorWrapper<?> vw : rightIterator) {
MajorType inputType = vw.getField().getType();
MajorType outputType;
if (joinType == JoinRelType.LEFT && inputType.getMode() == DataMode.REQUIRED) {
outputType = Types.overrideMode(inputType, DataMode.OPTIONAL);
} else {
outputType = inputType;
}
// TODO (DRILL-4011): Factor out CopyUtil and use it here.
JVar vvIn = cg.declareVectorValueSetupAndMember("incomingRight",
new TypedFieldId(inputType, vectorId - rightVectorBase));
JVar vvOut = cg.declareVectorValueSetupAndMember("outgoing",
new TypedFieldId(outputType,vectorId));
// todo: check result of copyFromSafe and grow allocation
cg.getEvalBlock().add(vvOut.invoke("copyFromSafe")
.arg(copyRightMappping.getValueReadIndex())
.arg(copyRightMappping.getValueWriteIndex())
.arg(vvIn));
cg.rotateBlock();
++vectorId;
}
}
JoinWorker w = context.getImplementationClass(cg);
w.setupJoin(context, status, this.container);
return w;
}
private void allocateBatch(boolean newSchema) {
boolean leftAllowed = status.getLeftStatus() != IterOutcome.NONE;
boolean rightAllowed = status.getRightStatus() != IterOutcome.NONE;
if (newSchema) {
container.clear();
// add fields from both batches
if (leftAllowed) {
for (VectorWrapper<?> w : leftIterator) {
MajorType inputType = w.getField().getType();
MajorType outputType;
if (joinType == JoinRelType.RIGHT && inputType.getMode() == DataMode.REQUIRED) {
outputType = Types.overrideMode(inputType, DataMode.OPTIONAL);
} else {
outputType = inputType;
}
MaterializedField newField = MaterializedField.create(w.getField().getPath(), outputType);
ValueVector v = container.addOrGet(newField);
if (v instanceof AbstractContainerVector) {
w.getValueVector().makeTransferPair(v);
v.clear();
}
}
}
if (rightAllowed) {
for (VectorWrapper<?> w : rightIterator) {
MajorType inputType = w.getField().getType();
MajorType outputType;
if (joinType == JoinRelType.LEFT && inputType.getMode() == DataMode.REQUIRED) {
outputType = Types.overrideMode(inputType, DataMode.OPTIONAL);
} else {
outputType = inputType;
}
MaterializedField newField = MaterializedField.create(w.getField().getPath(), outputType);
ValueVector v = container.addOrGet(newField);
if (v instanceof AbstractContainerVector) {
w.getValueVector().makeTransferPair(v);
v.clear();
}
}
}
} else {
container.zeroVectors();
}
for (VectorWrapper w : container) {
AllocationHelper.allocateNew(w.getValueVector(), Character.MAX_VALUE);
}
container.buildSchema(BatchSchema.SelectionVectorMode.NONE);
logger.debug("Built joined schema: {}", container.getSchema());
}
private void generateDoCompare(ClassGenerator<JoinWorker> cg, JVar incomingRecordBatch,
LogicalExpression[] leftExpression, JVar incomingLeftRecordBatch, LogicalExpression[] rightExpression,
JVar incomingRightRecordBatch, ErrorCollector collector) throws ClassTransformationException {
cg.setMappingSet(compareMapping);
if (status.getRightStatus() != IterOutcome.NONE) {
assert leftExpression.length == rightExpression.length;
for (int i = 0; i < leftExpression.length; i++) {
// generate compare()
////////////////////////
cg.setMappingSet(compareMapping);
cg.getSetupBlock().assign(JExpr._this().ref(incomingRecordBatch), JExpr._this().ref(incomingLeftRecordBatch));
ClassGenerator.HoldingContainer compareLeftExprHolder = cg.addExpr(leftExpression[i], ClassGenerator.BlkCreateMode.FALSE);
cg.setMappingSet(compareRightMapping);
cg.getSetupBlock().assign(JExpr._this().ref(incomingRecordBatch), JExpr._this().ref(incomingRightRecordBatch));
ClassGenerator.HoldingContainer compareRightExprHolder = cg.addExpr(rightExpression[i], ClassGenerator.BlkCreateMode.FALSE);
LogicalExpression fh =
FunctionGenerationHelper.getOrderingComparatorNullsHigh(compareLeftExprHolder,
compareRightExprHolder,
context.getFunctionRegistry());
HoldingContainer out = cg.addExpr(fh, ClassGenerator.BlkCreateMode.FALSE);
// If not 0, it means not equal.
// Null compares to Null should returns null (unknown). In such case, we return 1 to indicate they are not equal.
if (compareLeftExprHolder.isOptional() && compareRightExprHolder.isOptional()
&& comparators.get(i) == Comparator.EQUALS) {
JConditional jc = cg.getEvalBlock()._if(compareLeftExprHolder.getIsSet().eq(JExpr.lit(0)).
cand(compareRightExprHolder.getIsSet().eq(JExpr.lit(0))));
jc._then()._return(JExpr.lit(1));
jc._elseif(out.getValue().ne(JExpr.lit(0)))._then()._return(out.getValue());
} else {
cg.getEvalBlock()._if(out.getValue().ne(JExpr.lit(0)))._then()._return(out.getValue());
}
}
}
//Pass the equality check for all the join conditions. Finally, return 0.
cg.getEvalBlock()._return(JExpr.lit(0));
}
private LogicalExpression materializeExpression(LogicalExpression expression, IterOutcome lastStatus,
VectorAccessible input, ErrorCollector collector) throws ClassTransformationException {
LogicalExpression materializedExpr;
if (lastStatus != IterOutcome.NONE) {
materializedExpr = ExpressionTreeMaterializer.materialize(expression, input, collector, context.getFunctionRegistry(), unionTypeEnabled);
} else {
materializedExpr = new TypedNullConstant(Types.optional(MinorType.INT));
}
if (collector.hasErrors()) {
throw new ClassTransformationException(String.format(
"Failure while trying to materialize incoming field from %s batch. Errors:\n %s.",
(input == leftIterator ? LEFT_INPUT : RIGHT_INPUT), collector.toErrorString()));
}
return materializedExpr;
}
}
| |
/*
* 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.piggybank.storage;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.PositionedReadable;
import org.apache.hadoop.fs.Seekable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.mapreduce.InputFormat;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.OutputFormat;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.RecordWriter;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.TaskAttemptID;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.pig.IndexableLoadFunc;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MRConfiguration;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigTextInputFormat;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigTextOutputFormat;
import org.apache.pig.backend.hadoop.executionengine.shims.HadoopShims;
import org.apache.pig.piggybank.storage.IndexedStorage.IndexedStorageInputFormat.IndexedStorageRecordReader;
import org.apache.pig.piggybank.storage.IndexedStorage.IndexedStorageInputFormat.IndexedStorageRecordReader.IndexedStorageRecordReaderComparator;
import org.apache.pig.builtin.PigStorage;
import org.apache.pig.data.DataReaderWriter;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;
import org.apache.pig.impl.util.StorageUtil;
import org.apache.pig.data.DataType;
import org.apache.pig.data.DataByteArray;
/**
* <code>IndexedStorage</code> is a form of <code>PigStorage</code> that supports a
* per record seek. <code>IndexedStorage</code> creates a separate (hidden) index file for
* every data file that is written. The format of the index file is:
* <pre>
* | Header |
* | Index Body |
* | Footer |
* </pre>
* The Header contains the list of record indices (field numbers) that represent index keys.
* The Index Body contains a <code>Tuple</code> for each record in the data.
* The fields of the <code>Tuple</code> are:
* <ul>
* <li> The index key(s) <code>Tuple</code> </li>
* <li> The number of records that share this index key. </li>
* <li> Offset into the data file to read the first matching record. </li>
* </ul>
* The Footer contains sequentially:
* <ul>
* <li> The smallest key(s) <code>Tuple</code> in the index. </li>
* <li> The largest key(s) <code>Tuple</code> in the index. </li>
* <li> The offset in bytes to the start of the footer </li>
* </ul>
*
* <code>IndexStorage</code> implements <code>IndexableLoadFunc</code> and
* can be used as the 'right table' in a PIG 'merge' or 'merge-sparse' join.
*
* <code>IndexStorage</code> does not require the data to be globally partitioned & sorted
* by index keys. Each partition (separate index) must be locally sorted.
*
* Also note IndexStorage is a loader to demonstrate "merge-sparse" join.
*/
public class IndexedStorage extends PigStorage implements IndexableLoadFunc {
/**
* Constructs a Pig Storer that uses specified regex as a field delimiter.
* @param delimiter - field delimiter to use
* @param offsetsToIndexKeys - list of offset into Tuple for index keys (comma separated)
*/
public IndexedStorage(String delimiter, String offsetsToIndexKeys) {
super(delimiter);
this.fieldDelimiter = StorageUtil.parseFieldDel(delimiter);
String[] stroffsetsToIndexKeys = offsetsToIndexKeys.split(",");
this.offsetsToIndexKeys = new int[stroffsetsToIndexKeys.length];
for (int i = 0; i < stroffsetsToIndexKeys.length; ++i) {
this.offsetsToIndexKeys[i] = Integer.parseInt(stroffsetsToIndexKeys[i]);
}
}
@Override
public OutputFormat getOutputFormat() {
return new IndexedStorageOutputFormat(fieldDelimiter, offsetsToIndexKeys);
}
/**
* Assumes this list of readers is already sorted except for the provided element.
* This element is bubbled up the array to its appropriate sort location
* (faster than doing a Utils sort).
*/
private void sortReader(int startIndex) {
int idx = startIndex;
while (idx < this.readers.length - 1) {
IndexedStorageRecordReader reader1 = this.readers[idx];
IndexedStorageRecordReader reader2 = this.readers[idx+1];
if (this.readerComparator.compare(reader1, reader2) <= 0) {
return;
}
this.readers[idx] = reader2;
this.readers[idx+1] = reader1;
idx++;
}
}
/**
* Internal OutputFormat class
*/
public static class IndexedStorageOutputFormat extends PigTextOutputFormat {
public IndexedStorageOutputFormat(byte delimiter, int[] offsetsToIndexKeys) {
/* Call the base class constructor */
super(delimiter);
this.fieldDelimiter = delimiter;
this.offsetsToIndexKeys = offsetsToIndexKeys;
}
@Override
public RecordWriter<WritableComparable, Tuple> getRecordWriter(
TaskAttemptContext context) throws IOException,
InterruptedException {
Configuration conf = context.getConfiguration();
FileSystem fs = FileSystem.get(conf);
Path file = this.getDefaultWorkFile(context, "");
FSDataOutputStream fileOut = fs.create(file, false);
IndexManager indexManager = new IndexManager(offsetsToIndexKeys);
indexManager.createIndexFile(fs, file);
return new IndexedStorageRecordWriter(fileOut, this.fieldDelimiter, indexManager);
}
/**
* Internal class to do the actual record writing and index generation
*
*/
public static class IndexedStorageRecordWriter extends PigLineRecordWriter {
public IndexedStorageRecordWriter(FSDataOutputStream fileOut, byte fieldDel, IndexManager indexManager) throws IOException {
super(fileOut, fieldDel);
this.fileOut = fileOut;
this.indexManager = indexManager;
/* Write the index header first */
this.indexManager.WriteIndexHeader();
}
@Override
public void write(WritableComparable key, Tuple value) throws IOException {
/* Write the data */
long offset = this.fileOut.getPos();
super.write(key, value);
/* Build index */
this.indexManager.BuildIndex(value, offset);
}
@Override
public void close(TaskAttemptContext context)
throws IOException {
this.indexManager.WriterIndexFooter();
this.indexManager.Close();
super.close(context);
}
/**
* Output stream for data
*/
private FSDataOutputStream fileOut;
/**
* Index builder
*/
private IndexManager indexManager = null;
}
/**
* Delimiter to use between fields
*/
final private byte fieldDelimiter;
/**
* Offsets to index keys in given tuple
*/
final protected int[] offsetsToIndexKeys;
}
@Override
public InputFormat getInputFormat() {
return new IndexedStorageInputFormat();
}
@Override
public Tuple getNext() throws IOException {
if (this.readers == null) {
return super.getNext();
}
while (currentReaderIndexStart < this.readers.length) {
IndexedStorageRecordReader r = this.readers[currentReaderIndexStart];
this.prepareToRead(r, null);
Tuple tuple = super.getNext();
if (tuple == null) {
currentReaderIndexStart++;
r.close();
continue; //next Reader
}
//if we haven't yet initialized the indexManager (by reading the first index key)
if (r.indexManager.lastIndexKeyTuple == null) {
//initialize the indexManager
if (r.indexManager.ReadIndex() == null) {
//There should never be a case where there is a non-null record - but no corresponding index.
throw new IOException("Missing Index for Tuple: " + tuple);
}
}
r.indexManager.numberOfTuples--;
if (r.indexManager.numberOfTuples == 0) {
if (r.indexManager.ReadIndex() == null) {
r.close();
currentReaderIndexStart++;
} else {
//Since the index of the current reader was increased, we may need to push the
//current reader back in the sorted list of readers.
sortReader(currentReaderIndexStart);
}
}
return tuple;
}
return null;
}
/**
* IndexableLoadFunc interface implementation
*/
@Override
public void initialize(Configuration conf) throws IOException {
try {
InputFormat inputFormat = this.getInputFormat();
TaskAttemptID id = HadoopShims.getNewTaskAttemptID();
if (System.getenv("HADOOP_TOKEN_FILE_LOCATION") != null) {
conf.set(MRConfiguration.JOB_CREDENTIALS_BINARY, System.getenv("HADOOP_TOKEN_FILE_LOCATION"));
}
List<FileSplit> fileSplits = inputFormat.getSplits(HadoopShims.createJobContext(conf, null));
this.readers = new IndexedStorageRecordReader[fileSplits.size()];
int idx = 0;
Iterator<FileSplit> it = fileSplits.iterator();
while (it.hasNext()) {
FileSplit fileSplit = it.next();
TaskAttemptContext context = HadoopShims.createTaskAttemptContext(conf, id);
IndexedStorageRecordReader r = (IndexedStorageRecordReader) inputFormat.createRecordReader(fileSplit, context);
r.initialize(fileSplit, context);
this.readers[idx] = r;
idx++;
}
Arrays.sort(this.readers, this.readerComparator);
} catch (InterruptedException e) {
throw new IOException(e);
}
}
@Override
/* The list of readers is always sorted before and after this call. */
public void seekNear(Tuple keys) throws IOException {
/* Keeps track of the last (if any) reader where seekNear was called */
int lastIndexModified = -1;
int idx = currentReaderIndexStart;
while (idx < this.readers.length) {
IndexedStorageRecordReader r = this.readers[idx];
/* The key falls within the range of the reader index */
if (keys.compareTo(r.indexManager.maxIndexKeyTuple) <= 0 && keys.compareTo(r.indexManager.minIndexKeyTuple) >= 0) {
r.seekNear(keys);
lastIndexModified = idx;
/* The key is greater than the current range of the reader index */
} else if (keys.compareTo(r.indexManager.maxIndexKeyTuple) > 0) {
currentReaderIndexStart++;
/* DO NOTHING - The key is less than the current range of the reader index */
} else {
break;
}
idx++;
}
/*
* There is something to sort.
* We can rely on the following invariants that make the following check accurate:
* - currentReaderIndexStart is always >= 0.
* - lastIndexModified is only positive if seekNear was called.
* - lastIndexModified >= currentReaderIndexStart if lastIndexModifed >= 0. This is true because the list
* is already sorted.
*/
if (lastIndexModified - currentReaderIndexStart >= 0) {
/*
* The following logic is optimized for the (common) case where there are a tiny number of readers that
* need to be repositioned relative to the other readers in the much larger sorted list.
*/
/* First, just sort the readers that were updated relative to one another. */
Arrays.sort(this.readers, currentReaderIndexStart, lastIndexModified+1, this.readerComparator);
/* In descending order, push the updated readers back in the the sorted list. */
for (idx = lastIndexModified; idx >= currentReaderIndexStart; idx--) {
sortReader(idx);
}
}
}
@Override
public void close() throws IOException {
for (IndexedStorageRecordReader reader : this.readers) {
reader.close();
}
}
/**
* <code>IndexManager</code> manages the index file (both writing and reading)
* It keeps track of the last index read during reading.
*/
public static class IndexManager {
/**
* Constructor (called during reading)
* @param ifile index file to read
*/
public IndexManager(FileStatus ifile) {
this.indexFile = ifile;
this.offsetToFooter = -1;
}
/**
* Constructor (called during writing)
* @param offsetsToIndexKeys
*/
public IndexManager(int[] offsetsToIndexKeys) {
this.offsetsToIndexKeys = offsetsToIndexKeys;
this.offsetToFooter = -1;
}
/**
* Construct index file path for a given a data file
* @param file - Data file
* @return - Index file path for given data file
*/
private static Path getIndexFileName(Path file) {
return new Path(file.getParent(), "." + file.getName() + ".index");
}
/**
* Open the index file for writing for given data file
* @param fs
* @param file
* @throws IOException
*/
public void createIndexFile(FileSystem fs, Path file) throws IOException {
this.indexOut = fs.create(IndexManager.getIndexFileName(file), false);
}
/**
* Opens the index file.
*/
public void openIndexFile(FileSystem fs) throws IOException {
this.indexIn = fs.open(this.indexFile.getPath());
}
/**
* Close the index file
* @throws IOException
*/
public void Close() throws IOException {
this.indexOut.close();
}
/**
* Build index tuple
*
* @throws IOException
*/
private void BuildIndex(Tuple t, long offset) throws IOException {
/* Build index key tuple */
Tuple indexKeyTuple = tupleFactory.newTuple(this.offsetsToIndexKeys.length);
for (int i = 0; i < this.offsetsToIndexKeys.length; ++i) {
indexKeyTuple.set(i, t.get(this.offsetsToIndexKeys[i]));
}
/* Check if we have already seen Tuple(s) with same index keys */
if (indexKeyTuple.compareTo(this.lastIndexKeyTuple) == 0) {
/* We have seen Tuple(s) with given index keys, update the tuple count */
this.numberOfTuples += 1;
}
else {
if (this.lastIndexKeyTuple != null)
this.WriteIndex();
this.lastIndexKeyTuple = indexKeyTuple;
this.minIndexKeyTuple = ((this.minIndexKeyTuple == null) || (indexKeyTuple.compareTo(this.minIndexKeyTuple) < 0)) ? indexKeyTuple : this.minIndexKeyTuple;
this.maxIndexKeyTuple = ((this.maxIndexKeyTuple == null) || (indexKeyTuple.compareTo(this.maxIndexKeyTuple) > 0)) ? indexKeyTuple : this.maxIndexKeyTuple;
/* New index tuple for newly seen index key */
this.indexTuple = tupleFactory.newTuple(3);
/* Add index keys to index Tuple */
this.indexTuple.set(0, indexKeyTuple);
/* Reset Tuple count for index key */
this.numberOfTuples = 1;
/* Remember offset to Tuple with new index keys */
this.indexTuple.set(2, offset);
}
}
/**
* Write index header
* @param indexOut - Stream to write to
* @param ih - Index header to write
* @throws IOException
*/
public void WriteIndexHeader() throws IOException {
/* Number of index keys */
indexOut.writeInt(this.offsetsToIndexKeys.length);
/* Offset to index keys */
for (int i = 0; i < this.offsetsToIndexKeys.length; ++i) {
indexOut.writeInt(this.offsetsToIndexKeys[i]);
}
}
/**
* Read index header
* @param indexIn - Stream to read from
* @return Index header
* @throws IOException
*/
public void ReadIndexHeader() throws IOException {
/* Number of index keys */
int nkeys = this.indexIn.readInt();
/* Offset to index keys */
this.offsetsToIndexKeys = new int[nkeys];
for (int i = 0; i < nkeys; ++i) {
offsetsToIndexKeys[i] = this.indexIn.readInt();
}
}
/**
* Writes the index footer
*/
public void WriterIndexFooter() throws IOException {
/* Flush indexes for remaining records */
this.WriteIndex();
/* record the offset to footer */
this.offsetToFooter = this.indexOut.getPos();
/* Write index footer */
DataReaderWriter.writeDatum(indexOut, this.minIndexKeyTuple);
DataReaderWriter.writeDatum(indexOut, this.maxIndexKeyTuple);
/* Offset to footer */
indexOut.writeLong(this.offsetToFooter);
}
/**
* Reads the index footer
*/
public void ReadIndexFooter() throws IOException {
long currentOffset = this.indexIn.getPos();
this.SeekToIndexFooter();
this.minIndexKeyTuple = (Tuple)DataReaderWriter.readDatum(this.indexIn);
this.maxIndexKeyTuple = (Tuple)DataReaderWriter.readDatum(this.indexIn);
this.indexIn.seek(currentOffset);
}
/**
* Seeks to the index footer
*/
public void SeekToIndexFooter() throws IOException {
if (this.offsetToFooter < 0) {
/* offset to footer is at last long (8 bytes) in the file */
this.indexIn.seek(this.indexFile.getLen()-8);
this.offsetToFooter = this.indexIn.readLong();
}
this.indexIn.seek(this.offsetToFooter);
}
/**
* Writes the current index.
*/
public void WriteIndex() throws IOException {
this.indexTuple.set(1, this.numberOfTuples);
DataReaderWriter.writeDatum(this.indexOut, this.indexTuple);
}
/**
* Extracts the index key from the index tuple
*/
public Tuple getIndexKeyTuple(Tuple indexTuple) throws IOException {
if (indexTuple.size() == 3)
return (Tuple)indexTuple.get(0);
else
throw new IOException("Invalid index record with size " + indexTuple.size());
}
/**
* Extracts the number of records that share the current key from the index tuple.
*/
public long getIndexKeyTupleCount(Tuple indexTuple) throws IOException {
if (indexTuple.size() == 3)
return (Long)indexTuple.get(1);
else
throw new IOException("Invalid index record with size " + indexTuple.size());
}
/**
* Extracts the offset into the data file from the index tuple.
*/
public long getOffset(Tuple indexTuple) throws IOException {
if (indexTuple.size() == 3)
return (Long)indexTuple.get(2);
else
throw new IOException("Invalid index record with size " + indexTuple.size());
}
/**
* Reads the next index from the index file (or null if EOF) and extracts
* the index fields.
*/
public Tuple ReadIndex() throws IOException {
if (this.indexIn.getPos() < this.offsetToFooter) {
indexTuple = (Tuple)DataReaderWriter.readDatum(this.indexIn);
if (indexTuple != null) {
this.lastIndexKeyTuple = this.getIndexKeyTuple(indexTuple);
this.numberOfTuples = this.getIndexKeyTupleCount(indexTuple);
}
return indexTuple;
}
return null;
}
/**
* Scans the index looking for a given key.
* @return the matching index tuple OR the last index tuple
* greater than the requested key if no match is found.
*/
public Tuple ScanIndex(Tuple keys) throws IOException {
if (lastIndexKeyTuple != null && keys.compareTo(this.lastIndexKeyTuple) <= 0) {
return indexTuple;
}
/* Scan the index looking for given key */
while ((indexTuple = this.ReadIndex()) != null) {
if (keys.compareTo(this.lastIndexKeyTuple) > 0)
continue;
else
break;
}
return indexTuple;
}
/**
* stores the list of record indices that identify keys.
*/
private int[] offsetsToIndexKeys = null;
/**
* offset in bytes to the start of the footer of the index.
*/
private long offsetToFooter = -1;
/**
* output stream when writing the index.
*/
FSDataOutputStream indexOut;
/**
* input stream when reading the index.
*/
FSDataInputStream indexIn;
/**
* Tuple factory to create index tuples
*/
private TupleFactory tupleFactory = TupleFactory.getInstance();
/**
* Index key tuple of the form
* ((Tuple of index keys), count of tuples with index keys, offset to first tuple with index keys)
*/
private Tuple indexTuple = tupleFactory.newTuple(3);
/**
* "Smallest" index key tuple seen
*/
private Tuple minIndexKeyTuple = null;
/**
* "Biggest" index key tuple seen
*/
private Tuple maxIndexKeyTuple = null;
/**
* Last seen index key tuple
*/
private Tuple lastIndexKeyTuple = null;
/**
* Number of tuples seen for a index key
*/
private long numberOfTuples = 0;
/**
* The index file.
*/
private FileStatus indexFile;
}
/**
* Internal InputFormat class
*/
public static class IndexedStorageInputFormat extends PigTextInputFormat {
@Override
public RecordReader<LongWritable, Text> createRecordReader(InputSplit split, TaskAttemptContext context) {
IndexManager im = null;
try {
FileSystem fs = FileSystem.get(context.getConfiguration());
Path indexFile = IndexManager.getIndexFileName(((FileSplit)split).getPath());
im = new IndexManager(fs.getFileStatus(indexFile));
im.openIndexFile(fs);
im.ReadIndexHeader();
im.ReadIndexFooter();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new IndexedStorageRecordReader(im);
}
@Override
public boolean isSplitable(JobContext context, Path filename) {
return false;
}
/**
* Internal RecordReader class
*/
public static class IndexedStorageRecordReader extends RecordReader<LongWritable, Text> {
private long start;
private long pos;
private long end;
private IndexedStorageLineReader in;
private int maxLineLength;
private LongWritable key = null;
private Text value = null;
private IndexManager indexManager = null;
@Override
public String toString() {
return indexManager.minIndexKeyTuple + "|" + indexManager.lastIndexKeyTuple + "|" + indexManager.maxIndexKeyTuple;
}
public IndexedStorageRecordReader(IndexManager im) {
this.indexManager = im;
}
/**
* Class to compare record readers using underlying indexes
*
*/
public static class IndexedStorageRecordReaderComparator implements Comparator<IndexedStorageRecordReader> {
@Override
public int compare(IndexedStorageRecordReader o1, IndexedStorageRecordReader o2) {
Tuple t1 = (o1.indexManager.lastIndexKeyTuple == null) ? o1.indexManager.minIndexKeyTuple : o1.indexManager.lastIndexKeyTuple;
Tuple t2 = (o2.indexManager.lastIndexKeyTuple == null) ? o2.indexManager.minIndexKeyTuple : o2.indexManager.lastIndexKeyTuple;
return t1.compareTo(t2);
}
}
public static class IndexedStorageLineReader {
private static final int DEFAULT_BUFFER_SIZE = 64 * 1024;
private int bufferSize = DEFAULT_BUFFER_SIZE;
private InputStream in;
private byte[] buffer;
// the number of bytes of real data in the buffer
private int bufferLength = 0;
// the current position in the buffer
private int bufferPosn = 0;
private long bufferOffset = 0;
private static final byte CR = '\r';
private static final byte LF = '\n';
/**
* Create a line reader that reads from the given stream using the
* default buffer-size (64k).
* @param in The input stream
* @throws IOException
*/
public IndexedStorageLineReader(InputStream in) {
this(in, DEFAULT_BUFFER_SIZE);
}
/**
* Create a line reader that reads from the given stream using the
* given buffer-size.
* @param in The input stream
* @param bufferSize Size of the read buffer
* @throws IOException
*/
public IndexedStorageLineReader(InputStream in, int bufferSize) {
if( !(in instanceof Seekable) || !(in instanceof PositionedReadable) ) {
throw new IllegalArgumentException(
"In is not an instance of Seekable or PositionedReadable");
}
this.in = in;
this.bufferSize = bufferSize;
this.buffer = new byte[this.bufferSize];
}
/**
* Create a line reader that reads from the given stream using the
* <code>io.file.buffer.size</code> specified in the given
* <code>Configuration</code>.
* @param in input stream
* @param conf configuration
* @throws IOException
*/
public IndexedStorageLineReader(InputStream in, Configuration conf) throws IOException {
this(in, conf.getInt("io.file.buffer.size", DEFAULT_BUFFER_SIZE));
}
/**
* Close the underlying stream.
* @throws IOException
*/
public void close() throws IOException {
in.close();
}
/**
* Read one line from the InputStream into the given Text. A line
* can be terminated by one of the following: '\n' (LF) , '\r' (CR),
* or '\r\n' (CR+LF). EOF also terminates an otherwise unterminated
* line.
*
* @param str the object to store the given line (without newline)
* @param maxLineLength the maximum number of bytes to store into str;
* the rest of the line is silently discarded.
* @param maxBytesToConsume the maximum number of bytes to consume
* in this call. This is only a hint, because if the line cross
* this threshold, we allow it to happen. It can overshoot
* potentially by as much as one buffer length.
*
* @return the number of bytes read including the (longest) newline
* found.
*
* @throws IOException if the underlying stream throws
*/
public int readLine(Text str, int maxLineLength,
int maxBytesToConsume) throws IOException {
/* We're reading data from in, but the head of the stream may be
* already buffered in buffer, so we have several cases:
* 1. No newline characters are in the buffer, so we need to copy
* everything and read another buffer from the stream.
* 2. An unambiguously terminated line is in buffer, so we just
* copy to str.
* 3. Ambiguously terminated line is in buffer, i.e. buffer ends
* in CR. In this case we copy everything up to CR to str, but
* we also need to see what follows CR: if it's LF, then we
* need consume LF as well, so next call to readLine will read
* from after that.
* We use a flag prevCharCR to signal if previous character was CR
* and, if it happens to be at the end of the buffer, delay
* consuming it until we have a chance to look at the char that
* follows.
*/
str.clear();
int txtLength = 0; //tracks str.getLength(), as an optimization
int newlineLength = 0; //length of terminating newline
boolean prevCharCR = false; //true of prev char was CR
long bytesConsumed = 0;
do {
int startPosn = bufferPosn; //starting from where we left off the last time
if (bufferPosn >= bufferLength) {
startPosn = bufferPosn = 0;
if (prevCharCR)
++bytesConsumed; //account for CR from previous read
bufferOffset = ((Seekable)in).getPos();
bufferLength = in.read(buffer);
if (bufferLength <= 0)
break; // EOF
}
for (; bufferPosn < bufferLength; ++bufferPosn) { //search for newline
if (buffer[bufferPosn] == LF) {
newlineLength = (prevCharCR) ? 2 : 1;
++bufferPosn; // at next invocation proceed from following byte
break;
}
if (prevCharCR) { //CR + notLF, we are at notLF
newlineLength = 1;
break;
}
prevCharCR = (buffer[bufferPosn] == CR);
}
int readLength = bufferPosn - startPosn;
if (prevCharCR && newlineLength == 0)
--readLength; //CR at the end of the buffer
bytesConsumed += readLength;
int appendLength = readLength - newlineLength;
if (appendLength > maxLineLength - txtLength) {
appendLength = maxLineLength - txtLength;
}
if (appendLength > 0) {
str.append(buffer, startPosn, appendLength);
txtLength += appendLength;
}
} while (newlineLength == 0 && bytesConsumed < maxBytesToConsume);
if (bytesConsumed > (long)Integer.MAX_VALUE)
throw new IOException("Too many bytes before newline: " + bytesConsumed);
return (int)bytesConsumed;
}
/**
* Read from the InputStream into the given Text.
* @param str the object to store the given line
* @param maxLineLength the maximum number of bytes to store into str.
* @return the number of bytes read including the newline
* @throws IOException if the underlying stream throws
*/
public int readLine(Text str, int maxLineLength) throws IOException {
return readLine(str, maxLineLength, Integer.MAX_VALUE);
}
/**
* Read from the InputStream into the given Text.
* @param str the object to store the given line
* @return the number of bytes read including the newline
* @throws IOException if the underlying stream throws
*/
public int readLine(Text str) throws IOException {
return readLine(str, Integer.MAX_VALUE, Integer.MAX_VALUE);
}
/**
* If given offset is within the buffer, adjust the buffer position to read from
* otherwise seek to the given offset from start of the file.
* @param offset
* @throws IOException
*/
public void seek(long offset) throws IOException {
if ((offset >= bufferOffset) && (offset < (bufferOffset + bufferLength)))
bufferPosn = (int) (offset - bufferOffset);
else {
bufferPosn = bufferLength;
((Seekable)in).seek(offset);
}
}
}
@Override
public void initialize(InputSplit genericSplit, TaskAttemptContext context)
throws IOException, InterruptedException {
FileSplit split = (FileSplit) genericSplit;
Configuration job = context.getConfiguration();
this.maxLineLength = job.getInt(MRConfiguration.LINERECORDREADER_MAXLENGTH, Integer.MAX_VALUE);
start = split.getStart();
end = start + split.getLength();
final Path file = split.getPath();
FileSystem fs = file.getFileSystem(job);
FSDataInputStream fileIn = fs.open(split.getPath());
boolean skipFirstLine = false;
if (start != 0) {
skipFirstLine = true;
--start;
fileIn.seek(start);
}
in = new IndexedStorageLineReader(fileIn, job);
if (skipFirstLine) {
start += in.readLine(new Text(), 0, (int)Math.min((long)Integer.MAX_VALUE, end - start));
}
this.pos = start;
}
public void seek(long offset) throws IOException {
in.seek(offset);
pos = offset;
}
/**
* Scan the index for given key and seek to appropriate offset in the data
* @param keys to look for
* @return true if the given key was found, false otherwise
* @throws IOException
*/
public boolean seekNear(Tuple keys) throws IOException {
boolean ret = false;
Tuple indexTuple = this.indexManager.ScanIndex(keys);
if (indexTuple != null) {
long offset = this.indexManager.getOffset(indexTuple) ;
in.seek(offset);
if (keys.compareTo(this.indexManager.getIndexKeyTuple(indexTuple)) == 0) {
ret = true;
}
}
return ret;
}
@Override
public boolean nextKeyValue() throws IOException,
InterruptedException {
if (key == null) {
key = new LongWritable();
}
key.set(pos);
if (value == null) {
value = new Text();
}
int newSize = 0;
while (pos < end) {
newSize = in.readLine(value, maxLineLength,
Math.max((int)Math.min(Integer.MAX_VALUE, end-pos),
maxLineLength));
if (newSize == 0) {
break;
}
pos += newSize;
if (newSize < maxLineLength) {
break;
}
}
if (newSize == 0) {
key = null;
value = null;
return false;
} else {
return true;
}
}
@Override
public LongWritable getCurrentKey() throws IOException,
InterruptedException {
return key;
}
@Override
public Text getCurrentValue() throws IOException,
InterruptedException {
return value;
}
@Override
public float getProgress() throws IOException, InterruptedException {
if (start == end) {
return 0.0f;
} else {
return Math.min(1.0f, (pos - start) / (float)(end - start));
}
}
@Override
public void close() throws IOException {
if (in != null) {
in.close();
}
}
}
}
/**
* List of record readers.
*/
protected IndexedStorageRecordReader[] readers = null;
/**
* Index into the the list of readers to the current reader.
* Readers before this index have been fully scanned for keys.
*/
protected int currentReaderIndexStart = 0;
/**
* Delimiter to use between fields
*/
protected byte fieldDelimiter = '\t';
/**
* Offsets to index keys in tuple
*/
final protected int[] offsetsToIndexKeys;
/**
* Comparator used to compare key tuples.
*/
protected Comparator<IndexedStorageRecordReader> readerComparator = new IndexedStorageInputFormat.IndexedStorageRecordReader.IndexedStorageRecordReaderComparator();
}
| |
/*
* 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 macromedia.asc.parser;
import macromedia.asc.semantics.Value;
import macromedia.asc.util.Context;
import macromedia.asc.util.NumberUsage;
import java.io.PrintWriter;
import static macromedia.asc.parser.Tokens.*;
/**
* NodePrinter.h
*
* This visitor prints the parse tree
*/
public class NodePrinter implements Evaluator
{
private PrintWriter out;
private int level;
private int mode;
private void separate()
{
if (mode == machine_mode)
{
out.print("|");
}
}
private void push_in()
{
++level;
if (mode == machine_mode)
{
out.print("[");
}
else
{
out.print(" ");
}
}
private void pop_out()
{
if (mode == machine_mode)
{
out.print("]");
}
--level;
}
private void indent()
{
if (mode == man_mode)
{
out.println();
for (int i = level; i != 0; --i)
{
out.print(" ");
}
}
}
// public:
public static final int man_mode = 0;
public static final int machine_mode = 1;
public boolean checkFeature(Context cx, Node node)
{
return true; // return true;
}
public NodePrinter()
{
this(man_mode, new PrintWriter(System.out, true));
}
public NodePrinter(PrintWriter out)
{
this(man_mode, out);
}
public NodePrinter(int mode, PrintWriter out)
{
this.out = out;
this.level = 0;
this.mode = mode;
}
// Base node
public Value evaluate(Context cx, Node node)
{
indent();
out.print("error:undefined printer method");
return null;
}
// Expression evaluators
public Value evaluate(Context cx, IdentifierNode node)
{
indent();
if(node instanceof TypeIdentifierNode)
{
out.print("typeidentifier ");
}
else if (node.isAttr())
{
out.print("attributeidentifier ");
}
else
{
out.print("identifier ");
}
out.print(node.name);
if(node instanceof TypeIdentifierNode)
{
out.print("types ");
push_in();
((TypeIdentifierNode)node).typeArgs.evaluate(cx, this);
pop_out();
}
return null;
}
// Expression evaluators
public Value evaluate(Context cx, IncrementNode node)
{
indent();
out.print("increment");
out.print((node.getMode() == LEFTBRACKET_TOKEN ? " bracket" :
node.getMode() == LEFTPAREN_TOKEN ? " filter" :
node.getMode() == DOUBLEDOT_TOKEN ? " descend" :
node.getMode() == DOT_TOKEN ? " dot" :
node.getMode() == EMPTY_TOKEN ? " lexical" : " error"));
out.print((node.isPostfix ? " postfix " : " prefix ") + Token.getTokenClassName(node.op));
push_in();
pop_out();
separate();
push_in();
if (node.expr != null)
{
node.expr.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, ThisExpressionNode node)
{
indent();
out.print("this");
return null;
}
public Value evaluate(Context cx, QualifiedIdentifierNode node)
{
indent();
if (node.isAttr())
{
out.print("qualifiedattributeidentifier ");
}
else
{
out.print("qualifiedidentifier ");
}
out.print(node.name);
if (node.qualifier != null)
{
push_in();
indent();
out.print("qualifier");
push_in();
node.qualifier.evaluate(cx, this);
pop_out();
pop_out();
}
return null;
}
public Value evaluate(Context cx, QualifiedExpressionNode node)
{
indent();
if (node.isAttr())
{
out.print("qualifiedattributeexpression ");
}
else
{
out.print("qualifiedexpression ");
}
out.print(node.name);
if (node.qualifier != null)
{
push_in();
indent();
out.print("qualifier");
push_in();
node.qualifier.evaluate(cx, this);
pop_out();
pop_out();
}
if (node.expr != null)
{
push_in();
indent();
out.print("expr");
push_in();
node.expr.evaluate(cx, this);
pop_out();
pop_out();
}
return null;
}
public Value evaluate(Context cx, LiteralBooleanNode node)
{
indent();
out.print("literalboolean ");
out.print(node.value ? 1 : 0);
return null;
}
public Value evaluate(Context cx, LiteralNumberNode node)
{
indent();
out.print("literalnumber:");
out.print(node.value);
return null;
}
public Value evaluate(Context cx, LiteralStringNode node)
{
indent();
out.print("literalstring:");
out.print(node.value);
return null;
}
public Value evaluate(Context cx, LiteralNullNode node)
{
indent();
out.print("literalnull");
return null;
}
public Value evaluate(Context cx, LiteralRegExpNode node)
{
indent();
out.print("literalregexp:");
out.print(node.value);
return null;
}
public Value evaluate(Context cx, LiteralXMLNode node)
{
indent();
out.print("literalxml");
push_in();
if (node.list != null)
{
node.list.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, FunctionCommonNode node)
{
indent();
out.print("functioncommon");
push_in();
if (node.signature != null)
{
node.signature.evaluate(cx, this);
}
separate();
if (node.body != null)
{
node.body.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, ParenExpressionNode node)
{
indent();
out.print("paren");
return null;
}
public Value evaluate(Context cx, ParenListExpressionNode node)
{
indent();
out.print("parenlist");
if (node.expr != null)
{
node.expr.evaluate(cx, this);
}
return null;
}
public Value evaluate(Context cx, LiteralObjectNode node)
{
indent();
out.print("literalobject");
push_in();
if (node.fieldlist != null)
{
node.fieldlist.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, LiteralFieldNode node)
{
indent();
out.print("literalfield");
push_in();
if (node.name != null)
{
node.name.evaluate(cx, this);
}
separate();
if (node.value != null)
{
node.value.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, LiteralArrayNode node)
{
indent();
out.print("literalarray");
push_in();
if (node.elementlist != null)
{
node.elementlist.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, LiteralVectorNode node)
{
indent();
out.print("new<");
node.type.evaluate(cx, this);
out.print(">");
push_in();
if (node.elementlist != null)
{
node.elementlist.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, SuperExpressionNode node)
{
indent();
out.print("superexpression");
push_in();
if (node.expr != null)
{
node.expr.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, MemberExpressionNode node)
{
indent();
out.print("member");
push_in();
if (node.base != null)
{
node.base.evaluate(cx, this);
}
separate();
if (node.selector != null)
{
node.selector.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, InvokeNode node)
{
indent();
out.print("invoke");
out.print((node.getMode() == LEFTBRACKET_TOKEN ? " bracket" :
node.getMode() == LEFTPAREN_TOKEN ? " filter" :
node.getMode() == DOUBLEDOT_TOKEN ? " descend" :
node.getMode() == EMPTY_TOKEN ? " lexical" : " dot"));
push_in();
out.print(node.name);
separate();
if (node.args != null)
{
node.args.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, CallExpressionNode node)
{
indent();
out.print((node.is_new ? "construct" : "call"));
out.print((node.getMode() == LEFTBRACKET_TOKEN ? " bracket" :
node.getMode() == LEFTPAREN_TOKEN ? " filter" :
node.getMode() == DOUBLEDOT_TOKEN ? " descend" :
node.getMode() == EMPTY_TOKEN ? " lexical" : " dot"));
push_in();
if (node.expr != null)
{
node.expr.evaluate(cx, this);
}
separate();
if (node.args != null)
{
node.args.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, DeleteExpressionNode node)
{
indent();
out.print("delete");
out.print((node.getMode() == LEFTBRACKET_TOKEN ? " bracket" :
node.getMode() == LEFTPAREN_TOKEN ? " filter" :
node.getMode() == DOUBLEDOT_TOKEN ? " descend" :
node.getMode() == EMPTY_TOKEN ? " lexical" : " dot"));
push_in();
if (node.expr != null)
{
node.expr.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, ApplyTypeExprNode node)
{
indent();
out.print("applytype");
push_in();
node.typeArgs.evaluate(cx, this);
pop_out();
return null;
}
public Value evaluate(Context cx, GetExpressionNode node)
{
indent();
out.print("get");
out.print((node.getMode() == LEFTBRACKET_TOKEN ? " bracket" :
node.getMode() == LEFTPAREN_TOKEN ? " filter" :
node.getMode() == DOUBLEDOT_TOKEN ? " descend" :
node.getMode() == EMPTY_TOKEN ? " lexical" : " dot"));
push_in();
if (node.expr != null)
{
node.expr.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, SetExpressionNode node)
{
indent();
out.print("set");
out.print((node.getMode() == LEFTBRACKET_TOKEN ? " bracket" :
node.getMode() == LEFTPAREN_TOKEN ? " filter" :
node.getMode() == DOUBLEDOT_TOKEN ? " descend" :
node.getMode() == EMPTY_TOKEN ? " lexical" : " dot"));
push_in();
if (node.expr != null)
{
node.expr.evaluate(cx, this);
}
separate();
if (node.args != null)
{
node.args.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, UnaryExpressionNode node)
{
indent();
out.print("unary");
push_in();
out.print(Token.getTokenClassName(node.op));
pop_out();
separate();
push_in();
if (node.expr != null)
{
node.expr.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, BinaryExpressionNode node)
{
indent();
out.print("binary");
push_in();
out.print(Token.getTokenClassName(node.op));
pop_out();
separate();
push_in();
if (node.lhs != null)
{
node.lhs.evaluate(cx, this);
}
separate();
if (node.rhs != null)
{
node.rhs.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, ConditionalExpressionNode node)
{
indent();
out.print("cond");
push_in();
if (node.condition != null)
{
node.condition.evaluate(cx, this);
}
pop_out();
separate();
push_in();
if (node.thenexpr != null)
{
node.thenexpr.evaluate(cx, this);
}
separate();
if (node.elseexpr != null)
{
node.elseexpr.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, ArgumentListNode node)
{
indent();
out.print("argumentlist");
push_in();
for (Node n : node.items)
{
n.evaluate(cx, this);
separate();
}
pop_out();
return null;
}
public Value evaluate(Context cx, ListNode node)
{
indent();
out.print("list");
push_in();
for (Node n : node.items)
{
n.evaluate(cx, this);
separate();
}
pop_out();
return null;
}
// Statements
public Value evaluate(Context cx, StatementListNode node)
{
indent();
out.print("statementlist");
push_in();
for (Node n : node.items)
{
if (n != null)
{
n.evaluate(cx, this);
}
}
pop_out();
return null;
}
public Value evaluate(Context cx, EmptyElementNode node)
{
indent();
out.print("empty");
return null;
}
public Value evaluate(Context cx, EmptyStatementNode node)
{
indent();
out.print("empty");
return null;
}
public Value evaluate(Context cx, ExpressionStatementNode node)
{
indent();
out.print("expression");
push_in();
if (node.expr != null)
{
node.expr.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, SuperStatementNode node)
{
indent();
out.print("super");
push_in();
if (node.call.args != null)
{
node.call.args.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, LabeledStatementNode node)
{
indent();
out.print("labeled");
push_in();
if (node.label != null)
{
node.label.evaluate(cx, this);
}
pop_out();
separate();
push_in();
if (node.statement != null)
{
node.statement.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, IfStatementNode node)
{
indent();
out.print("if");
push_in();
if (node.condition != null)
{
node.condition.evaluate(cx, this);
}
pop_out();
separate();
push_in();
if (node.thenactions != null)
{
node.thenactions.evaluate(cx, this);
}
pop_out();
separate();
push_in();
if (node.elseactions != null)
{
node.elseactions.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, SwitchStatementNode node)
{
indent();
out.print("switch");
push_in();
if (node.expr != null)
{
node.expr.evaluate(cx, this);
}
pop_out();
separate();
push_in();
if (node.statements != null)
{
node.statements.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, CaseLabelNode node)
{
indent();
out.print("case");
push_in();
if (node.label != null)
{
node.label.evaluate(cx, this);
}
else
{
out.print("default");
}
pop_out();
return null;
}
public Value evaluate(Context cx, DoStatementNode node)
{
indent();
out.print("do");
push_in();
if (node.expr != null)
{
node.expr.evaluate(cx, this);
}
pop_out();
separate();
push_in();
if (node.statements != null)
{
node.statements.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, WhileStatementNode node)
{
indent();
out.print("while");
push_in();
if (node.expr != null)
{
node.expr.evaluate(cx, this);
}
pop_out();
separate();
push_in();
if (node.statement != null)
{
node.statement.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, ForStatementNode node)
{
indent();
out.print("for");
push_in();
if (node.initialize != null)
{
node.initialize.evaluate(cx, this);
}
pop_out();
separate();
push_in();
if (node.test != null)
{
node.test.evaluate(cx, this);
}
pop_out();
separate();
push_in();
if (node.increment != null)
{
node.increment.evaluate(cx, this);
}
pop_out();
separate();
push_in();
if (node.statement != null)
{
node.statement.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, WithStatementNode node)
{
indent();
out.print("with");
push_in();
if (node.expr != null)
{
node.expr.evaluate(cx, this);
}
pop_out();
separate();
push_in();
if (node.statement != null)
{
node.statement.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, ContinueStatementNode node)
{
indent();
out.print("continue");
push_in();
if (node.id != null)
{
node.id.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, BreakStatementNode node)
{
indent();
out.print("break");
push_in();
if (node.id != null)
{
node.id.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, ReturnStatementNode node)
{
indent();
out.print("return");
push_in();
if (node.expr != null)
{
node.expr.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, ThrowStatementNode node)
{
indent();
out.print("throw");
push_in();
if (node.expr != null)
{
node.expr.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, TryStatementNode node)
{
indent();
out.print("try");
push_in();
if (node.tryblock != null)
{
node.tryblock.evaluate(cx, this);
}
pop_out();
separate();
push_in();
if (node.catchlist != null)
{
node.catchlist.evaluate(cx, this);
}
pop_out();
separate();
push_in();
if (node.finallyblock != null)
{
node.finallyblock.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, CatchClauseNode node)
{
indent();
out.print("catch");
push_in();
if (node.parameter != null)
{
node.parameter.evaluate(cx, this);
}
pop_out();
separate();
push_in();
if (node.statements != null)
{
node.statements.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, FinallyClauseNode node)
{
indent();
out.print("finally");
push_in();
if (node.statements != null)
{
node.statements.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, UseDirectiveNode node)
{
indent();
out.print("use");
if( node.expr != null )
{
node.expr.evaluate(cx,this);
}
return null;
}
public Value evaluate(Context cx, IncludeDirectiveNode node)
{
indent();
out.print("include");
push_in();
if (node.filespec != null)
{
node.filespec.evaluate(cx, this);
}
separate();
if (node.program != null)
{
// node.program.evaluate(cx, this);
}
pop_out();
return null;
}
// Definitions
public Value evaluate(Context cx, ImportDirectiveNode node)
{
indent();
out.print("import");
push_in();
if (node.attrs != null)
{
node.attrs.evaluate(cx, this);
}
pop_out();
separate();
push_in();
if (node.name != null)
{
node.name.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, AttributeListNode node)
{
indent();
out.print("attributelist");
push_in();
for (Node n : node.items)
{
n.evaluate(cx, this);
separate();
}
pop_out();
return null;
}
public Value evaluate(Context cx, VariableDefinitionNode node)
{
indent();
if (node.kind == CONST_TOKEN)
{
out.print("const");
}
else
{
out.print("var");
}
push_in();
if (node.attrs != null)
{
node.attrs.evaluate(cx, this);
}
pop_out();
separate();
push_in();
if (node.list != null)
{
node.list.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, VariableBindingNode node)
{
indent();
out.print("variablebinding");
push_in();
if (node.variable != null)
{
node.variable.evaluate(cx, this);
}
separate();
if (node.initializer != null)
{
node.initializer.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, UntypedVariableBindingNode node)
{
indent();
out.print("untypedvariablebinding");
push_in();
if (node.identifier != null)
{
node.identifier.evaluate(cx, this);
}
separate();
if (node.initializer != null)
{
node.initializer.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, TypedIdentifierNode node)
{
indent();
out.print("typedidentifier");
push_in();
if (node.identifier != null)
{
node.identifier.evaluate(cx, this);
}
separate();
if (node.type != null)
{
node.type.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, BinaryFunctionDefinitionNode node)
{
return null;
}
public Value evaluate(Context cx, FunctionDefinitionNode node)
{
indent();
out.print("function");
push_in();
if (node.attrs != null)
{
node.attrs.evaluate(cx, this);
}
separate();
if (node.name != null)
{
node.name.evaluate(cx, this);
}
separate();
if (node.fexpr != null)
{
node.fexpr.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, FunctionNameNode node)
{
indent();
out.print("functionname");
out.print((node.kind == GET_TOKEN ? " get" :
node.kind == SET_TOKEN ? " set" : ""));
push_in();
if (node.identifier != null)
{
node.identifier.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, FunctionSignatureNode node)
{
indent();
out.print(node.inits != null ? "constructorsignature" : "functionsignature" );
push_in();
if (node.parameter != null)
{
node.parameter.evaluate(cx, this);
}
separate();
if (node.result != null)
{
node.result.evaluate(cx, this);
}
if (node.inits != null)
{
node.inits.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, ParameterNode node)
{
indent();
out.print("parameter");
if (node.kind == CONST_TOKEN)
{
out.print(" const");
}
push_in();
if (node.identifier != null)
{
node.identifier.evaluate(cx, this);
}
separate();
if (node.init != null)
{
node.init.evaluate(cx, this);
}
separate();
if (node.type != null)
{
node.type.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, RestExpressionNode node)
{
indent();
out.print("restexpression");
push_in();
if (node.expr != null)
{
node.expr.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, RestParameterNode node)
{
indent();
out.print("restparameter");
push_in();
if (node.parameter != null)
{
node.parameter.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, ClassDefinitionNode node)
{
indent();
out.print("class");
push_in();
if (node.attrs != null)
{
node.attrs.evaluate(cx, this);
}
separate();
if (node.name != null)
{
node.name.evaluate(cx, this);
}
separate();
if (node.baseclass != null)
{
node.baseclass.evaluate(cx, this);
}
separate();
if (node.interfaces != null)
{
node.interfaces.evaluate(cx, this);
}
separate();
if (node.statements != null)
{
node.statements.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, InterfaceDefinitionNode node)
{
indent();
out.print("interface");
push_in();
if (node.attrs != null)
{
node.attrs.evaluate(cx, this);
}
separate();
if (node.name != null)
{
node.name.evaluate(cx, this);
}
separate();
if (node.interfaces != null)
{
node.interfaces.evaluate(cx, this);
}
separate();
if (node.statements != null)
{
node.statements.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, ClassNameNode node)
{
indent();
out.print("classname");
push_in();
if (node.pkgname != null)
{
node.pkgname.evaluate(cx, this);
}
pop_out();
separate();
push_in();
if (node.ident != null)
{
node.ident.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, InheritanceNode node)
{
if (node.baseclass != null)
{
indent();
out.print("extends");
push_in();
node.baseclass.evaluate(cx, this);
pop_out();
}
separate();
if (node.interfaces != null)
{
indent();
out.print("implements");
push_in();
node.interfaces.evaluate(cx, this);
pop_out();
}
return null;
}
public Value evaluate(Context cx, NamespaceDefinitionNode node)
{
indent();
out.print("namespace");
push_in();
if (node.attrs != null)
{
node.attrs.evaluate(cx, this);
}
pop_out();
separate();
push_in();
if (node.name != null)
{
node.name.evaluate(cx, this);
}
pop_out();
separate();
push_in();
if (node.value != null)
{
node.value.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, ConfigNamespaceDefinitionNode node)
{
indent();
out.print("config namespace");
push_in();
if (node.attrs != null)
{
node.attrs.evaluate(cx, this);
}
pop_out();
separate();
push_in();
if (node.name != null)
{
node.name.evaluate(cx, this);
}
pop_out();
separate();
push_in();
if (node.value != null)
{
node.value.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, PackageDefinitionNode node)
{
indent();
out.print("package");
push_in();
if (node.name != null)
{
node.name.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, PackageIdentifiersNode node)
{
indent();
out.print("packageidentifiers");
push_in();
for (IdentifierNode n : node.list)
{
n.evaluate(cx, this);
separate();
}
pop_out();
return null;
}
public Value evaluate(Context cx, PackageNameNode node)
{
indent();
out.print("packagename");
push_in();
if (node.id != null)
{
node.id.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, ProgramNode node)
{
indent();
out.print("program");
push_in();
if (node.statements != null)
{
node.statements.evaluate(cx, this);
}
pop_out();
out.println();
return null;
}
public Value evaluate(Context cx, ErrorNode node)
{
indent();
out.print("error");
out.print(node.errorCode);
return null;
}
public Value evaluate(Context cx, ToObjectNode node)
{
indent();
out.print("toobject");
push_in();
if (node.expr != null)
{
node.expr.evaluate(cx, this);
}
pop_out();
out.println();
return null;
}
public Value evaluate(Context cx, LoadRegisterNode node)
{
indent();
out.print("loadregister");
push_in();
if (node.reg != null)
{
node.reg.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, StoreRegisterNode node)
{
indent();
out.print("storeregister");
push_in();
if (node.reg != null)
{
node.reg.evaluate(cx, this);
}
pop_out();
push_in();
if (node.expr != null)
{
node.expr.evaluate(cx, this);
}
pop_out();
out.println();
return null;
}
public Value evaluate(Context cx, RegisterNode node)
{
indent();
out.print("register");
push_in();
out.print(node.index);
return null;
}
public Value evaluate(Context cx, HasNextNode node)
{
indent();
out.print("hasNext");
push_in();
if (node.objectRegister != null)
{
node.objectRegister.evaluate(cx, this);
}
pop_out();
push_in();
if (node.indexRegister != null)
{
node.indexRegister.evaluate(cx, this);
}
pop_out();
out.println();
return null;
}
public Value evaluate(Context cx, BoxNode node)
{
indent();
out.print("box");
out.print(node.actual);
push_in();
if (node.expr != null)
{
node.expr.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, CoerceNode node)
{
indent();
out.print("coerce");
push_in();
if (node.expr != null)
{
node.expr.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, PragmaNode node)
{
indent();
out.print("pragma");
push_in();
if (node.list != null)
{
node.list.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate(Context cx, UsePrecisionNode node)
{
indent();
out.print("usePrecision(" + node.precision + ")");
return null;
}
private static String[] usageName = {"Number", "decimal", "double", "int", "uint"};
public Value evaluate(Context cx, UseNumericNode node)
{
indent();
out.print("useNumeric(" + usageName[node.numeric_mode] + ")");
return null;
}
public Value evaluate(Context cx, UseRoundingNode node)
{
indent();
out.print("useRounding(" + NumberUsage.roundingModeName[node.mode] + ")");
return null;
}
public Value evaluate(Context cx, PragmaExpressionNode node)
{
indent();
out.print("pragmaitem");
push_in();
if (node.identifier != null)
{
node.identifier.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate( Context cx, ParameterListNode node )
{
indent();
out.print("parameterlist");
push_in();
for (int i = 0, size = node.items.size(); i < size; i++)
{
ParameterNode param = node.items.get(i);
if (param != null)
{
param.evaluate(cx, this);
}
if (i < size - 1)
{
separate();
}
}
pop_out();
return null;
}
public Value evaluate(Context cx, MetaDataNode node)
{
if (node.data != null)
{
MetaDataEvaluator mde = new MetaDataEvaluator();
mde.evaluate(cx, node);
}
indent();
out.print("metadata:");
out.print(node.getId() !=null? node.getId() :"");
out.print(" ");
for (int i = 0, length = (node.getValues() == null) ? 0 : node.getValues().length; i < length; i++)
{
Value v = node.getValues()[i];
if (v instanceof MetaDataEvaluator.KeyValuePair)
{
MetaDataEvaluator.KeyValuePair pair = (MetaDataEvaluator.KeyValuePair) v;
out.print("[" + pair.key + "," + pair.obj + "]");
}
if (v instanceof MetaDataEvaluator.KeylessValue)
{
MetaDataEvaluator.KeylessValue val = (MetaDataEvaluator.KeylessValue) v;
out.print("[" + val.obj + "]");
}
}
return null;
}
public Value evaluate(Context cx, DefaultXMLNamespaceNode node)
{
indent();
out.print("dxns");
push_in();
if (node.expr != null)
{
node.expr.evaluate(cx, this);
}
pop_out();
return null;
}
public Value evaluate( Context cx, DocCommentNode node )
{
evaluate(cx,(MetaDataNode)node);
return null;
}
public Value evaluate( Context cx, ImportNode node )
{
return null;
}
public Value evaluate( Context cx, BinaryProgramNode node )
{
return null;
}
public Value evaluate(Context cx, BinaryClassDefNode node)
{
return null;
}
public Value evaluate(Context cx, BinaryInterfaceDefinitionNode node)
{
return null;
}
public Value evaluate(Context cx, TypeExpressionNode node)
{
indent();
out.print("typeexpr");
push_in();
if (node.expr != null)
{
node.expr.evaluate(cx, this);
}
pop_out();
return null;
}
}
| |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.refactoring.typeMigration;
import com.intellij.codeInsight.generation.GetterSetterPrototypeProvider;
import com.intellij.codeInsight.intention.impl.SplitDeclarationAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.*;
import com.intellij.psi.controlFlow.DefUseUtil;
import com.intellij.psi.impl.PsiSubstitutorImpl;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.*;
import com.intellij.refactoring.typeMigration.usageInfo.TypeMigrationUsageInfo;
import com.intellij.util.CommonProcessors;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.HashMap;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
import java.util.Map;
/**
* @author anna
* Date: 04-Apr-2008
*/
class TypeMigrationStatementProcessor extends JavaRecursiveElementVisitor {
private final PsiElement myStatement;
private final TypeMigrationLabeler myLabeler;
private static final Logger LOG = Logger.getInstance(TypeMigrationStatementProcessor.class);
private final TypeEvaluator myTypeEvaluator;
public TypeMigrationStatementProcessor(final PsiElement expression, TypeMigrationLabeler labeler) {
myStatement = expression;
myLabeler = labeler;
myTypeEvaluator = myLabeler.getTypeEvaluator();
}
@Override
public void visitAssignmentExpression(PsiAssignmentExpression expression) {
super.visitAssignmentExpression(expression);
final PsiExpression lExpression = expression.getLExpression();
final TypeView left = new TypeView(lExpression);
final PsiExpression rExpression = expression.getRExpression();
if (rExpression == null) return;
final TypeView right = new TypeView(rExpression);
final IElementType sign = expression.getOperationTokenType();
final PsiType ltype = left.getType();
final PsiType rtype = right.getType();
if (ltype == null || rtype == null) return;
if (sign != JavaTokenType.EQ) {
final IElementType binaryOperator = TypeConversionUtil.convertEQtoOperation(sign);
if (!TypeConversionUtil.isBinaryOperatorApplicable(binaryOperator, ltype, rtype, false)) {
if (left.isChanged()) {
findConversionOrFail(expression, lExpression, left.getTypePair());
}
if (right.isChanged()) {
findConversionOrFail(expression, rExpression, right.getTypePair());
}
return;
}
}
switch (TypeInfection.getInfection(left, right)) {
case TypeInfection.NONE_INFECTED:
break;
case TypeInfection.LEFT_INFECTED:
myLabeler.migrateExpressionType(rExpression, ltype, myStatement, TypeConversionUtil.isAssignable(ltype, rtype) && !isSetter(expression), true);
break;
case TypeInfection.RIGHT_INFECTED:
if (lExpression instanceof PsiReferenceExpression &&
((PsiReferenceExpression)lExpression).resolve() instanceof PsiLocalVariable &&
!canBeVariableType(rtype)) {
tryToRemoveLocalVariableAssignment((PsiLocalVariable)((PsiReferenceExpression)lExpression).resolve(), rExpression, rtype);
} else {
myLabeler.migrateExpressionType(lExpression, rtype, myStatement, TypeConversionUtil.isAssignable(ltype, rtype), false);
}
break;
case TypeInfection.BOTH_INFECTED:
addTypeUsage(lExpression);
addTypeUsage(rExpression);
break;
default:
LOG.error("Must not happen.");
}
}
@Override
public void visitArrayAccessExpression(final PsiArrayAccessExpression expression) {
super.visitArrayAccessExpression(expression);
final PsiExpression indexExpression = expression.getIndexExpression();
if (indexExpression != null) {
checkIndexExpression(indexExpression);
}
final TypeView typeView = new TypeView(expression.getArrayExpression());
if (typeView.isChanged() && typeView.getType() instanceof PsiClassType) {
final TypeConversionDescriptorBase conversion =
myLabeler.getRules().findConversion(typeView.getTypePair().first, typeView.getType(), null, expression, false, myLabeler);
if (conversion == null) {
myLabeler.markFailedConversion(typeView.getTypePair(), expression);
}
else {
myLabeler.setConversionMapping(expression, conversion);
myTypeEvaluator.setType(new TypeMigrationUsageInfo(expression), myTypeEvaluator.evaluateType(expression));
}
}
}
@Override
public void visitSwitchLabelStatement(PsiSwitchLabelStatement statement) {
super.visitSwitchLabelStatement(statement);
final PsiExpression caseValue = statement.getCaseValue();
if (caseValue != null) {
final TypeView typeView = new TypeView(caseValue);
if (typeView.isChanged()) {
final PsiSwitchStatement switchStatement = statement.getEnclosingSwitchStatement();
if (switchStatement != null) {
final PsiExpression expression = switchStatement.getExpression();
myLabeler.migrateExpressionType(expression, typeView.getType(), myStatement, false, false);
}
}
}
}
@Override
public void visitInstanceOfExpression(final PsiInstanceOfExpression expression) {
super.visitInstanceOfExpression(expression);
final PsiTypeElement typeElement = expression.getCheckType();
if (typeElement != null) {
final PsiExpression consideredExpression = expression.getOperand();
final PsiType migrationType = myTypeEvaluator.evaluateType(consideredExpression);
final PsiType fixedType = typeElement.getType();
if (migrationType != null && !TypeConversionUtil.isAssignable(migrationType, fixedType)) {
myLabeler.markFailedConversion(Pair.create(fixedType, migrationType), consideredExpression);
}
}
}
@Override
public void visitTypeCastExpression(final PsiTypeCastExpression expression) {
super.visitTypeCastExpression(expression);
final PsiTypeElement typeElement = expression.getCastType();
if (typeElement != null) {
final PsiType fixedType = typeElement.getType();
final PsiType migrationType = myTypeEvaluator.evaluateType(expression.getOperand());
if (migrationType != null && !TypeConversionUtil.areTypesConvertible(migrationType, fixedType)) {
myLabeler.markFailedConversion(Pair.create(fixedType, migrationType), expression);
}
}
}
@Override
public void visitVariable(PsiVariable variable) {
super.visitVariable(variable);
final PsiExpression initializer = variable.getInitializer();
if (initializer != null && initializer.getType() != null) {
processVariable(variable, initializer, null, null, null, false);
}
}
@Override
public void visitReturnStatement(final PsiReturnStatement statement) { // has to change method return type corresponding to new value type
super.visitReturnStatement(statement);
final PsiElement method = PsiTreeUtil.getParentOfType(statement, PsiMethod.class, PsiLambdaExpression.class);
final PsiExpression value = statement.getReturnValue();
if (method != null && value != null) {
if (method instanceof PsiLambdaExpression) {
//todo [IDEA-133097]
return;
}
final PsiType returnType = ((PsiMethod)method).getReturnType();
final PsiType valueType = myTypeEvaluator.evaluateType(value);
if (returnType != null && valueType != null) {
if (!myLabeler.addMigrationRoot(method, valueType, myStatement, TypeConversionUtil.isAssignable(returnType, valueType) && !isGetter(value, method), true, true)
&& TypeMigrationLabeler.typeContainsTypeParameters(returnType, Collections.emptySet())) {
value.accept(this);
}
}
}
}
@Override
public void visitReferenceExpression(PsiReferenceExpression expression) {
final PsiExpression qualifierExpression = expression.getQualifierExpression();
if (qualifierExpression != null && qualifierExpression.isPhysical()) {
qualifierExpression.accept(this);
final TypeView qualifierView = new TypeView(qualifierExpression);
if (qualifierView.isChanged()) {
final PsiMember member = (PsiMember)expression.advancedResolve(false).getElement();
if (member == null) return;
final Pair<PsiType, PsiType> typePair = qualifierView.getTypePair();
final TypeConversionDescriptorBase conversion = myLabeler.getRules().findConversion(typePair.getFirst(), typePair.getSecond(), member, expression, false, myLabeler);
if (conversion == null) {
myLabeler.markFailedConversion(typePair, qualifierExpression);
} else {
final PsiElement parent = Util.getEssentialParent(expression);
final PsiType type = conversion.conversionType();
if (parent instanceof PsiMethodCallExpression) {
myLabeler.setConversionMapping((PsiMethodCallExpression)parent, conversion);
myTypeEvaluator.setType(new TypeMigrationUsageInfo(parent), type != null ? type: myTypeEvaluator.evaluateType((PsiExpression)parent));
} else {
myLabeler.setConversionMapping(expression, conversion);
myTypeEvaluator.setType(new TypeMigrationUsageInfo(expression), type != null ? type: myTypeEvaluator.evaluateType(expression));
}
}
}
}
}
@Override
public void visitIfStatement(PsiIfStatement statement) {
super.visitIfStatement(statement);
final PsiExpression condition = statement.getCondition();
if (condition != null) {
final TypeView view = new TypeView(condition);
if (view.isChanged()) { //means that boolean condition becomes non-boolean
findConversionOrFail(condition, condition, view.getTypePair());
}
}
}
@Override
public void visitForeachStatement(final PsiForeachStatement statement) {
super.visitForeachStatement(statement);
final PsiExpression value = statement.getIteratedValue();
final PsiParameter psiParameter = statement.getIterationParameter();
if (value != null) {
final TypeView typeView = new TypeView(value);
PsiType psiType = typeView.getType();
if (psiType instanceof PsiArrayType) {
psiType = ((PsiArrayType)psiType).getComponentType();
}
else if (psiType instanceof PsiClassType) {
final PsiClassType.ClassResolveResult resolveResult = ((PsiClassType)psiType).resolveGenerics();
final PsiClass psiClass = resolveResult.getElement();
final PsiType targetTypeParameter = getTargetTypeParameter(psiClass, value, typeView);
if (targetTypeParameter == null) return;
psiType = resolveResult.getSubstitutor().substitute(targetTypeParameter);
if (psiType instanceof PsiWildcardType) {
psiType = ((PsiWildcardType)psiType).getExtendsBound();
}
}
else {
return;
}
final TypeView left = new TypeView(psiParameter, null, null);
if (TypeInfection.getInfection(left, typeView) == TypeInfection.LEFT_INFECTED) {
PsiType iterableType;
final PsiType typeViewType = typeView.getType();
if (typeViewType instanceof PsiArrayType) {
iterableType = left.getType().createArrayType();
} else {
final PsiClass iterableClass = PsiUtil.resolveClassInType(typeViewType);
LOG.assertTrue(iterableClass != null);
final PsiType targetType = getTargetTypeParameter(iterableClass, value, typeView);
final PsiClass typeParam = PsiUtil.resolveClassInClassTypeOnly(targetType);
if (!(typeParam instanceof PsiTypeParameter)) return;
final Map<PsiTypeParameter, PsiType> substMap = Collections.singletonMap(((PsiTypeParameter)typeParam), left.getType());
final PsiElementFactory factory = JavaPsiFacade.getElementFactory(iterableClass.getProject());
iterableType = factory.createType(iterableClass, factory.createSubstitutor(substMap));
}
myLabeler.migrateExpressionType(value, iterableType, myStatement, TypeConversionUtil.isAssignable(iterableType, typeViewType), true);
} else {
processVariable(psiParameter, value, psiType, null, null, false);
}
}
}
private PsiType getTargetTypeParameter(PsiClass iterableClass, PsiExpression value, TypeView typeView) {
final Project project = iterableClass.getProject();
final PsiClass itClass =
JavaPsiFacade.getInstance(project).findClass("java.lang.Iterable", GlobalSearchScope.allScope(project));
if (itClass == null) return null;
if (!InheritanceUtil.isInheritorOrSelf(iterableClass, itClass, true)) {
findConversionOrFail(value, value, typeView.getTypePair());
return null;
}
final PsiSubstitutor aSubstitutor = TypeConversionUtil.getSuperClassSubstitutor(itClass, iterableClass, PsiSubstitutor.EMPTY);
return aSubstitutor.substitute(itClass.getTypeParameters()[0]);
}
@Override
public void visitNewExpression(final PsiNewExpression expression) {
super.visitNewExpression(expression);
final PsiExpression[] dimensions = expression.getArrayDimensions();
for (PsiExpression dimension : dimensions) {
checkIndexExpression(dimension);
}
final PsiArrayInitializerExpression arrayInitializer = expression.getArrayInitializer();
if (arrayInitializer != null) {
processArrayInitializer(arrayInitializer, expression);
}
}
@Override
public void visitArrayInitializerExpression(final PsiArrayInitializerExpression expression) {
super.visitArrayInitializerExpression(expression);
processArrayInitializer(expression, expression);
}
@Override
public void visitPostfixExpression(final PsiPostfixExpression expression) {
super.visitPostfixExpression(expression);
processUnaryExpression(expression, expression.getOperationSign());
}
@Override
public void visitPrefixExpression(final PsiPrefixExpression expression) {
super.visitPrefixExpression(expression);
processUnaryExpression(expression, expression.getOperationSign());
}
private void processUnaryExpression(final PsiExpression expression, PsiJavaToken sign) {
final TypeView typeView = new TypeView(expression);
if (typeView.isChanged()) {
if (!TypeConversionUtil.isUnaryOperatorApplicable(sign, typeView.getType())) {
findConversionOrFail(expression, expression, typeView.getTypePair());
}
}
}
private void findConversionOrFail(PsiExpression expression, PsiExpression toFail, Pair<PsiType, PsiType> typePair) {
final TypeConversionDescriptorBase conversion = myLabeler.getRules().findConversion(typePair.getFirst(), typePair.getSecond(), null, expression, myLabeler);
if (conversion == null) {
myLabeler.markFailedConversion(typePair, toFail);
}
else {
myLabeler.setConversionMapping(expression, conversion);
final PsiType psiType = myTypeEvaluator.evaluateType(expression);
LOG.assertTrue(psiType != null, expression);
myTypeEvaluator.setType(new TypeMigrationUsageInfo(expression), psiType);
}
}
@Override
public void visitPolyadicExpression(PsiPolyadicExpression expression) {
super.visitPolyadicExpression(expression);
final PsiExpression[] operands = expression.getOperands();
if (operands.length == 0) return;
final IElementType operationTokenType = expression.getOperationTokenType();
PsiExpression lOperand = operands[0];
TypeView left = new TypeView(lOperand);
for(int i = 1; i < operands.length; i++) {
final PsiExpression rOperand = operands[i];
if (rOperand == null) return;
final TypeView right = new TypeView(rOperand);
if (tryFindConversionIfOperandIsNull(left, right, rOperand)) continue;
if (tryFindConversionIfOperandIsNull(right, left, lOperand)) continue;
if (!TypeConversionUtil.isBinaryOperatorApplicable(operationTokenType, left.getType(), right.getType(), false)) {
if (left.isChanged()) {
findConversionOrFail(lOperand, lOperand, left.getTypePair());
}
if (right.isChanged()) {
findConversionOrFail(rOperand, rOperand, right.getTypePair());
}
}
lOperand = rOperand;
left = right;
}
}
protected boolean tryFindConversionIfOperandIsNull(TypeView nullCandidate, TypeView comparingType, PsiExpression comparingExpr) {
if (nullCandidate.getType() == PsiType.NULL && comparingType.isChanged()) {
Pair<PsiType, PsiType> typePair = comparingType.getTypePair();
final TypeConversionDescriptorBase
conversion = myLabeler.getRules().findConversion(typePair.getFirst(), typePair.getSecond(), null, comparingExpr, false, myLabeler);
if (conversion != null) {
myLabeler.setConversionMapping(comparingExpr, conversion);
}
return true;
}
return false;
}
private void processArrayInitializer(final PsiArrayInitializerExpression expression, final PsiExpression parentExpression) {
final PsiExpression[] initializers = expression.getInitializers();
PsiType migrationType = null;
for (PsiExpression initializer : initializers) {
final TypeView typeView = new TypeView(initializer);
if (typeView.isChanged()) {
final PsiType type = typeView.getType();
if (migrationType == null || !TypeConversionUtil.isAssignable(migrationType, type)) {
if (migrationType != null && !TypeConversionUtil.isAssignable(type, migrationType)) {
myLabeler.markFailedConversion(Pair.create(parentExpression.getType(), type), parentExpression);
return;
}
migrationType = type;
}
}
}
final PsiType exprType = expression.getType();
if (migrationType != null && exprType instanceof PsiArrayType) {
final boolean alreadyProcessed = TypeConversionUtil.isAssignable(((PsiArrayType)exprType).getComponentType(), migrationType);
myLabeler.migrateExpressionType(parentExpression, alreadyProcessed ? exprType : migrationType.createArrayType(), expression, alreadyProcessed, true);
}
}
private void checkIndexExpression(final PsiExpression indexExpression) {
final PsiType indexType = myTypeEvaluator.evaluateType(indexExpression);
if (indexType != null && !TypeConversionUtil.isAssignable(PsiType.INT, indexType)) {
myLabeler.markFailedConversion(Pair.create(indexExpression.getType(), indexType), indexExpression);
}
}
@Override
public void visitMethodCallExpression(final PsiMethodCallExpression methodCallExpression) {
super.visitMethodCallExpression(methodCallExpression);
final JavaResolveResult resolveResult = methodCallExpression.resolveMethodGenerics();
final PsiElement method = resolveResult.getElement();
if (method instanceof PsiMethod) {
if (migrateEqualsMethod(methodCallExpression, (PsiMethod)method)) {
return;
}
final PsiExpression[] psiExpressions = methodCallExpression.getArgumentList().getExpressions();
final PsiParameter[] originalParams = ((PsiMethod)method).getParameterList().getParameters();
final PsiSubstitutor evalSubstitutor = myTypeEvaluator.createMethodSubstitution(originalParams, psiExpressions, (PsiMethod)method, methodCallExpression);
for (int i = 0; i < psiExpressions.length; i++) {
PsiParameter originalParameter;
if (originalParams.length <= i) {
if (originalParams.length > 0 && originalParams[originalParams.length - 1].isVarArgs()) {
originalParameter = originalParams[originalParams.length - 1];
} else {
continue;
}
}
else {
originalParameter = originalParams[i];
}
processVariable(originalParameter, psiExpressions[i], null, resolveResult.getSubstitutor(), evalSubstitutor, true);
}
final PsiExpression qualifier = methodCallExpression.getMethodExpression().getQualifierExpression();
if (qualifier != null && qualifier.isPhysical() && !new TypeView(qualifier).isChanged()) { //substitute property otherwise
final PsiType qualifierType = qualifier.getType();
if (qualifierType instanceof PsiClassType) {
final PsiClassType.ClassResolveResult classResolveResult = ((PsiClassType)qualifierType).resolveGenerics();
final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(myStatement.getProject());
final PsiType migrationType = elementFactory.createType(classResolveResult.getElement(), composeIfNotAssignable(classResolveResult.getSubstitutor(), evalSubstitutor));
myLabeler.migrateExpressionType(qualifier, migrationType, myStatement, migrationType.equals(qualifierType), true);
}
}
}
}
private boolean migrateEqualsMethod(PsiMethodCallExpression methodCallExpression, PsiMethod method) {
final PsiExpression qualifier = methodCallExpression.getMethodExpression().getQualifierExpression();
if (qualifier == null) {
return false;
}
final TypeView qualifierTypeView = new TypeView(qualifier);
if (!qualifierTypeView.isChanged()) {
return false;
}
if (method.getName().equals("equals") && method.getParameterList().getParametersCount() == 1) {
final PsiParameter parameter = method.getParameterList().getParameters()[0];
if (parameter.getType().equals(PsiType.getJavaLangObject(methodCallExpression.getManager(), methodCallExpression.getResolveScope()))) {
final PsiExpression[] expressions = methodCallExpression.getArgumentList().getExpressions();
if (expressions.length != 1) {
return false;
}
final TypeView argumentTypeView = new TypeView(expressions[0]);
final PsiType argumentType = argumentTypeView.getType();
if (!argumentTypeView.isChanged() && qualifierTypeView.getTypePair().getFirst().equals(argumentType)) {
final PsiType migrationType = qualifierTypeView.getType();
myLabeler.migrateExpressionType(expressions[0],
migrationType,
methodCallExpression,
TypeConversionUtil.isAssignable(migrationType, argumentType),
true);
return true;
}
}
}
return false;
}
private void processVariable(final PsiVariable variable,
final PsiExpression value,
final PsiType migrationType,
final PsiSubstitutor varSubstitutor,
final PsiSubstitutor evalSubstitutor,
final boolean isCovariantPosition) {
final TypeView right = new TypeView(value);
final TypeView left = new TypeView(variable, varSubstitutor, evalSubstitutor);
final PsiType declarationType = left.getType();
switch (TypeInfection.getInfection(left, right)) {
case TypeInfection.NONE_INFECTED:
break;
case TypeInfection.LEFT_INFECTED:
final PsiType valueType = right.getType();
if (valueType != null && declarationType != null) {
myLabeler.migrateExpressionType(value,
adjustMigrationTypeIfGenericArrayCreation(declarationType, value),
myStatement,
left.isVarArgs() ? isVarargAssignable(left, right) : TypeConversionUtil.isAssignable(declarationType, valueType), true);
}
break;
case TypeInfection.RIGHT_INFECTED:
PsiType psiType = migrationType != null ? migrationType : right.getType();
if (psiType != null) {
if (canBeVariableType(psiType)) {
if (declarationType != null &&
!myLabeler.addMigrationRoot(variable, psiType, myStatement, TypeConversionUtil.isAssignable(declarationType, psiType), true) &&
!TypeConversionUtil.isAssignable(left.getType(), psiType)) {
PsiType initialType = left.getType();
if (initialType instanceof PsiEllipsisType) {
initialType = ((PsiEllipsisType)initialType).getComponentType();
}
myLabeler.convertExpression(value, psiType, initialType, isCovariantPosition);
}
}
else {
if (variable instanceof PsiLocalVariable) {
final PsiDeclarationStatement decl = PsiTreeUtil.getParentOfType(variable, PsiDeclarationStatement.class);
if (decl != null && decl.getDeclaredElements().length == 1) {
tryToRemoveLocalVariableAssignment((PsiLocalVariable)variable, value, psiType);
}
break;
}
}
}
break;
case TypeInfection.BOTH_INFECTED:
addTypeUsage(variable);
break;
default:
LOG.error("Must not happen.");
}
}
private void tryToRemoveLocalVariableAssignment(@NotNull PsiLocalVariable variable, @NotNull PsiExpression valueExpression, @NotNull PsiType migrationType) {
final PsiCodeBlock codeBlock = PsiTreeUtil.getParentOfType(variable, PsiCodeBlock.class);
final PsiElement[] refs = DefUseUtil.getRefs(codeBlock, variable, valueExpression);
if (refs.length == 0) {
myLabeler.setConversionMapping(valueExpression, new TypeConversionDescriptorBase() {
@Override
public PsiExpression replace(PsiExpression expression, @NotNull TypeEvaluator evaluator) throws IncorrectOperationException {
final PsiElement parent = expression.getParent();
if (parent instanceof PsiLocalVariable) {
final PsiLocalVariable var = (PsiLocalVariable)parent;
final PsiDeclarationStatement decl = PsiTreeUtil.getParentOfType(var, PsiDeclarationStatement.class);
if (decl == null) return null;
final Project project = var.getProject();
final PsiAssignmentExpression assignment =
SplitDeclarationAction.invokeOnDeclarationStatement(decl, PsiManager.getInstance(project), project);
final PsiExpression rExpression = assignment.getRExpression();
if (rExpression == null) return null;
assignment.replace(rExpression);
if (ReferencesSearch.search(var).forEach(new CommonProcessors.FindFirstProcessor<>())) {
var.delete();
}
}
else if (parent instanceof PsiAssignmentExpression) {
final PsiExpression rExpression = ((PsiAssignmentExpression)parent).getRExpression();
return rExpression == null ? null : (PsiExpression)parent.replace(rExpression);
}
return null;
}
});
} else {
myLabeler.markFailedConversion(Pair.pair(null, migrationType), valueExpression);
}
}
private static boolean canBeVariableType(@NotNull PsiType type) {
return !type.getDeepComponentType().equals(PsiType.VOID);
}
private static PsiType adjustMigrationTypeIfGenericArrayCreation(PsiType migrationType, PsiExpression expression) {
if (expression instanceof PsiNewExpression) {
if (migrationType instanceof PsiArrayType) {
final PsiType componentType = migrationType.getDeepComponentType();
if (componentType instanceof PsiClassType) {
final PsiClassType rawType = ((PsiClassType)componentType).rawType();
if (!rawType.equals(componentType)) {
return com.intellij.refactoring.typeCook.Util.createArrayType(rawType, migrationType.getArrayDimensions());
}
}
}
}
return migrationType;
}
private void addTypeUsage(final PsiElement typedElement) {
if (typedElement instanceof PsiReferenceExpression) {
myLabeler.setTypeUsage(((PsiReferenceExpression)typedElement).resolve(), myStatement);
}
else if (typedElement instanceof PsiMethodCallExpression) {
myLabeler.setTypeUsage(((PsiMethodCallExpression)typedElement).resolveMethod(), myStatement);
}
else {
myLabeler.setTypeUsage(typedElement, myStatement);
}
}
private class TypeView {
final PsiType myOriginType;
final PsiType myType;
final boolean myChanged;
public TypeView(@NotNull PsiExpression expr) {
PsiType exprType = expr.getType();
exprType = exprType instanceof PsiEllipsisType ? ((PsiEllipsisType)exprType).toArrayType() : exprType;
myOriginType = GenericsUtil.getVariableTypeByExpressionType(exprType);
PsiType type = myTypeEvaluator.evaluateType(expr);
type = type instanceof PsiEllipsisType ? ((PsiEllipsisType)type).toArrayType() : type;
myType = GenericsUtil.getVariableTypeByExpressionType(type);
myChanged = !(myOriginType == null || myType == null) && !myType.equals(myOriginType);
}
public TypeView(PsiVariable var, PsiSubstitutor varSubstitutor, PsiSubstitutor evalSubstitutor) {
myOriginType = varSubstitutor != null ? varSubstitutor.substitute(var.getType()) : var.getType();
Map<PsiTypeParameter, PsiType> realMap = new HashMap<>();
if (varSubstitutor != null) realMap.putAll(varSubstitutor.getSubstitutionMap());
if (evalSubstitutor != null) realMap.putAll(evalSubstitutor.getSubstitutionMap());
myType = PsiSubstitutorImpl.createSubstitutor(realMap).substitute(myTypeEvaluator.getType(var));
myChanged = !(myOriginType == null || myType == null) && !myType.equals(myOriginType);
}
public PsiType getType() {
return myType;
}
public boolean isChanged() {
return myChanged;
}
public Pair<PsiType, PsiType> getTypePair() {
return Pair.create(myOriginType, myType);
}
public boolean isVarArgs() {
return myType instanceof PsiEllipsisType && myOriginType instanceof PsiEllipsisType;
}
}
private static class TypeInfection {
static final int NONE_INFECTED = 0;
static final int LEFT_INFECTED = 1;
static final int RIGHT_INFECTED = 2;
static final int BOTH_INFECTED = 3;
static int getInfection(final TypeView left, final TypeView right) {
return (left.isChanged() ? 1 : 0) + (right.isChanged() ? 2 : 0);
}
}
private static boolean isSetter(PsiAssignmentExpression expression) {
final PsiExpression lExpression = expression.getLExpression();
if (lExpression instanceof PsiReferenceExpression) {
final PsiElement resolved = ((PsiReferenceExpression)lExpression).resolve();
if (resolved instanceof PsiField) {
PsiField field = (PsiField) resolved;
final NavigatablePsiElement containingMethod = PsiTreeUtil.getParentOfType(expression, PsiMethod.class, PsiLambdaExpression.class);
if (containingMethod instanceof PsiMethod) {
final PsiMethod setter = PropertyUtil.findPropertySetter(field.getContainingClass(), field.getName(), field.hasModifierProperty(PsiModifier.STATIC), false);
if (containingMethod.isEquivalentTo(setter)) {
return true;
}
}
}
}
return false;
}
private static boolean isGetter(PsiExpression returnValue, PsiElement containingMethod) {
if (returnValue instanceof PsiReferenceExpression) {
final PsiElement resolved = ((PsiReferenceExpression)returnValue).resolve();
if (resolved instanceof PsiField) {
PsiField field = (PsiField)resolved;
final boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC);
final PsiMethod[] getters = GetterSetterPrototypeProvider.findGetters(field.getContainingClass(), field.getName(), isStatic);
if (getters != null) {
for (PsiMethod getter : getters) {
if (containingMethod.isEquivalentTo(getter)) {
return true;
}
}
}
}
}
return false;
}
private static PsiSubstitutor composeIfNotAssignable(PsiSubstitutor actual, PsiSubstitutor required) {
if (actual == PsiSubstitutor.EMPTY) {
return required;
}
if (required == PsiSubstitutor.EMPTY) {
return actual;
}
PsiSubstitutor result = PsiSubstitutorImpl.createSubstitutor(actual.getSubstitutionMap());
for (Map.Entry<PsiTypeParameter, PsiType> e : required.getSubstitutionMap().entrySet()) {
final PsiTypeParameter typeParameter = e.getKey();
final PsiType requiredType = e.getValue();
final PsiType actualType = result.getSubstitutionMap().get(typeParameter);
if (requiredType != null && (actualType == null || !TypeConversionUtil.isAssignable(actualType, requiredType))) {
result = result.put(typeParameter, requiredType);
}
}
return result;
}
private static boolean isVarargAssignable(TypeView left, TypeView right) {
Pair<PsiType, PsiType> leftPair = left.getTypePair();
Pair<PsiType, PsiType> rightPair = right.getTypePair();
PsiType leftOrigin = leftPair.getFirst();
PsiType rightOrigin = rightPair.getFirst();
boolean isDirectlyAssignable = TypeConversionUtil.isAssignable(leftOrigin, rightOrigin);
return TypeConversionUtil.isAssignable(isDirectlyAssignable ?
leftPair.getSecond() :
((PsiEllipsisType)leftPair.getSecond()).getComponentType(), rightPair.getSecond());
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.