code
stringlengths 3
1.04M
| repo_name
stringlengths 5
109
| path
stringlengths 6
306
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 3
1.04M
|
---|---|---|---|---|---|
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.module.impl.scopes;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import java.util.*;
/**
* @author max
*/
public class LibraryRuntimeClasspathScope extends GlobalSearchScope {
private final ProjectFileIndex myIndex;
private final LinkedHashSet<VirtualFile> myEntries = new LinkedHashSet<VirtualFile>();
private int myCachedHashCode = 0;
public LibraryRuntimeClasspathScope(final Project project, final List<Module> modules) {
super(project);
myIndex = ProjectRootManager.getInstance(project).getFileIndex();
final Set<Sdk> processedSdk = new THashSet<Sdk>();
final Set<Library> processedLibraries = new THashSet<Library>();
final Set<Module> processedModules = new THashSet<Module>();
final Condition<OrderEntry> condition = new Condition<OrderEntry>() {
@Override
public boolean value(OrderEntry orderEntry) {
if (orderEntry instanceof ModuleOrderEntry) {
final Module module = ((ModuleOrderEntry)orderEntry).getModule();
return module != null && !processedModules.contains(module);
}
return true;
}
};
for (Module module : modules) {
buildEntries(module, processedModules, processedLibraries, processedSdk, condition);
}
}
public LibraryRuntimeClasspathScope(Project project, LibraryOrderEntry entry) {
super(project);
myIndex = ProjectRootManager.getInstance(project).getFileIndex();
Collections.addAll(myEntries, entry.getRootFiles(OrderRootType.CLASSES));
}
public int hashCode() {
if (myCachedHashCode == 0) {
myCachedHashCode = myEntries.hashCode();
}
return myCachedHashCode;
}
public boolean equals(Object object) {
if (object == this) return true;
if (object == null || object.getClass() != LibraryRuntimeClasspathScope.class) return false;
final LibraryRuntimeClasspathScope that = (LibraryRuntimeClasspathScope)object;
return that.myEntries.equals(myEntries);
}
private void buildEntries(@NotNull final Module module,
@NotNull final Set<Module> processedModules,
@NotNull final Set<Library> processedLibraries,
@NotNull final Set<Sdk> processedSdk,
Condition<OrderEntry> condition) {
if (!processedModules.add(module)) return;
ModuleRootManager.getInstance(module).orderEntries().recursively().satisfying(condition).process(new RootPolicy<LinkedHashSet<VirtualFile>>() {
public LinkedHashSet<VirtualFile> visitLibraryOrderEntry(final LibraryOrderEntry libraryOrderEntry,
final LinkedHashSet<VirtualFile> value) {
final Library library = libraryOrderEntry.getLibrary();
if (library != null && processedLibraries.add(library)) {
ContainerUtil.addAll(value, libraryOrderEntry.getRootFiles(OrderRootType.CLASSES));
}
return value;
}
public LinkedHashSet<VirtualFile> visitModuleSourceOrderEntry(final ModuleSourceOrderEntry moduleSourceOrderEntry,
final LinkedHashSet<VirtualFile> value) {
processedModules.add(moduleSourceOrderEntry.getOwnerModule());
ContainerUtil.addAll(value, moduleSourceOrderEntry.getRootModel().getSourceRoots());
return value;
}
@Override
public LinkedHashSet<VirtualFile> visitModuleOrderEntry(ModuleOrderEntry moduleOrderEntry, LinkedHashSet<VirtualFile> value) {
final Module depModule = moduleOrderEntry.getModule();
if (depModule != null) {
ContainerUtil.addAll(value, ModuleRootManager.getInstance(depModule).getSourceRoots());
}
return value;
}
public LinkedHashSet<VirtualFile> visitJdkOrderEntry(final JdkOrderEntry jdkOrderEntry, final LinkedHashSet<VirtualFile> value) {
final Sdk jdk = jdkOrderEntry.getJdk();
if (jdk != null && processedSdk.add(jdk)) {
ContainerUtil.addAll(value, jdkOrderEntry.getRootFiles(OrderRootType.CLASSES));
}
return value;
}
}, myEntries);
}
public boolean contains(VirtualFile file) {
return myEntries.contains(getFileRoot(file));
}
@Nullable
private VirtualFile getFileRoot(VirtualFile file) {
if (myIndex.isLibraryClassFile(file)) {
return myIndex.getClassRootForFile(file);
}
if (myIndex.isInContent(file)) {
return myIndex.getSourceRootForFile(file);
}
if (myIndex.isInLibraryClasses(file)) {
return myIndex.getClassRootForFile(file);
}
return null;
}
public int compare(VirtualFile file1, VirtualFile file2) {
final VirtualFile r1 = getFileRoot(file1);
final VirtualFile r2 = getFileRoot(file2);
for (VirtualFile root : myEntries) {
if (Comparing.equal(r1, root)) return 1;
if (Comparing.equal(r2, root)) return -1;
}
return 0;
}
@TestOnly
public List<VirtualFile> getRoots() {
return new ArrayList<VirtualFile>(myEntries);
}
public boolean isSearchInModuleContent(@NotNull Module aModule) {
return false;
}
public boolean isSearchInLibraries() {
return true;
}
}
| liveqmock/platform-tools-idea | platform/indexing-impl/src/com/intellij/openapi/module/impl/scopes/LibraryRuntimeClasspathScope.java | Java | apache-2.0 | 6,421 |
/**
* Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*******************************************************************************
* 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.easemob.chatuidemo.widget.photoview;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.widget.OverScroller;
import android.widget.Scroller;
public abstract class ScrollerProxy {
public static ScrollerProxy getScroller(Context context) {
if (VERSION.SDK_INT < VERSION_CODES.GINGERBREAD) {
return new PreGingerScroller(context);
} else {
return new GingerScroller(context);
}
}
public abstract boolean computeScrollOffset();
public abstract void fling(int startX, int startY, int velocityX, int velocityY, int minX, int maxX, int minY,
int maxY, int overX, int overY);
public abstract void forceFinished(boolean finished);
public abstract int getCurrX();
public abstract int getCurrY();
@TargetApi(9)
private static class GingerScroller extends ScrollerProxy {
private OverScroller mScroller;
public GingerScroller(Context context) {
mScroller = new OverScroller(context);
}
@Override
public boolean computeScrollOffset() {
return mScroller.computeScrollOffset();
}
@Override
public void fling(int startX, int startY, int velocityX, int velocityY, int minX, int maxX, int minY, int maxY,
int overX, int overY) {
mScroller.fling(startX, startY, velocityX, velocityY, minX, maxX, minY, maxY, overX, overY);
}
@Override
public void forceFinished(boolean finished) {
mScroller.forceFinished(finished);
}
@Override
public int getCurrX() {
return mScroller.getCurrX();
}
@Override
public int getCurrY() {
return mScroller.getCurrY();
}
}
private static class PreGingerScroller extends ScrollerProxy {
private Scroller mScroller;
public PreGingerScroller(Context context) {
mScroller = new Scroller(context);
}
@Override
public boolean computeScrollOffset() {
return mScroller.computeScrollOffset();
}
@Override
public void fling(int startX, int startY, int velocityX, int velocityY, int minX, int maxX, int minY, int maxY,
int overX, int overY) {
mScroller.fling(startX, startY, velocityX, velocityY, minX, maxX, minY, maxY);
}
@Override
public void forceFinished(boolean finished) {
mScroller.forceFinished(finished);
}
@Override
public int getCurrX() {
return mScroller.getCurrX();
}
@Override
public int getCurrY() {
return mScroller.getCurrY();
}
}
}
| cf0566/CarMarket | src/com/easemob/chatuidemo/widget/photoview/ScrollerProxy.java | Java | apache-2.0 | 3,945 |
/*
* 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.sql.calcite.expression.builtin;
import org.apache.calcite.rex.RexCall;
import org.apache.calcite.rex.RexLiteral;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.sql.SqlOperator;
import org.apache.calcite.sql.fun.SqlStdOperatorTable;
import org.apache.druid.query.filter.DimFilter;
import org.apache.druid.query.filter.LikeDimFilter;
import org.apache.druid.segment.VirtualColumn;
import org.apache.druid.segment.column.RowSignature;
import org.apache.druid.sql.calcite.expression.DirectOperatorConversion;
import org.apache.druid.sql.calcite.expression.DruidExpression;
import org.apache.druid.sql.calcite.expression.Expressions;
import org.apache.druid.sql.calcite.planner.PlannerContext;
import org.apache.druid.sql.calcite.rel.VirtualColumnRegistry;
import javax.annotation.Nullable;
import java.util.List;
public class LikeOperatorConversion extends DirectOperatorConversion
{
private static final SqlOperator SQL_FUNCTION = SqlStdOperatorTable.LIKE;
public LikeOperatorConversion()
{
super(SQL_FUNCTION, "like");
}
@Override
public SqlOperator calciteOperator()
{
return SQL_FUNCTION;
}
@Nullable
@Override
public DimFilter toDruidFilter(
PlannerContext plannerContext,
RowSignature rowSignature,
@Nullable VirtualColumnRegistry virtualColumnRegistry,
RexNode rexNode
)
{
final List<RexNode> operands = ((RexCall) rexNode).getOperands();
final DruidExpression druidExpression = Expressions.toDruidExpression(
plannerContext,
rowSignature,
operands.get(0)
);
if (druidExpression == null) {
return null;
}
if (druidExpression.isSimpleExtraction()) {
return new LikeDimFilter(
druidExpression.getSimpleExtraction().getColumn(),
RexLiteral.stringValue(operands.get(1)),
operands.size() > 2 ? RexLiteral.stringValue(operands.get(2)) : null,
druidExpression.getSimpleExtraction().getExtractionFn()
);
} else if (virtualColumnRegistry != null) {
VirtualColumn v = virtualColumnRegistry.getOrCreateVirtualColumnForExpression(
plannerContext,
druidExpression,
operands.get(0).getType().getSqlTypeName()
);
return new LikeDimFilter(
v.getOutputName(),
RexLiteral.stringValue(operands.get(1)),
operands.size() > 2 ? RexLiteral.stringValue(operands.get(2)) : null,
null
);
} else {
return null;
}
}
}
| implydata/druid | sql/src/main/java/org/apache/druid/sql/calcite/expression/builtin/LikeOperatorConversion.java | Java | apache-2.0 | 3,331 |
/*
* Copyright (C) 2015 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;
import com.google.common.annotations.GwtIncompatible;
import java.util.List;
/**
* Creates, based on your criteria, a JUnit test suite that exhaustively tests
* a ConcurrentNavigableMap implementation.
*
* @author Louis Wasserman
*/
@GwtIncompatible
public class ConcurrentNavigableMapTestSuiteBuilder<K, V>
extends NavigableMapTestSuiteBuilder<K, V> {
public static <K, V> ConcurrentNavigableMapTestSuiteBuilder<K, V> using(
TestSortedMapGenerator<K, V> generator) {
ConcurrentNavigableMapTestSuiteBuilder<K, V> result =
new ConcurrentNavigableMapTestSuiteBuilder<K, V>();
result.usingGenerator(generator);
return result;
}
@Override
protected List<Class<? extends AbstractTester>> getTesters() {
List<Class<? extends AbstractTester>> testers = Helpers.copyToList(super.getTesters());
testers.addAll(ConcurrentMapTestSuiteBuilder.TESTERS);
return testers;
}
@Override
NavigableMapTestSuiteBuilder<K, V> subSuiteUsing(TestSortedMapGenerator<K, V> generator) {
return using(generator);
}
}
| DavesMan/guava | guava-testlib/src/com/google/common/collect/testing/ConcurrentNavigableMapTestSuiteBuilder.java | Java | apache-2.0 | 1,706 |
/*
* 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.pherf.rules;
import org.apache.phoenix.thirdparty.com.google.common.base.Preconditions;
import org.apache.phoenix.pherf.configuration.Column;
import org.apache.phoenix.pherf.configuration.DataSequence;
import org.apache.phoenix.pherf.configuration.DataTypeMapping;
import java.util.concurrent.atomic.AtomicLong;
public class SequentialIntegerDataGenerator implements RuleBasedDataGenerator {
private final Column columnRule;
private final AtomicLong counter;
private final long minValue;
private final long maxValue;
public SequentialIntegerDataGenerator(Column columnRule) {
Preconditions.checkArgument(columnRule.getDataSequence() == DataSequence.SEQUENTIAL);
Preconditions.checkArgument(isIntegerType(columnRule.getType()));
this.columnRule = columnRule;
minValue = columnRule.getMinValue();
maxValue = columnRule.getMaxValue();
counter = new AtomicLong(0);
}
/**
* Note that this method rolls over for attempts to get larger than maxValue
* @return new DataValue
*/
@Override
public DataValue getDataValue() {
return new DataValue(columnRule.getType(), String.valueOf((counter.getAndIncrement() % (maxValue - minValue + 1)) + minValue));
}
// Probably could go into a util class in the future
boolean isIntegerType(DataTypeMapping mapping) {
switch (mapping) {
case BIGINT:
case INTEGER:
case TINYINT:
case UNSIGNED_LONG:
return true;
default:
return false;
}
}
}
| ankitsinghal/phoenix | phoenix-pherf/src/main/java/org/apache/phoenix/pherf/rules/SequentialIntegerDataGenerator.java | Java | apache-2.0 | 2,431 |
package org.ovirt.engine.core.bll;
import org.ovirt.engine.core.common.action.VdcActionParametersBase;
public abstract class ConfigCommandBase<T extends VdcActionParametersBase> extends CommandBase<T> {
protected ConfigCommandBase(T parameters) {
super(parameters);
}
}
| Dhandapani/gluster-ovirt | backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/ConfigCommandBase.java | Java | apache-2.0 | 288 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.infinispan.remote;
import org.apache.camel.test.infra.infinispan.services.InfinispanService;
import org.apache.camel.test.infra.infinispan.services.InfinispanServiceFactory;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.commons.api.BasicCache;
import org.infinispan.configuration.cache.CacheMode;
import org.jgroups.util.UUID;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.testcontainers.shaded.org.apache.commons.lang.SystemUtils;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class InfinispanRemoteConfigurationIT {
@RegisterExtension
static InfinispanService service = InfinispanServiceFactory.createService();
@Test
public void remoteCacheWithoutProperties() throws Exception {
InfinispanRemoteConfiguration configuration = new InfinispanRemoteConfiguration();
configuration.setHosts(service.host() + ":" + service.port());
configuration.setSecure(true);
configuration.setUsername(service.username());
configuration.setPassword(service.password());
configuration.setSecurityServerName("infinispan");
configuration.setSaslMechanism("DIGEST-MD5");
configuration.setSecurityRealm("default");
if (SystemUtils.IS_OS_MAC) {
configuration.addConfigurationProperty(
"infinispan.client.hotrod.client_intelligence", "BASIC");
}
try (InfinispanRemoteManager manager = new InfinispanRemoteManager(configuration)) {
manager.start();
manager.getCacheContainer().administration()
.getOrCreateCache(
"misc_cache",
new org.infinispan.configuration.cache.ConfigurationBuilder()
.clustering()
.cacheMode(CacheMode.DIST_SYNC).build());
BasicCache<Object, Object> cache = manager.getCache("misc_cache");
assertNotNull(cache);
assertTrue(cache instanceof RemoteCache);
String key = UUID.randomUUID().toString();
assertNull(cache.put(key, "val1"));
assertNull(cache.put(key, "val2"));
}
}
@Test
public void remoteCacheWithProperties() throws Exception {
InfinispanRemoteConfiguration configuration = new InfinispanRemoteConfiguration();
configuration.setHosts(service.host() + ":" + service.port());
configuration.setSecure(true);
configuration.setUsername(service.username());
configuration.setPassword(service.password());
configuration.setSecurityServerName("infinispan");
configuration.setSaslMechanism("DIGEST-MD5");
configuration.setSecurityRealm("default");
if (SystemUtils.IS_OS_MAC) {
configuration.setConfigurationUri("infinispan/client-mac.properties");
} else {
configuration.setConfigurationUri("infinispan/client.properties");
}
try (InfinispanRemoteManager manager = new InfinispanRemoteManager(configuration)) {
manager.start();
manager.getCacheContainer().administration()
.getOrCreateCache(
"misc_cache",
new org.infinispan.configuration.cache.ConfigurationBuilder()
.clustering()
.cacheMode(CacheMode.DIST_SYNC).build());
BasicCache<Object, Object> cache = manager.getCache("misc_cache");
assertNotNull(cache);
assertTrue(cache instanceof RemoteCache);
String key = UUID.randomUUID().toString();
assertNull(cache.put(key, "val1"));
assertNotNull(cache.put(key, "val2"));
}
}
}
| christophd/camel | components/camel-infinispan/camel-infinispan/src/test/java/org/apache/camel/component/infinispan/remote/InfinispanRemoteConfigurationIT.java | Java | apache-2.0 | 4,826 |
// Copyright 2015 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.profiler;
import static com.google.common.truth.Truth.assertThat;
import static java.nio.charset.StandardCharsets.ISO_8859_1;
import static org.junit.Assert.fail;
import com.google.devtools.build.lib.clock.BlazeClock;
import com.google.devtools.build.lib.clock.Clock;
import com.google.devtools.build.lib.profiler.Profiler.ProfiledTaskKinds;
import com.google.devtools.build.lib.profiler.analysis.ProfileInfo;
import com.google.devtools.build.lib.testutil.FoundationTestCase;
import com.google.devtools.build.lib.testutil.ManualClock;
import com.google.devtools.build.lib.testutil.Suite;
import com.google.devtools.build.lib.testutil.TestSpec;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
import com.google.devtools.build.lib.vfs.Path;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Unit tests for the profiler.
*/
@TestSpec(size = Suite.MEDIUM_TESTS) // testConcurrentProfiling takes ~700ms, testProfiler 100ms.
@RunWith(JUnit4.class)
public class ProfilerTest extends FoundationTestCase {
private Path cacheDir;
private Profiler profiler = Profiler.instance();
private ManualClock clock;
@Before
public final void createCacheDirectory() throws Exception {
cacheDir = scratch.dir("/tmp");
}
@Before
public final void setManualClock() {
clock = new ManualClock();
BlazeClock.setClock(clock);
}
@Test
public void testProfilerActivation() throws Exception {
Path cacheFile = cacheDir.getRelative("profile1.dat");
assertThat(profiler.isActive()).isFalse();
profiler.start(ProfiledTaskKinds.ALL, cacheFile.getOutputStream(), "basic test", false,
BlazeClock.instance(), BlazeClock.instance().nanoTime());
assertThat(profiler.isActive()).isTrue();
profiler.stop();
assertThat(profiler.isActive()).isFalse();
}
@Test
public void testTaskDetails() throws Exception {
Path cacheFile = cacheDir.getRelative("profile1.dat");
profiler.start(ProfiledTaskKinds.ALL, cacheFile.getOutputStream(), "basic test", false,
BlazeClock.instance(), BlazeClock.instance().nanoTime());
profiler.startTask(ProfilerTask.ACTION, "action task");
profiler.logEvent(ProfilerTask.TEST, "event");
profiler.completeTask(ProfilerTask.ACTION);
profiler.stop();
ProfileInfo info = ProfileInfo.loadProfile(cacheFile);
info.calculateStats();
ProfileInfo.Task task = info.allTasksById.get(0);
assertThat(task.id).isEqualTo(1);
assertThat(task.type).isEqualTo(ProfilerTask.ACTION);
assertThat(task.getDescription()).isEqualTo("action task");
task = info.allTasksById.get(1);
assertThat(task.id).isEqualTo(2);
assertThat(task.type).isEqualTo(ProfilerTask.TEST);
assertThat(task.getDescription()).isEqualTo("event");
}
@Test
public void testProfiler() throws Exception {
Path cacheFile = cacheDir.getRelative("profile1.dat");
profiler.start(ProfiledTaskKinds.ALL, cacheFile.getOutputStream(), "basic test", false,
BlazeClock.instance(), BlazeClock.instance().nanoTime());
profiler.logSimpleTask(BlazeClock.instance().nanoTime(),
ProfilerTask.PHASE, "profiler start");
profiler.startTask(ProfilerTask.ACTION, "complex task");
profiler.logEvent(ProfilerTask.PHASE, "event1");
profiler.startTask(ProfilerTask.ACTION_CHECK, "complex subtask");
// next task takes less than 10 ms and should be only aggregated
profiler.logSimpleTask(BlazeClock.instance().nanoTime(),
ProfilerTask.VFS_STAT, "stat1");
long startTime = BlazeClock.instance().nanoTime();
clock.advanceMillis(20);
// this one will take at least 20 ms and should be present
profiler.logSimpleTask(startTime, ProfilerTask.VFS_STAT, "stat2");
profiler.completeTask(ProfilerTask.ACTION_CHECK);
profiler.completeTask(ProfilerTask.ACTION);
profiler.stop();
// all other calls to profiler should be ignored
profiler.logEvent(ProfilerTask.PHASE, "should be ignored");
// normally this would cause an exception but it is ignored since profiler
// is disabled
profiler.completeTask(ProfilerTask.ACTION_EXECUTE);
ProfileInfo info = ProfileInfo.loadProfile(cacheFile);
info.calculateStats();
assertThat(info.allTasksById).hasSize(6); // only 5 tasks + finalization should be recorded
ProfileInfo.Task task = info.allTasksById.get(0);
assertThat(task.stats.isEmpty()).isTrue();
task = info.allTasksById.get(1);
int count = 0;
for (ProfileInfo.AggregateAttr attr : task.getStatAttrArray()) {
if (attr != null) {
count++;
}
}
assertThat(count).isEqualTo(2); // only children are GENERIC and ACTION_CHECK
assertThat(ProfilerTask.TASK_COUNT).isEqualTo(task.aggregatedStats.toArray().length);
assertThat(task.aggregatedStats.getAttr(ProfilerTask.VFS_STAT).count).isEqualTo(2);
task = info.allTasksById.get(2);
assertThat(task.durationNanos).isEqualTo(0);
task = info.allTasksById.get(3);
assertThat(task.stats.getAttr(ProfilerTask.VFS_STAT).count).isEqualTo(2);
assertThat(task.subtasks).hasLength(1);
assertThat(task.subtasks[0].getDescription()).isEqualTo("stat2");
// assert that startTime grows with id
long time = -1;
for (ProfileInfo.Task t : info.allTasksById) {
assertThat(t.startTime).isAtLeast(time);
time = t.startTime;
}
}
@Test
public void testProfilerRecordingAllEvents() throws Exception {
Path cacheFile = cacheDir.getRelative("profile1.dat");
profiler.start(ProfiledTaskKinds.ALL, cacheFile.getOutputStream(), "basic test", true,
BlazeClock.instance(), BlazeClock.instance().nanoTime());
profiler.startTask(ProfilerTask.ACTION, "action task");
// Next task takes less than 10 ms but should be recorded anyway.
clock.advanceMillis(1);
profiler.logSimpleTask(BlazeClock.instance().nanoTime(), ProfilerTask.VFS_STAT, "stat1");
profiler.completeTask(ProfilerTask.ACTION);
profiler.stop();
ProfileInfo info = ProfileInfo.loadProfile(cacheFile);
info.calculateStats();
assertThat(info.allTasksById).hasSize(3); // 2 tasks + finalization should be recorded
ProfileInfo.Task task = info.allTasksById.get(1);
assertThat(task.type).isEqualTo(ProfilerTask.VFS_STAT);
// Check that task would have been dropped if profiler was not configured to record everything.
assertThat(task.durationNanos).isLessThan(ProfilerTask.VFS_STAT.minDuration);
}
@Test
public void testProfilerRecordingOnlySlowestEvents() throws Exception {
Path profileData = cacheDir.getRelative("foo");
profiler.start(ProfiledTaskKinds.SLOWEST, profileData.getOutputStream(), "test", true,
BlazeClock.instance(), BlazeClock.instance().nanoTime());
profiler.logSimpleTask(10000, 20000, ProfilerTask.VFS_STAT, "stat");
profiler.logSimpleTask(20000, 30000, ProfilerTask.REMOTE_EXECUTION, "remote execution");
assertThat(profiler.isProfiling(ProfilerTask.VFS_STAT)).isTrue();
assertThat(profiler.isProfiling(ProfilerTask.REMOTE_EXECUTION)).isFalse();
profiler.stop();
ProfileInfo info = ProfileInfo.loadProfile(profileData);
info.calculateStats();
assertThat(info.allTasksById).hasSize(1); // only VFS_STAT task should be recorded
ProfileInfo.Task task = info.allTasksById.get(0);
assertThat(task.type).isEqualTo(ProfilerTask.VFS_STAT);
}
@Test
public void testProfilerRecordsNothing() throws Exception {
Path profileData = cacheDir.getRelative("foo");
profiler.start(ProfiledTaskKinds.NONE, profileData.getOutputStream(), "test", true,
BlazeClock.instance(), BlazeClock.instance().nanoTime());
profiler.logSimpleTask(10000, 20000, ProfilerTask.VFS_STAT, "stat");
assertThat(ProfilerTask.VFS_STAT.collectsSlowestInstances()).isTrue();
assertThat(profiler.isProfiling(ProfilerTask.VFS_STAT)).isFalse();
profiler.stop();
ProfileInfo info = ProfileInfo.loadProfile(profileData);
info.calculateStats();
assertThat(info.allTasksById).isEmpty();
}
@Test
public void testInconsistentCompleteTask() throws Exception {
Path cacheFile = cacheDir.getRelative("profile2.dat");
profiler.start(ProfiledTaskKinds.ALL, cacheFile.getOutputStream(),
"task stack inconsistency test", false,
BlazeClock.instance(), BlazeClock.instance().nanoTime());
profiler.startTask(ProfilerTask.PHASE, "some task");
try {
profiler.completeTask(ProfilerTask.ACTION);
fail();
} catch (IllegalStateException e) {
// this is expected
}
profiler.stop();
}
@Test
public void testConcurrentProfiling() throws Exception {
Path cacheFile = cacheDir.getRelative("profile3.dat");
profiler.start(ProfiledTaskKinds.ALL, cacheFile.getOutputStream(), "concurrent test", false,
BlazeClock.instance(), BlazeClock.instance().nanoTime());
long id = Thread.currentThread().getId();
Thread thread1 = new Thread() {
@Override public void run() {
for (int i = 0; i < 10000; i++) {
Profiler.instance().logEvent(ProfilerTask.TEST, "thread1");
}
}
};
long id1 = thread1.getId();
Thread thread2 = new Thread() {
@Override public void run() {
for (int i = 0; i < 10000; i++) {
Profiler.instance().logEvent(ProfilerTask.TEST, "thread2");
}
}
};
long id2 = thread2.getId();
profiler.startTask(ProfilerTask.PHASE, "main task");
profiler.logEvent(ProfilerTask.TEST, "starting threads");
thread1.start();
thread2.start();
thread2.join();
thread1.join();
profiler.logEvent(ProfilerTask.TEST, "joined");
profiler.completeTask(ProfilerTask.PHASE);
profiler.stop();
ProfileInfo info = ProfileInfo.loadProfile(cacheFile);
info.calculateStats();
info.analyzeRelationships();
assertThat(info.allTasksById).hasSize(4 + 10000 + 10000); // total number of tasks
assertThat(info.tasksByThread).hasSize(3); // total number of threads
// while main thread had 3 tasks, 2 of them were nested, so tasksByThread
// would contain only one "main task" task
assertThat(info.tasksByThread.get(id)).hasLength(2);
ProfileInfo.Task mainTask = info.tasksByThread.get(id)[0];
assertThat(mainTask.getDescription()).isEqualTo("main task");
assertThat(mainTask.subtasks).hasLength(2);
// other threads had 10000 independent recorded tasks each
assertThat(info.tasksByThread.get(id1)).hasLength(10000);
assertThat(info.tasksByThread.get(id2)).hasLength(10000);
int startId = mainTask.subtasks[0].id; // id of "starting threads"
int endId = mainTask.subtasks[1].id; // id of "joining"
assertThat(startId).isLessThan(info.tasksByThread.get(id1)[0].id);
assertThat(startId).isLessThan(info.tasksByThread.get(id2)[0].id);
assertThat(endId).isGreaterThan(info.tasksByThread.get(id1)[9999].id);
assertThat(endId).isGreaterThan(info.tasksByThread.get(id2)[9999].id);
}
@Test
public void testPhaseTasks() throws Exception {
Path cacheFile = cacheDir.getRelative("profile4.dat");
profiler.start(ProfiledTaskKinds.ALL, cacheFile.getOutputStream(), "phase test", false,
BlazeClock.instance(), BlazeClock.instance().nanoTime());
Thread thread1 = new Thread() {
@Override public void run() {
for (int i = 0; i < 100; i++) {
Profiler.instance().logEvent(ProfilerTask.TEST, "thread1");
}
}
};
profiler.markPhase(ProfilePhase.INIT); // Empty phase.
profiler.markPhase(ProfilePhase.LOAD);
thread1.start();
thread1.join();
clock.advanceMillis(1);
profiler.markPhase(ProfilePhase.ANALYZE);
Thread thread2 = new Thread() {
@Override public void run() {
profiler.startTask(ProfilerTask.TEST, "complex task");
for (int i = 0; i < 100; i++) {
Profiler.instance().logEvent(ProfilerTask.TEST, "thread2a");
}
profiler.completeTask(ProfilerTask.TEST);
profiler.markPhase(ProfilePhase.EXECUTE);
for (int i = 0; i < 100; i++) {
Profiler.instance().logEvent(ProfilerTask.TEST, "thread2b");
}
}
};
thread2.start();
thread2.join();
profiler.logEvent(ProfilerTask.TEST, "last task");
clock.advanceMillis(1);
profiler.stop();
ProfileInfo info = ProfileInfo.loadProfile(cacheFile);
info.calculateStats();
info.analyzeRelationships();
// number of tasks: INIT(1) + LOAD(1) + Thread1.TEST(100) + ANALYZE(1)
// + Thread2a.TEST(100) + TEST(1) + EXECUTE(1) + Thread2b.TEST(100) + TEST(1) + INFO(1)
assertThat(info.allTasksById).hasSize(1 + 1 + 100 + 1 + 100 + 1 + 1 + 100 + 1 + 1);
assertThat(info.tasksByThread).hasSize(3); // total number of threads
// Phase0 contains only itself
ProfileInfo.Task p0 = info.getPhaseTask(ProfilePhase.INIT);
assertThat(info.getTasksForPhase(p0)).hasSize(1);
// Phase1 contains itself and 100 TEST "thread1" tasks
ProfileInfo.Task p1 = info.getPhaseTask(ProfilePhase.LOAD);
assertThat(info.getTasksForPhase(p1)).hasSize(101);
// Phase2 contains itself and 1 "complex task"
ProfileInfo.Task p2 = info.getPhaseTask(ProfilePhase.ANALYZE);
assertThat(info.getTasksForPhase(p2)).hasSize(2);
// Phase3 contains itself, 100 TEST "thread2b" tasks and "last task"
ProfileInfo.Task p3 = info.getPhaseTask(ProfilePhase.EXECUTE);
assertThat(info.getTasksForPhase(p3)).hasSize(103);
}
@Test
public void testCorruptedFile() throws Exception {
Path cacheFile = cacheDir.getRelative("profile5.dat");
profiler.start(ProfiledTaskKinds.ALL, cacheFile.getOutputStream(), "phase test", false,
BlazeClock.instance(), BlazeClock.instance().nanoTime());
for (int i = 0; i < 100; i++) {
profiler.startTask(ProfilerTask.TEST, "outer task " + i);
clock.advanceMillis(1);
profiler.logEvent(ProfilerTask.TEST, "inner task " + i);
profiler.completeTask(ProfilerTask.TEST);
}
profiler.stop();
ProfileInfo info = ProfileInfo.loadProfile(cacheFile);
info.calculateStats();
assertThat(info.isCorruptedOrIncomplete()).isFalse();
Path corruptedFile = cacheDir.getRelative("profile5bad.dat");
FileSystemUtils.writeContent(
corruptedFile, Arrays.copyOf(FileSystemUtils.readContent(cacheFile), 2000));
info = ProfileInfo.loadProfile(corruptedFile);
info.calculateStats();
assertThat(info.isCorruptedOrIncomplete()).isTrue();
// Since root tasks will appear after nested tasks in the profile file and
// we have exactly one nested task for each root task, the following will always
// be true for our corrupted file:
// 0 <= number_of_all_tasks - 2*number_of_root_tasks <= 1
assertThat(info.allTasksById.size() / 2).isEqualTo(info.rootTasksById.size());
}
@Test
public void testUnsupportedProfilerRecord() throws Exception {
Path dataFile = cacheDir.getRelative("profile5.dat");
profiler.start(ProfiledTaskKinds.ALL, dataFile.getOutputStream(), "phase test", false,
BlazeClock.instance(), BlazeClock.instance().nanoTime());
profiler.startTask(ProfilerTask.TEST, "outer task");
profiler.logEvent(ProfilerTask.EXCEPTION, "inner task");
profiler.completeTask(ProfilerTask.TEST);
profiler.startTask(ProfilerTask.SCANNER, "outer task 2");
profiler.logSimpleTask(Profiler.nanoTimeMaybe(), ProfilerTask.TEST, "inner task 2");
profiler.completeTask(ProfilerTask.SCANNER);
profiler.stop();
// Validate our test profile.
ProfileInfo info = ProfileInfo.loadProfile(dataFile);
info.calculateStats();
assertThat(info.isCorruptedOrIncomplete()).isFalse();
assertThat(info.getStatsForType(ProfilerTask.TEST, info.rootTasksById).count).isEqualTo(2);
assertThat(info.getStatsForType(ProfilerTask.UNKNOWN, info.rootTasksById).count).isEqualTo(0);
// Now replace "TEST" type with something unsupported - e.g. "XXXX".
InputStream in = new InflaterInputStream(dataFile.getInputStream(), new Inflater(false), 65536);
byte[] buffer = new byte[60000];
int len = in.read(buffer);
in.close();
assertThat(len).isLessThan(buffer.length); // Validate that file was completely decoded.
String content = new String(buffer, ISO_8859_1);
int infoIndex = content.indexOf("TEST");
assertThat(infoIndex).isGreaterThan(0);
content = content.substring(0, infoIndex) + "XXXX" + content.substring(infoIndex + 4);
OutputStream out = new DeflaterOutputStream(dataFile.getOutputStream(),
new Deflater(Deflater.BEST_SPEED, false), 65536);
out.write(content.getBytes(ISO_8859_1));
out.close();
// Validate that XXXX records were classified as UNKNOWN.
info = ProfileInfo.loadProfile(dataFile);
info.calculateStats();
assertThat(info.isCorruptedOrIncomplete()).isFalse();
assertThat(info.getStatsForType(ProfilerTask.TEST, info.rootTasksById).count).isEqualTo(0);
assertThat(info.getStatsForType(ProfilerTask.SCANNER, info.rootTasksById).count).isEqualTo(1);
assertThat(info.getStatsForType(ProfilerTask.EXCEPTION, info.rootTasksById).count).isEqualTo(1);
assertThat(info.getStatsForType(ProfilerTask.UNKNOWN, info.rootTasksById).count).isEqualTo(2);
}
@Test
public void testResilenceToNonDecreasingNanoTimes() throws Exception {
final long initialNanoTime = BlazeClock.instance().nanoTime();
final AtomicInteger numNanoTimeCalls = new AtomicInteger(0);
Clock badClock = new Clock() {
@Override
public long currentTimeMillis() {
return BlazeClock.instance().currentTimeMillis();
}
@Override
public long nanoTime() {
return initialNanoTime - numNanoTimeCalls.addAndGet(1);
}
};
Path cacheFile = cacheDir.getRelative("profile1.dat");
profiler.start(ProfiledTaskKinds.ALL, cacheFile.getOutputStream(),
"testResilenceToNonDecreasingNanoTimes", false, badClock, initialNanoTime);
profiler.logSimpleTask(badClock.nanoTime(), ProfilerTask.TEST, "some task");
profiler.stop();
}
}
| damienmg/bazel | src/test/java/com/google/devtools/build/lib/profiler/ProfilerTest.java | Java | apache-2.0 | 19,092 |
/*
* 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.runtimefields.query;
import org.apache.lucene.search.QueryVisitor;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.automaton.Automata;
import org.apache.lucene.util.automaton.ByteRunAutomaton;
import org.elasticsearch.script.Script;
import org.elasticsearch.xpack.runtimefields.mapper.StringFieldScript;
import java.util.List;
import java.util.Objects;
public class StringScriptFieldRangeQuery extends AbstractStringScriptFieldQuery {
private final String lowerValue;
private final String upperValue;
private final boolean includeLower;
private final boolean includeUpper;
public StringScriptFieldRangeQuery(
Script script,
StringFieldScript.LeafFactory leafFactory,
String fieldName,
String lowerValue,
String upperValue,
boolean includeLower,
boolean includeUpper
) {
super(script, leafFactory, fieldName);
this.lowerValue = Objects.requireNonNull(lowerValue);
this.upperValue = Objects.requireNonNull(upperValue);
this.includeLower = includeLower;
this.includeUpper = includeUpper;
assert lowerValue.compareTo(upperValue) <= 0;
}
@Override
protected boolean matches(List<String> values) {
for (String value : values) {
int lct = lowerValue.compareTo(value);
boolean lowerOk = includeLower ? lct <= 0 : lct < 0;
if (lowerOk) {
int uct = upperValue.compareTo(value);
boolean upperOk = includeUpper ? uct >= 0 : uct > 0;
if (upperOk) {
return true;
}
}
}
return false;
}
@Override
public void visit(QueryVisitor visitor) {
if (visitor.acceptField(fieldName())) {
visitor.consumeTermsMatching(
this,
fieldName(),
() -> new ByteRunAutomaton(
Automata.makeBinaryInterval(new BytesRef(lowerValue), includeLower, new BytesRef(upperValue), includeUpper)
)
);
}
}
@Override
public final String toString(String field) {
StringBuilder b = new StringBuilder();
if (false == fieldName().contentEquals(field)) {
b.append(fieldName()).append(':');
}
b.append(includeLower ? '[' : '{');
b.append(lowerValue).append(" TO ").append(upperValue);
b.append(includeUpper ? ']' : '}');
return b.toString();
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), lowerValue, upperValue, includeLower, includeUpper);
}
@Override
public boolean equals(Object obj) {
if (false == super.equals(obj)) {
return false;
}
StringScriptFieldRangeQuery other = (StringScriptFieldRangeQuery) obj;
return lowerValue.equals(other.lowerValue)
&& upperValue.equals(other.upperValue)
&& includeLower == other.includeLower
&& includeUpper == other.includeUpper;
}
String lowerValue() {
return lowerValue;
}
String upperValue() {
return upperValue;
}
boolean includeLower() {
return includeLower;
}
boolean includeUpper() {
return includeUpper;
}
}
| nknize/elasticsearch | x-pack/plugin/runtime-fields/src/main/java/org/elasticsearch/xpack/runtimefields/query/StringScriptFieldRangeQuery.java | Java | apache-2.0 | 3,629 |
/*
* Copyright © 2013-2018 camunda services GmbH and various authors (info@camunda.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.camunda.bpm.container.impl.jboss.deployment.marker;
import java.util.List;
import org.camunda.bpm.application.AbstractProcessApplication;
import org.camunda.bpm.application.impl.metadata.spi.ProcessesXml;
import org.camunda.bpm.container.impl.jboss.util.ProcessesXmlWrapper;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.server.deployment.AttachmentKey;
import org.jboss.as.server.deployment.AttachmentList;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.jandex.AnnotationInstance;
/**
*
* @author Daniel Meyer
*
*/
public class ProcessApplicationAttachments {
private static final AttachmentKey<Boolean> MARKER = AttachmentKey.create(Boolean.class);
private static final AttachmentKey<Boolean> PART_OF_MARKER = AttachmentKey.create(Boolean.class);
private static final AttachmentKey<AttachmentList<ProcessesXmlWrapper>> PROCESSES_XML_LIST = AttachmentKey.createList(ProcessesXmlWrapper.class);
private static final AttachmentKey<ComponentDescription> PA_COMPONENT = AttachmentKey.create(ComponentDescription.class);
private static final AttachmentKey<AnnotationInstance> POST_DEPLOY_METHOD = AttachmentKey.create(AnnotationInstance.class);
private static final AttachmentKey<AnnotationInstance> PRE_UNDEPLOY_METHOD = AttachmentKey.create(AnnotationInstance.class);
/**
* Attach the parsed ProcessesXml file to a deployment unit.
*
*/
public static void addProcessesXml(DeploymentUnit unit, ProcessesXmlWrapper processesXmlWrapper) {
unit.addToAttachmentList(PROCESSES_XML_LIST, processesXmlWrapper);
}
/**
* Returns the attached {@link ProcessesXml} marker or null;
*
*/
public static List<ProcessesXmlWrapper> getProcessesXmls(DeploymentUnit deploymentUnit) {
return deploymentUnit.getAttachmentList(PROCESSES_XML_LIST);
}
/**
* marks a a {@link DeploymentUnit} as a process application
*/
public static void mark(DeploymentUnit unit) {
unit.putAttachment(MARKER, Boolean.TRUE);
}
/**
* marks a a {@link DeploymentUnit} as part of a process application
*/
public static void markPartOfProcessApplication(DeploymentUnit unit) {
if(unit.getParent() != null && unit.getParent() != unit) {
unit.getParent().putAttachment(PART_OF_MARKER, Boolean.TRUE);
}
}
/**
* return true if the deployment unit is either itself a process
* application or part of a process application.
*/
public static boolean isPartOfProcessApplication(DeploymentUnit unit) {
if(isProcessApplication(unit)) {
return true;
}
if(unit.getParent() != null && unit.getParent() != unit) {
return unit.getParent().hasAttachment(PART_OF_MARKER);
}
return false;
}
/**
* Returns true if the {@link DeploymentUnit} itself is a process application (carries a processes.xml)
*
*/
public static boolean isProcessApplication(DeploymentUnit deploymentUnit) {
return deploymentUnit.hasAttachment(MARKER);
}
/**
* Returns the {@link ComponentDescription} for the {@link AbstractProcessApplication} component
*/
public static ComponentDescription getProcessApplicationComponent(DeploymentUnit deploymentUnit) {
return deploymentUnit.getAttachment(PA_COMPONENT);
}
/**
* Attach the {@link ComponentDescription} for the {@link AbstractProcessApplication} component
*/
public static void attachProcessApplicationComponent(DeploymentUnit deploymentUnit, ComponentDescription componentDescription){
deploymentUnit.putAttachment(PA_COMPONENT, componentDescription);
}
/**
* Attach the {@link AnnotationInstance}s for the PostDeploy methods
*/
public static void attachPostDeployDescription(DeploymentUnit deploymentUnit, AnnotationInstance annotation){
deploymentUnit.putAttachment(POST_DEPLOY_METHOD, annotation);
}
/**
* Attach the {@link AnnotationInstance}s for the PreUndeploy methods
*/
public static void attachPreUndeployDescription(DeploymentUnit deploymentUnit, AnnotationInstance annotation){
deploymentUnit.putAttachment(PRE_UNDEPLOY_METHOD, annotation);
}
/**
* @return the description of the PostDeploy method
*/
public static AnnotationInstance getPostDeployDescription(DeploymentUnit deploymentUnit) {
return deploymentUnit.getAttachment(POST_DEPLOY_METHOD);
}
/**
* @return the description of the PreUndeploy method
*/
public static AnnotationInstance getPreUndeployDescription(DeploymentUnit deploymentUnit) {
return deploymentUnit.getAttachment(PRE_UNDEPLOY_METHOD);
}
private ProcessApplicationAttachments() {
}
}
| xasx/camunda-bpm-platform | distro/wildfly8/subsystem/src/main/java/org/camunda/bpm/container/impl/jboss/deployment/marker/ProcessApplicationAttachments.java | Java | apache-2.0 | 5,340 |
/* Copyright 2010, Object Management Group, Inc.
* Copyright 2010, PrismTech, Inc.
* Copyright 2010, Real-Time Innovations, 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 org.omg.dds.type.typeobject;
import java.util.List;
import org.omg.dds.type.Extensibility;
import org.omg.dds.type.ID;
import org.omg.dds.type.Nested;
@Extensibility(Extensibility.Kind.MUTABLE_EXTENSIBILITY)
@Nested
public interface UnionType extends Type
{
// -----------------------------------------------------------------------
// Properties
// -----------------------------------------------------------------------
@ID(MemberId.MEMBER_UNIONTYPE_MEMBER_ID)
public List<UnionMember> getMember();
// -----------------------------------------------------------------------
// Types
// -----------------------------------------------------------------------
public static final class MemberId
{
// --- Constants: ----------------------------------------------------
public static final int MEMBER_UNIONTYPE_MEMBER_ID = 100;
// --- Constructor: --------------------------------------------------
private MemberId() {
// empty
}
}
}
| steveturner/datadistrib4j | srcJava/org/omg/dds/type/typeobject/UnionType.java | Java | apache-2.0 | 1,765 |
package alien4cloud.tosca.parser.postprocess;
import static alien4cloud.utils.AlienUtils.safe;
import javax.annotation.Resource;
import org.alien4cloud.tosca.model.types.NodeType;
import org.springframework.stereotype.Component;
/**
* Post process a node type.
*/
@Component
public class NodeTypePostProcessor implements IPostProcessor<NodeType> {
@Resource
private CapabilityDefinitionPostProcessor capabilityDefinitionPostProcessor;
@Resource
private RequirementDefinitionPostProcessor requirementDefinitionPostProcessor;
@Override
public void process(NodeType instance) {
safe(instance.getCapabilities()).forEach(capabilityDefinitionPostProcessor);
safe(instance.getRequirements()).forEach(requirementDefinitionPostProcessor);
}
} | alien4cloud/alien4cloud | alien4cloud-tosca/src/main/java/alien4cloud/tosca/parser/postprocess/NodeTypePostProcessor.java | Java | apache-2.0 | 784 |
/*
* Copyright 2021 NAVER Corp.
*
* 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.navercorp.pinpoint.profiler.plugin.config;
import com.navercorp.pinpoint.bootstrap.config.DefaultProfilerConfig;
import com.navercorp.pinpoint.bootstrap.config.Value;
import com.navercorp.pinpoint.common.util.StringUtils;
import java.util.Collections;
import java.util.List;
public class DefaultPluginLoadingConfig implements PluginLoadingConfig {
// ArtifactIdUtils.ARTIFACT_SEPARATOR
private static final String ARTIFACT_SEPARATOR = ";";
private List<String> pluginLoadOrder = Collections.emptyList();
private List<String> disabledPlugins = Collections.emptyList();
private List<String> importPluginIds = Collections.emptyList();
public DefaultPluginLoadingConfig() {
}
@Override
public List<String> getPluginLoadOrder() {
return pluginLoadOrder;
}
@Value("${profiler.plugin.load.order}")
public void setPluginLoadOrder(String pluginLoadOrder) {
this.pluginLoadOrder = StringUtils.tokenizeToStringList(pluginLoadOrder, ",");
}
@Override
public List<String> getDisabledPlugins() {
return disabledPlugins;
}
@Value("${profiler.plugin.disable}")
public void setDisabledPlugins(String disabledPlugins) {
this.disabledPlugins = StringUtils.tokenizeToStringList(disabledPlugins, ",");
}
@Override
public List<String> getImportPluginIds() {
return importPluginIds;
}
@Value("${" + DefaultProfilerConfig.IMPORT_PLUGIN + "}")
public void setImportPluginIds(String importPluginIds) {
this.importPluginIds = StringUtils.tokenizeToStringList(importPluginIds, ARTIFACT_SEPARATOR);
}
@Override
public String toString() {
return "DefaultPluginLoadingConfig{" +
"pluginLoadOrder=" + pluginLoadOrder +
", disabledPlugins=" + disabledPlugins +
", importPluginIds=" + importPluginIds +
'}';
}
}
| emeroad/pinpoint | profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/config/DefaultPluginLoadingConfig.java | Java | apache-2.0 | 2,527 |
package org.jaudiotagger.audio.mp4;
import org.jaudiotagger.audio.generic.GenericAudioHeader;
import org.jaudiotagger.audio.mp4.atom.Mp4EsdsBox;
/**
* Store some additional attributes not available for all audio types
*/
public class Mp4AudioHeader extends GenericAudioHeader {
/**
* The key for the kind field<br>
*
* @see #content
*/
public final static String FIELD_KIND = "KIND";
/**
* The key for the profile<br>
*
* @see #content
*/
public final static String FIELD_PROFILE = "PROFILE";
/**
* The key for the ftyp brand<br>
*
* @see #content
*/
public final static String FIELD_BRAND = "BRAND";
public void setKind(Mp4EsdsBox.Kind kind) {
content.put(FIELD_KIND, kind);
}
/**
* @return kind
*/
public Mp4EsdsBox.Kind getKind() {
return (Mp4EsdsBox.Kind) content.get(FIELD_KIND);
}
/**
* The key for the profile
*
* @param profile
*/
public void setProfile(Mp4EsdsBox.AudioProfile profile) {
content.put(FIELD_PROFILE, profile);
}
/**
* @return audio profile
*/
public Mp4EsdsBox.AudioProfile getProfile() {
return (Mp4EsdsBox.AudioProfile) content.get(FIELD_PROFILE);
}
/**
* @param brand
*/
public void setBrand(String brand) {
content.put(FIELD_BRAND, brand);
}
/**
* @return brand
*/
public String getBrand() {
return (String) content.get(FIELD_BRAND);
}
}
| dubenju/javay | src/java/org/jaudiotagger/audio/mp4/Mp4AudioHeader.java | Java | apache-2.0 | 1,542 |
/*
* Copyright 2016 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.serverhealth;
import com.thoughtworks.go.config.CaseInsensitiveString;
import com.thoughtworks.go.config.CruiseConfig;
import com.thoughtworks.go.config.PipelineConfig;
import com.thoughtworks.go.config.remote.ConfigRepoConfig;
import com.thoughtworks.go.domain.materials.Material;
import com.thoughtworks.go.domain.materials.MaterialConfig;
import org.apache.commons.lang.StringUtils;
import java.util.HashSet;
import java.util.Set;
public class HealthStateScope implements Comparable<HealthStateScope> {
public static final HealthStateScope GLOBAL = new HealthStateScope(ScopeType.GLOBAL, "GLOBAL");
private final ScopeType type;
private final String scope;
private HealthStateScope(ScopeType type, String scope) {
this.type = type;
this.scope = scope;
}
public static HealthStateScope forGroup(String groupName) {
return new HealthStateScope(ScopeType.GROUP, groupName);
}
public static HealthStateScope forPipeline(String pipelineName) {
return new HealthStateScope(ScopeType.PIPELINE, pipelineName);
}
public static HealthStateScope forFanin(String pipelineName) {
return new HealthStateScope(ScopeType.FANIN, pipelineName);
}
public static HealthStateScope forStage(String pipelineName, String stageName) {
return new HealthStateScope(ScopeType.STAGE, pipelineName + "/" + stageName);
}
public static HealthStateScope forJob(String pipelineName, String stageName, String jobName) {
return new HealthStateScope(ScopeType.JOB, pipelineName + "/" + stageName + "/" + jobName);
}
public static HealthStateScope forMaterial(Material material) {
return new HealthStateScope(ScopeType.MATERIAL, material.getSqlCriteria().toString());
}
public static HealthStateScope forMaterialUpdate(Material material) {
return new HealthStateScope(ScopeType.MATERIAL_UPDATE, material.getFingerprint());
}
public static HealthStateScope forMaterialConfig(MaterialConfig materialConfig) {
return new HealthStateScope(ScopeType.MATERIAL, materialConfig.getSqlCriteria().toString());
}
public static HealthStateScope forMaterialConfigUpdate(MaterialConfig materialConfig) {
return new HealthStateScope(ScopeType.MATERIAL_UPDATE, materialConfig.getFingerprint());
}
public static HealthStateScope forConfigRepo(String operation) {
return new HealthStateScope(ScopeType.CONFIG_REPO, operation);
}
public static HealthStateScope forPartialConfigRepo(ConfigRepoConfig repoConfig) {
return new HealthStateScope(ScopeType.CONFIG_PARTIAL, repoConfig.getMaterialConfig().getFingerprint());
}
public static HealthStateScope forPartialConfigRepo(String fingerprint) {
return new HealthStateScope(ScopeType.CONFIG_PARTIAL, fingerprint);
}
public boolean isSame(String scope) {
return StringUtils.endsWithIgnoreCase(this.scope, scope);
}
public boolean isForPipeline() {
return type == ScopeType.PIPELINE;
}
public boolean isForGroup() {
return type == ScopeType.GROUP;
}
public boolean isForMaterial() {
return type == ScopeType.MATERIAL;
}
ScopeType getType() {
return type;
}
public String getScope() {
return scope;
}
public String toString() {
return String.format("LogScope[%s, scope=%s]", type, scope);
}
public boolean equals(Object that) {
if (this == that) { return true; }
if (that == null) { return false; }
if (getClass() != that.getClass()) { return false; }
return equals((HealthStateScope) that);
}
private boolean equals(HealthStateScope that) {
if (type != that.type) { return false; }
if (!scope.equals(that.scope)) { return false; }
return true;
}
public int hashCode() {
int result = type.hashCode();
result = 31 * result + (scope != null ? scope.hashCode() : 0);
return result;
}
public boolean isRemovedFromConfig(CruiseConfig cruiseConfig) {
return type.isRemovedFromConfig(cruiseConfig, scope);
}
public static HealthStateScope forAgent(String cookie) {
return new HealthStateScope(ScopeType.GLOBAL, cookie);
}
public static HealthStateScope forInvalidConfig() {
return new HealthStateScope(ScopeType.GLOBAL, "global");
}
public int compareTo(HealthStateScope o) {
int comparison;
comparison = type.compareTo(o.type);
if (comparison != 0) {
return comparison;
}
comparison = scope.compareTo(o.scope);
if (comparison != 0) {
return comparison;
}
return 0;
}
public static HealthStateScope forPlugin(String symbolicName) {
return new HealthStateScope(ScopeType.PLUGIN, symbolicName);
}
public Set<String> getPipelineNames(CruiseConfig config) {
HashSet<String> pipelineNames = new HashSet<>();
switch (type) {
case PIPELINE:
case FANIN:
pipelineNames.add(scope);
break;
case STAGE:
case JOB:
pipelineNames.add(scope.split("/")[0]);
break;
case MATERIAL:
for (PipelineConfig pc : config.getAllPipelineConfigs()) {
for (MaterialConfig mc : pc.materialConfigs()) {
String scope = HealthStateScope.forMaterialConfig(mc).getScope();
if (scope.equals(this.scope)) {
pipelineNames.add(pc.name().toString());
}
}
}
break;
case MATERIAL_UPDATE:
for (PipelineConfig pc : config.getAllPipelineConfigs()) {
for (MaterialConfig mc : pc.materialConfigs()) {
String scope = HealthStateScope.forMaterialConfigUpdate(mc).getScope();
if (scope.equals(this.scope)) {
pipelineNames.add(pc.name().toString());
}
}
}
break;
}
return pipelineNames;
}
public boolean isForConfigPartial() {
return type == ScopeType.CONFIG_PARTIAL;
}
enum ScopeType {
GLOBAL,
CONFIG_REPO,
GROUP {
public boolean isRemovedFromConfig(CruiseConfig cruiseConfig, String group) {
return !cruiseConfig.hasPipelineGroup(group);
}
},
MATERIAL {
public boolean isRemovedFromConfig(CruiseConfig cruiseConfig, String materialScope) {
for (MaterialConfig materialConfig : cruiseConfig.getAllUniqueMaterials()) {
if (HealthStateScope.forMaterialConfig(materialConfig).getScope().equals(materialScope)) {
return false;
}
}
return true;
}
},
MATERIAL_UPDATE {
public boolean isRemovedFromConfig(CruiseConfig cruiseConfig, String materialScope) {
for (MaterialConfig materialConfig : cruiseConfig.getAllUniqueMaterials()) {
if (HealthStateScope.forMaterialConfigUpdate(materialConfig).getScope().equals(materialScope)) {
return false;
}
}
return true;
}
},
CONFIG_PARTIAL {
public boolean isRemovedFromConfig(CruiseConfig cruiseConfig, String materialScope) {
for (ConfigRepoConfig configRepoConfig : cruiseConfig.getConfigRepos()) {
if (HealthStateScope.forPartialConfigRepo(configRepoConfig).getScope().equals(materialScope)) {
return false;
}
}
return true;
}
},
PIPELINE {
public boolean isRemovedFromConfig(CruiseConfig cruiseConfig, String pipeline) {
return !cruiseConfig.hasPipelineNamed(new CaseInsensitiveString(pipeline));
}
},
FANIN {
public boolean isRemovedFromConfig(CruiseConfig cruiseConfig, String pipeline) {
return !cruiseConfig.hasPipelineNamed(new CaseInsensitiveString(pipeline));
}
},
STAGE {
public boolean isRemovedFromConfig(CruiseConfig cruiseConfig, String pipelineStage) {
String[] parts = pipelineStage.split("/");
return !cruiseConfig.hasStageConfigNamed(new CaseInsensitiveString(parts[0]), new CaseInsensitiveString(parts[1]), true);
}
},
JOB {
public boolean isRemovedFromConfig(CruiseConfig cruiseConfig, String pipelineStageJob) {
String[] parts = pipelineStageJob.split("/");
return !cruiseConfig.hasBuildPlan(new CaseInsensitiveString(parts[0]), new CaseInsensitiveString(parts[1]), parts[2], true);
}
}, PLUGIN;
protected boolean isRemovedFromConfig(CruiseConfig cruiseConfig, String scope) {
return false;
};
}
}
| VibyJocke/gocd | common/src/com/thoughtworks/go/serverhealth/HealthStateScope.java | Java | apache-2.0 | 9,950 |
/*
* Copyright 2019 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.workbench.common.stunner.bpmn.client.marshall.converters.customproperties;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class AssociationListTest {
private AssociationList tested;
public static final String VALUE = "[din]var1->input1,[din]var2->input2,[dout]var3->output1," +
"[dout]var5->output2";
public static final String VALUE_WITH_COMMA = "[din]var1->input1,[din]var2->input2,input22,input33," +
"[dout]var3->output1,[dout]var5->output2,output22,ouput23";
@Before
public void setUp() {
tested = new AssociationList();
}
@Test
public void fromString() {
AssociationList list = tested.fromString(VALUE);
assertEquals(2, list.getInputs().size());
assertEquals(2, list.getOutputs().size());
}
@Test
public void fromStringWithComma() {
AssociationList list = tested.fromString(VALUE_WITH_COMMA);
assertEquals(2, list.getInputs().size());
assertEquals(2, list.getOutputs().size());
}
} | porcelli-forks/kie-wb-common | kie-wb-common-stunner/kie-wb-common-stunner-sets/kie-wb-common-stunner-bpmn/kie-wb-common-stunner-bpmn-marshalling/src/test/java/org/kie/workbench/common/stunner/bpmn/client/marshall/converters/customproperties/AssociationListTest.java | Java | apache-2.0 | 1,713 |
/*
* Copyright 2008-2013 LinkedIn, 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 voldemort.cluster;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import voldemort.VoldemortException;
import voldemort.annotations.concurrency.Threadsafe;
import voldemort.annotations.jmx.JmxGetter;
import voldemort.annotations.jmx.JmxManaged;
import voldemort.utils.Utils;
import com.google.common.collect.Sets;
/**
* A representation of the voldemort cluster
*
*
*/
@Threadsafe
@JmxManaged(description = "Metadata about the physical servers on which the Voldemort cluster runs")
public class Cluster implements Serializable {
private static final long serialVersionUID = 1;
private final String name;
private final int numberOfPartitionIds;
private final Map<Integer, Node> nodesById;
private final Map<Integer, Zone> zonesById;
private final Map<Zone, List<Integer>> nodesPerZone;
private final Map<Zone, List<Integer>> partitionsPerZone;
// Since partitionId space must be dense, arrays could be used instead of
// maps. To do so, the partition ID range would have to be determined. This
// could be done by summing up the lengths of each node's .getPartitionIds()
// returned list. This could be faster to construct and lookup by some
// constant and memory footprint could be better.
private final Map<Integer, Zone> partitionIdToZone;
private final Node[] partitionIdToNodeArray;
private final Map<Integer, Node> partitionIdToNode;
private final Map<Integer, Integer> partitionIdToNodeId;
public Cluster(String name, List<Node> nodes) {
this(name, nodes, new ArrayList<Zone>());
}
public Cluster(String name, List<Node> nodes, List<Zone> zones) {
this.name = Utils.notNull(name);
this.partitionsPerZone = new LinkedHashMap<Zone, List<Integer>>();
this.nodesPerZone = new LinkedHashMap<Zone, List<Integer>>();
this.partitionIdToZone = new HashMap<Integer, Zone>();
Map<Integer, Node> partitionIdToNodeMap = new HashMap<Integer, Node>();
this.partitionIdToNode = new HashMap<Integer, Node>();
this.partitionIdToNodeId = new HashMap<Integer, Integer>();
if(zones.size() != 0) {
zonesById = new LinkedHashMap<Integer, Zone>(zones.size());
for(Zone zone: zones) {
if(zonesById.containsKey(zone.getId()))
throw new IllegalArgumentException("Zone id " + zone.getId()
+ " appears twice in the zone list.");
zonesById.put(zone.getId(), zone);
nodesPerZone.put(zone, new ArrayList<Integer>());
partitionsPerZone.put(zone, new ArrayList<Integer>());
}
} else {
// Add default zone
zonesById = new LinkedHashMap<Integer, Zone>(1);
Zone defaultZone = new Zone();
zonesById.put(defaultZone.getId(), defaultZone);
nodesPerZone.put(defaultZone, new ArrayList<Integer>());
partitionsPerZone.put(defaultZone, new ArrayList<Integer>());
}
this.nodesById = new LinkedHashMap<Integer, Node>(nodes.size());
for(Node node: nodes) {
if(nodesById.containsKey(node.getId()))
throw new IllegalArgumentException("Node id " + node.getId()
+ " appears twice in the node list.");
nodesById.put(node.getId(), node);
Zone nodesZone = zonesById.get(node.getZoneId());
if(nodesZone == null) {
throw new IllegalArgumentException("No zone associated with this node exists.");
}
nodesPerZone.get(nodesZone).add(node.getId());
partitionsPerZone.get(nodesZone).addAll(node.getPartitionIds());
for(Integer partitionId: node.getPartitionIds()) {
if(this.partitionIdToNodeId.containsKey(partitionId)) {
throw new IllegalArgumentException("Partition id " + partitionId
+ " found on two nodes : " + node.getId()
+ " and "
+ this.partitionIdToNodeId.get(partitionId));
}
this.partitionIdToZone.put(partitionId, nodesZone);
partitionIdToNodeMap.put(partitionId, node);
this.partitionIdToNode.put(partitionId, node);
this.partitionIdToNodeId.put(partitionId, node.getId());
}
}
this.numberOfPartitionIds = getNumberOfTags(nodes);
this.partitionIdToNodeArray = new Node[this.numberOfPartitionIds];
for(int partitionId = 0; partitionId < this.numberOfPartitionIds; partitionId++) {
this.partitionIdToNodeArray[partitionId] = partitionIdToNodeMap.get(partitionId);
}
}
private int getNumberOfTags(List<Node> nodes) {
List<Integer> tags = new ArrayList<Integer>();
for(Node node: nodes) {
tags.addAll(node.getPartitionIds());
}
Collections.sort(tags);
for(int i = 0; i < numberOfPartitionIds; i++) {
if(tags.get(i).intValue() != i)
throw new IllegalArgumentException("Invalid tag assignment.");
}
return tags.size();
}
@JmxGetter(name = "name", description = "The name of the cluster")
public String getName() {
return name;
}
public Collection<Node> getNodes() {
return nodesById.values();
}
/**
* @return Sorted set of node Ids
*/
public Set<Integer> getNodeIds() {
Set<Integer> nodeIds = nodesById.keySet();
return new TreeSet<Integer>(nodeIds);
}
/**
*
* @return Sorted set of Zone Ids
*/
public Set<Integer> getZoneIds() {
Set<Integer> zoneIds = zonesById.keySet();
return new TreeSet<Integer>(zoneIds);
}
public Collection<Zone> getZones() {
return zonesById.values();
}
public Zone getZoneById(int id) {
Zone zone = zonesById.get(id);
if(zone == null) {
throw new VoldemortException("No such zone in cluster: " + id
+ " Available zones : " + displayZones());
}
return zone;
}
private String displayZones() {
String zoneIDS = "{";
for(Zone z: this.getZones()) {
if(zoneIDS.length() != 1)
zoneIDS += ",";
zoneIDS += z.getId();
}
zoneIDS += "}";
return zoneIDS;
}
public int getNumberOfZones() {
return zonesById.size();
}
public int getNumberOfPartitionsInZone(Integer zoneId) {
return partitionsPerZone.get(getZoneById(zoneId)).size();
}
public int getNumberOfNodesInZone(Integer zoneId) {
return nodesPerZone.get(getZoneById(zoneId)).size();
}
/**
* @return Sorted set of node Ids for given zone
*/
public Set<Integer> getNodeIdsInZone(Integer zoneId) {
return new TreeSet<Integer>(nodesPerZone.get(getZoneById(zoneId)));
}
/**
* @return Sorted set of partition Ids for given zone
*/
public Set<Integer> getPartitionIdsInZone(Integer zoneId) {
return new TreeSet<Integer>(partitionsPerZone.get(getZoneById(zoneId)));
}
public Zone getZoneForPartitionId(int partitionId) {
return partitionIdToZone.get(partitionId);
}
public Node getNodeForPartitionId(int partitionId) {
return this.partitionIdToNodeArray[partitionId];
}
public Node[] getPartitionIdToNodeArray() {
return this.partitionIdToNodeArray;
}
/**
*
* @return Map of partition id to node id.
*/
public Map<Integer, Integer> getPartitionIdToNodeIdMap() {
return new HashMap<Integer, Integer>(partitionIdToNodeId);
}
public Node getNodeById(int id) {
Node node = nodesById.get(id);
if(node == null)
throw new VoldemortException("No such node in cluster: " + id);
return node;
}
/**
* Given a cluster and a node id checks if the node exists
*
* @param nodeId The node id to search for
* @return True if cluster contains the node id, else false
*/
public boolean hasNodeWithId(int nodeId) {
Node node = nodesById.get(nodeId);
if(node == null) {
return false;
}
return true;
}
@JmxGetter(name = "numberOfNodes", description = "The number of nodes in the cluster.")
public int getNumberOfNodes() {
return nodesById.size();
}
public int getNumberOfPartitions() {
return numberOfPartitionIds;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Cluster('");
builder.append(getName());
builder.append("', [");
for(Node n: getNodes()) {
builder.append(n.toString());
builder.append('\n');
}
builder.append("])");
return builder.toString();
}
/**
* Return a detailed string representation of the current cluster
*
* @param isDetailed
* @return descripton of cluster
*/
public String toString(boolean isDetailed) {
if(!isDetailed) {
return toString();
}
StringBuilder builder = new StringBuilder("Cluster [" + getName() + "] Nodes ["
+ getNumberOfNodes() + "] Zones ["
+ getNumberOfZones() + "] Partitions ["
+ getNumberOfPartitions() + "]");
builder.append(" Zone Info [" + getZones() + "]");
builder.append(" Node Info [" + getNodes() + "]");
return builder.toString();
}
/**
* Clones the cluster by constructing a new one with same name, partition
* layout, and nodes.
*
* @param cluster
* @return clone of Cluster cluster.
*/
public static Cluster cloneCluster(Cluster cluster) {
// Could add a better .clone() implementation that clones the derived
// data structures. The constructor invoked by this clone implementation
// can be slow for large numbers of partitions. Probably faster to copy
// all the maps and stuff.
return new Cluster(cluster.getName(),
new ArrayList<Node>(cluster.getNodes()),
new ArrayList<Zone>(cluster.getZones()));
/*-
* Historic "clone" code being kept in case this, for some reason, was the "right" way to be doing this.
ClusterMapper mapper = new ClusterMapper();
return mapper.readCluster(new StringReader(mapper.writeCluster(cluster)));
*/
}
@Override
public boolean equals(Object second) {
if(this == second)
return true;
if(second == null || second.getClass() != getClass())
return false;
Cluster secondCluster = (Cluster) second;
if(this.getZones().size() != secondCluster.getZones().size()) {
return false;
}
if(this.getNodes().size() != secondCluster.getNodes().size()) {
return false;
}
for(Zone zoneA: this.getZones()) {
Zone zoneB;
try {
zoneB = secondCluster.getZoneById(zoneA.getId());
} catch(VoldemortException e) {
return false;
}
if(zoneB == null || zoneB.getProximityList().size() != zoneA.getProximityList().size()) {
return false;
}
for(int index = 0; index < zoneA.getProximityList().size(); index++) {
if(zoneA.getProximityList().get(index) != zoneB.getProximityList().get(index)) {
return false;
}
}
}
for(Node nodeA: this.getNodes()) {
Node nodeB;
try {
nodeB = secondCluster.getNodeById(nodeA.getId());
} catch(VoldemortException e) {
return false;
}
if(nodeA.getNumberOfPartitions() != nodeB.getNumberOfPartitions()) {
return false;
}
if(nodeA.getZoneId() != nodeB.getZoneId()) {
return false;
}
if(!Sets.newHashSet(nodeA.getPartitionIds())
.equals(Sets.newHashSet(nodeB.getPartitionIds())))
return false;
}
return true;
}
@Override
public int hashCode() {
int hc = getNodes().size();
for(Node node: getNodes()) {
hc ^= node.getHost().hashCode();
}
return hc;
}
}
| HB-SI/voldemort | src/java/voldemort/cluster/Cluster.java | Java | apache-2.0 | 13,745 |
/**
* Copyright 2014-2016 CyberVision, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kaaproject.kaa.server.common.nosql.cassandra.dao.model;
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;
import org.junit.Test;
public class CassandraEndpointUserTest {
@Test
public void hashCodeEqualsTest(){
EqualsVerifier.forClass(CassandraEndpointUser.class).suppress(Warning.NONFINAL_FIELDS).verify();
}
} | Deepnekroz/kaa | server/common/nosql/cassandra-dao/src/test/java/org/kaaproject/kaa/server/common/nosql/cassandra/dao/model/CassandraEndpointUserTest.java | Java | apache-2.0 | 999 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.search.aggregations.bucket.composite;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.LeafReaderContext;
import org.elasticsearch.search.aggregations.LeafBucketCollector;
import java.io.IOException;
import static org.elasticsearch.search.aggregations.support.ValuesSource.Numeric;
import static org.elasticsearch.search.aggregations.support.ValuesSource.Bytes;
import static org.elasticsearch.search.aggregations.support.ValuesSource.Bytes.WithOrdinals;
final class CompositeValuesComparator {
private final int size;
private final CompositeValuesSource<?, ?>[] arrays;
private boolean topValueSet = false;
/**
*
* @param sources The list of {@link CompositeValuesSourceConfig} to build the composite buckets.
* @param size The number of composite buckets to keep.
*/
CompositeValuesComparator(IndexReader reader, CompositeValuesSourceConfig[] sources, int size) {
this.size = size;
this.arrays = new CompositeValuesSource<?, ?>[sources.length];
for (int i = 0; i < sources.length; i++) {
final int reverseMul = sources[i].reverseMul();
if (sources[i].valuesSource() instanceof WithOrdinals && reader instanceof DirectoryReader) {
WithOrdinals vs = (WithOrdinals) sources[i].valuesSource();
arrays[i] = CompositeValuesSource.wrapGlobalOrdinals(vs, size, reverseMul);
} else if (sources[i].valuesSource() instanceof Bytes) {
Bytes vs = (Bytes) sources[i].valuesSource();
arrays[i] = CompositeValuesSource.wrapBinary(vs, size, reverseMul);
} else if (sources[i].valuesSource() instanceof Numeric) {
final Numeric vs = (Numeric) sources[i].valuesSource();
if (vs.isFloatingPoint()) {
arrays[i] = CompositeValuesSource.wrapDouble(vs, size, reverseMul);
} else {
arrays[i] = CompositeValuesSource.wrapLong(vs, sources[i].format(), size, reverseMul);
}
}
}
}
/**
* Moves the values in <code>slot1</code> to <code>slot2</code>.
*/
void move(int slot1, int slot2) {
assert slot1 < size && slot2 < size;
for (int i = 0; i < arrays.length; i++) {
arrays[i].move(slot1, slot2);
}
}
/**
* Compares the values in <code>slot1</code> with <code>slot2</code>.
*/
int compare(int slot1, int slot2) {
assert slot1 < size && slot2 < size;
for (int i = 0; i < arrays.length; i++) {
int cmp = arrays[i].compare(slot1, slot2);
if (cmp != 0) {
return cmp;
}
}
return 0;
}
/**
* Returns true if a top value has been set for this comparator.
*/
boolean hasTop() {
return topValueSet;
}
/**
* Sets the top values for this comparator.
*/
void setTop(Comparable<?>[] values) {
assert values.length == arrays.length;
topValueSet = true;
for (int i = 0; i < arrays.length; i++) {
arrays[i].setTop(values[i]);
}
}
/**
* Compares the top values with the values in <code>slot</code>.
*/
int compareTop(int slot) {
assert slot < size;
for (int i = 0; i < arrays.length; i++) {
int cmp = arrays[i].compareTop(slot);
if (cmp != 0) {
return cmp;
}
}
return 0;
}
/**
* Builds the {@link CompositeKey} for <code>slot</code>.
*/
CompositeKey toCompositeKey(int slot) throws IOException {
assert slot < size;
Comparable<?>[] values = new Comparable<?>[arrays.length];
for (int i = 0; i < values.length; i++) {
values[i] = arrays[i].toComparable(slot);
}
return new CompositeKey(values);
}
/**
* Gets the {@link LeafBucketCollector} that will record the composite buckets of the visited documents.
*/
CompositeValuesSource.Collector getLeafCollector(LeafReaderContext context, CompositeValuesSource.Collector in) throws IOException {
int last = arrays.length - 1;
CompositeValuesSource.Collector next = arrays[last].getLeafCollector(context, in);
for (int i = last - 1; i >= 0; i--) {
next = arrays[i].getLeafCollector(context, next);
}
return next;
}
}
| qwerty4030/elasticsearch | server/src/main/java/org/elasticsearch/search/aggregations/bucket/composite/CompositeValuesComparator.java | Java | apache-2.0 | 5,333 |
/*
* 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.tamaya.events;
import org.apache.tamaya.ConfigException;
import org.apache.tamaya.ConfigOperator;
import org.apache.tamaya.ConfigQuery;
import org.apache.tamaya.Configuration;
import org.apache.tamaya.ConfigurationProvider;
import org.apache.tamaya.TypeLiteral;
import org.apache.tamaya.spi.PropertyConverter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
/**
* Created by Anatole on 24.03.2015.
*/
public class TestConfigView implements ConfigOperator{
private static final TestConfigView INSTANCE = new TestConfigView();
private TestConfigView(){}
public static ConfigOperator of(){
return INSTANCE;
}
@Override
public Configuration operate(final Configuration config) {
return new Configuration() {
@Override
public Map<String, String> getProperties() {
Map<String, String> result = new HashMap<>();
for (Map.Entry<String, String> en : config.getProperties().entrySet()) {
if (en.getKey().startsWith("test")) {
result.put(en.getKey(), en.getValue());
}
}
return result;
// return config.getProperties().entrySet().stream().filter(e -> e.getKey().startsWith("test")).collect(
// Collectors.toMap(en -> en.getKey(), en -> en.getValue()));
}
@Override
public Configuration with(ConfigOperator operator) {
return null;
}
@Override
public <T> T query(ConfigQuery<T> query) {
return null;
}
@Override
public String get(String key) {
return getProperties().get(key);
}
@Override
public <T> T get(String key, Class<T> type) {
return (T) get(key, TypeLiteral.of(type));
}
/**
* Accesses the current String value for the given key and tries to convert it
* using the {@link org.apache.tamaya.spi.PropertyConverter} instances provided by the current
* {@link org.apache.tamaya.spi.ConfigurationContext}.
*
* @param key the property's absolute, or relative path, e.g. @code
* a/b/c/d.myProperty}.
* @param type The target type required, not null.
* @param <T> the value type
* @return the converted value, never null.
*/
@Override
public <T> T get(String key, TypeLiteral<T> type) {
String value = get(key);
if (value != null) {
List<PropertyConverter<T>> converters = ConfigurationProvider.getConfigurationContext()
.getPropertyConverters(type);
for (PropertyConverter<T> converter : converters) {
try {
T t = converter.convert(value);
if (t != null) {
return t;
}
} catch (Exception e) {
Logger.getLogger(getClass().getName())
.log(Level.FINEST, "PropertyConverter: " + converter + " failed to convert value: "
+ value, e);
}
}
throw new ConfigException("Unparseable config value for type: " + type.getRawType().getName() + ": " + key);
}
return null;
}
};
}
}
| syzer/incubator-tamaya | modules/events/src/test/java/org/apache/tamaya/events/TestConfigView.java | Java | apache-2.0 | 4,643 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.table.planner.functions.aggfunctions;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.expressions.Expression;
import org.apache.flink.table.expressions.UnresolvedCallExpression;
import org.apache.flink.table.expressions.UnresolvedReferenceExpression;
import org.apache.flink.table.types.DataType;
import org.apache.flink.table.types.logical.DecimalType;
import org.apache.flink.table.types.logical.utils.LogicalTypeMerging;
import java.math.BigDecimal;
import static org.apache.flink.table.expressions.ApiExpressionUtils.unresolvedRef;
import static org.apache.flink.table.planner.expressions.ExpressionBuilder.cast;
import static org.apache.flink.table.planner.expressions.ExpressionBuilder.div;
import static org.apache.flink.table.planner.expressions.ExpressionBuilder.equalTo;
import static org.apache.flink.table.planner.expressions.ExpressionBuilder.ifThenElse;
import static org.apache.flink.table.planner.expressions.ExpressionBuilder.isNull;
import static org.apache.flink.table.planner.expressions.ExpressionBuilder.literal;
import static org.apache.flink.table.planner.expressions.ExpressionBuilder.minus;
import static org.apache.flink.table.planner.expressions.ExpressionBuilder.nullOf;
import static org.apache.flink.table.planner.expressions.ExpressionBuilder.plus;
import static org.apache.flink.table.planner.expressions.ExpressionBuilder.typeLiteral;
/** built-in avg aggregate function. */
public abstract class AvgAggFunction extends DeclarativeAggregateFunction {
private UnresolvedReferenceExpression sum = unresolvedRef("sum");
private UnresolvedReferenceExpression count = unresolvedRef("count");
public abstract DataType getSumType();
@Override
public int operandCount() {
return 1;
}
@Override
public UnresolvedReferenceExpression[] aggBufferAttributes() {
return new UnresolvedReferenceExpression[] {sum, count};
}
@Override
public DataType[] getAggBufferTypes() {
return new DataType[] {getSumType(), DataTypes.BIGINT()};
}
@Override
public Expression[] initialValuesExpressions() {
return new Expression[] {
/* sum = */ literal(0L, getSumType().notNull()), /* count = */ literal(0L)
};
}
@Override
public Expression[] accumulateExpressions() {
return new Expression[] {
/* sum = */ adjustSumType(ifThenElse(isNull(operand(0)), sum, plus(sum, operand(0)))),
/* count = */ ifThenElse(isNull(operand(0)), count, plus(count, literal(1L))),
};
}
@Override
public Expression[] retractExpressions() {
return new Expression[] {
/* sum = */ adjustSumType(ifThenElse(isNull(operand(0)), sum, minus(sum, operand(0)))),
/* count = */ ifThenElse(isNull(operand(0)), count, minus(count, literal(1L))),
};
}
@Override
public Expression[] mergeExpressions() {
return new Expression[] {
/* sum = */ adjustSumType(plus(sum, mergeOperand(sum))),
/* count = */ plus(count, mergeOperand(count))
};
}
private UnresolvedCallExpression adjustSumType(UnresolvedCallExpression sumExpr) {
return cast(sumExpr, typeLiteral(getSumType()));
}
/** If all input are nulls, count will be 0 and we will get null after the division. */
@Override
public Expression getValueExpression() {
Expression ifTrue = nullOf(getResultType());
Expression ifFalse = cast(div(sum, count), typeLiteral(getResultType()));
return ifThenElse(equalTo(count, literal(0L)), ifTrue, ifFalse);
}
/** Built-in Byte Avg aggregate function. */
public static class ByteAvgAggFunction extends AvgAggFunction {
@Override
public DataType getResultType() {
return DataTypes.TINYINT();
}
@Override
public DataType getSumType() {
return DataTypes.BIGINT();
}
}
/** Built-in Short Avg aggregate function. */
public static class ShortAvgAggFunction extends AvgAggFunction {
@Override
public DataType getResultType() {
return DataTypes.SMALLINT();
}
@Override
public DataType getSumType() {
return DataTypes.BIGINT();
}
}
/** Built-in Integer Avg aggregate function. */
public static class IntAvgAggFunction extends AvgAggFunction {
@Override
public DataType getResultType() {
return DataTypes.INT();
}
@Override
public DataType getSumType() {
return DataTypes.BIGINT();
}
}
/** Built-in Long Avg aggregate function. */
public static class LongAvgAggFunction extends AvgAggFunction {
@Override
public DataType getResultType() {
return DataTypes.BIGINT();
}
@Override
public DataType getSumType() {
return DataTypes.BIGINT();
}
}
/** Built-in Float Avg aggregate function. */
public static class FloatAvgAggFunction extends AvgAggFunction {
@Override
public DataType getResultType() {
return DataTypes.FLOAT();
}
@Override
public DataType getSumType() {
return DataTypes.DOUBLE();
}
@Override
public Expression[] initialValuesExpressions() {
return new Expression[] {literal(0D), literal(0L)};
}
}
/** Built-in Double Avg aggregate function. */
public static class DoubleAvgAggFunction extends AvgAggFunction {
@Override
public DataType getResultType() {
return DataTypes.DOUBLE();
}
@Override
public DataType getSumType() {
return DataTypes.DOUBLE();
}
@Override
public Expression[] initialValuesExpressions() {
return new Expression[] {literal(0D), literal(0L)};
}
}
/** Built-in Decimal Avg aggregate function. */
public static class DecimalAvgAggFunction extends AvgAggFunction {
private final DecimalType type;
public DecimalAvgAggFunction(DecimalType type) {
this.type = type;
}
@Override
public DataType getResultType() {
DecimalType t = (DecimalType) LogicalTypeMerging.findAvgAggType(type);
return DataTypes.DECIMAL(t.getPrecision(), t.getScale());
}
@Override
public DataType getSumType() {
DecimalType t = (DecimalType) LogicalTypeMerging.findSumAggType(type);
return DataTypes.DECIMAL(t.getPrecision(), t.getScale());
}
@Override
public Expression[] initialValuesExpressions() {
return new Expression[] {literal(BigDecimal.ZERO, getSumType().notNull()), literal(0L)};
}
}
}
| StephanEwen/incubator-flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/aggfunctions/AvgAggFunction.java | Java | apache-2.0 | 7,723 |
/*
* 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.
*/
/**
* Defines relational expressions and rules for converting between calling
* conventions.
*/
package org.apache.calcite.rel.convert;
// End package-info.java
| mehant/incubator-calcite | core/src/main/java/org/apache/calcite/rel/convert/package-info.java | Java | apache-2.0 | 964 |
/*Copyright (C) 2012 Longerian (http://www.longerian.me)
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.rubychina.android;
import java.util.ArrayList;
import java.util.List;
import org.rubychina.android.type.Node;
import org.rubychina.android.type.SiteGroup;
import org.rubychina.android.type.Topic;
import org.rubychina.android.type.User;
public enum GlobalResource {
INSTANCE;
private List<Topic> curTopics = new ArrayList<Topic>();
private List<Node> nodes = new ArrayList<Node>();
private List<User> users = new ArrayList<User>();
private List<SiteGroup> sites = new ArrayList<SiteGroup>();
public synchronized List<Topic> getCurTopics() {
return curTopics;
}
public synchronized void setCurTopics(List<Topic> curTopics) {
this.curTopics = curTopics;
}
public synchronized List<Node> getNodes() {
return nodes;
}
public synchronized void setNodes(List<Node> nodes) {
this.nodes = nodes;
}
public synchronized List<User> getUsers() {
return users;
}
public synchronized void setUsers(List<User> users) {
this.users = users;
}
public synchronized List<SiteGroup> getSites() {
return sites;
}
public synchronized void setSites(List<SiteGroup> sites) {
this.sites = sites;
}
}
| longerian/RC4A | src/org/rubychina/android/GlobalResource.java | Java | apache-2.0 | 1,797 |
/*
* Copyright 2011 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.workbench.common.widgets.client.widget;
public class PercentageCalculator {
public static int calculatePercent(int numerator,
int denominator) {
int percent = 0;
if (denominator != 0) {
percent = (int) ((((float) denominator - (float) numerator) / (float) denominator) * 100);
}
return percent;
}
}
| psiroky/kie-wb-common | kie-wb-common-widgets/kie-wb-common-ui/src/main/java/org/kie/workbench/common/widgets/client/widget/PercentageCalculator.java | Java | apache-2.0 | 979 |
/*
* Copyright 2015 DuraSpace, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fcrepo.http.api;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @author cabeer
* @since 10/17/14
*/
@Component
public class FedoraHttpConfiguration {
@Value("${fcrepo.http.ldp.putRequiresIfMatch:false}")
private boolean putRequiresIfMatch;
/**
* Should PUT requests require an If-Match header?
* @return put request if match
*/
public boolean putRequiresIfMatch() {
return putRequiresIfMatch;
}
}
| ruebot/fcrepo4 | fcrepo-http-api/src/main/java/org/fcrepo/http/api/FedoraHttpConfiguration.java | Java | apache-2.0 | 1,125 |
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.util.xml.highlighting;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.lang.annotation.Annotation;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiReference;
import com.intellij.util.xml.DomElement;
import com.intellij.util.xml.DomFileElement;
import com.intellij.util.xml.GenericDomValue;
import com.intellij.util.xml.reflect.DomCollectionChildDescription;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public interface DomElementAnnotationHolder extends Iterable<DomElementProblemDescriptor>{
boolean isOnTheFly();
@NotNull
DomFileElement<?> getFileElement();
@NotNull
DomElementProblemDescriptor createProblem(@NotNull DomElement domElement, @Nullable String message, LocalQuickFix... fixes);
@NotNull
DomElementProblemDescriptor createProblem(@NotNull DomElement domElement, DomCollectionChildDescription childDescription, @Nullable String message);
@NotNull
DomElementProblemDescriptor createProblem(@NotNull DomElement domElement, HighlightSeverity highlightType, String message);
DomElementProblemDescriptor createProblem(@NotNull DomElement domElement, HighlightSeverity highlightType, String message, LocalQuickFix... fixes);
DomElementProblemDescriptor createProblem(@NotNull DomElement domElement, HighlightSeverity highlightType, String message, TextRange textRange, LocalQuickFix... fixes);
DomElementProblemDescriptor createProblem(@NotNull DomElement domElement, ProblemHighlightType highlightType, String message, @Nullable TextRange textRange, LocalQuickFix... fixes);
@NotNull
DomElementResolveProblemDescriptor createResolveProblem(@NotNull GenericDomValue element, @NotNull PsiReference reference);
/**
* Is useful only if called from {@link com.intellij.util.xml.highlighting.DomElementsAnnotator} instance
* @param element element
* @param severity highlight severity
* @param message description
* @return annotation
*/
@NotNull
Annotation createAnnotation(@NotNull DomElement element, HighlightSeverity severity, @Nullable String message);
int getSize();
}
| paplorinc/intellij-community | xml/dom-openapi/src/com/intellij/util/xml/highlighting/DomElementAnnotationHolder.java | Java | apache-2.0 | 2,866 |
package com.mapswithme.maps.purchase;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.android.billingclient.api.SkuDetails;
import com.bumptech.glide.Glide;
import com.mapswithme.maps.Framework;
import com.mapswithme.maps.PrivateVariables;
import com.mapswithme.maps.PurchaseOperationObservable;
import com.mapswithme.maps.R;
import com.mapswithme.maps.base.BaseMwmFragment;
import com.mapswithme.maps.bookmarks.data.PaymentData;
import com.mapswithme.maps.dialog.AlertDialogCallback;
import com.mapswithme.util.Utils;
import com.mapswithme.util.log.Logger;
import com.mapswithme.util.log.LoggerFactory;
import com.mapswithme.util.statistics.Statistics;
import java.util.Collections;
import java.util.List;
public class BookmarkPaymentFragment extends BaseMwmFragment
implements AlertDialogCallback, PurchaseStateActivator<BookmarkPaymentState>
{
static final String ARG_PAYMENT_DATA = "arg_payment_data";
private static final Logger LOGGER = LoggerFactory.INSTANCE.getLogger(LoggerFactory.Type.BILLING);
private static final String TAG = BookmarkPaymentFragment.class.getSimpleName();
private static final String EXTRA_CURRENT_STATE = "extra_current_state";
private static final String EXTRA_PRODUCT_DETAILS = "extra_product_details";
private static final String EXTRA_SUBS_PRODUCT_DETAILS = "extra_subs_product_details";
private static final String EXTRA_VALIDATION_RESULT = "extra_validation_result";
@SuppressWarnings("NullableProblems")
@NonNull
private PurchaseController<PurchaseCallback> mPurchaseController;
@SuppressWarnings("NullableProblems")
@NonNull
private BookmarkPurchaseCallback mPurchaseCallback;
@SuppressWarnings("NullableProblems")
@NonNull
private PaymentData mPaymentData;
@Nullable
private ProductDetails mProductDetails;
@Nullable
private ProductDetails mSubsProductDetails;
private boolean mValidationResult;
@NonNull
private BookmarkPaymentState mState = BookmarkPaymentState.NONE;
@SuppressWarnings("NullableProblems")
@NonNull
private BillingManager<PlayStoreBillingCallback> mSubsProductDetailsLoadingManager;
@NonNull
private final SubsProductDetailsCallback mSubsProductDetailsCallback
= new SubsProductDetailsCallback();
@Override
public void onCreate(@Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args == null)
throw new IllegalStateException("Args must be provided for payment fragment!");
PaymentData paymentData = args.getParcelable(ARG_PAYMENT_DATA);
if (paymentData == null)
throw new IllegalStateException("Payment data must be provided for payment fragment!");
mPaymentData = paymentData;
mPurchaseCallback = new BookmarkPurchaseCallback(mPaymentData.getServerId());
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable
Bundle savedInstanceState)
{
mPurchaseController = PurchaseFactory.createBookmarkPurchaseController(requireContext(),
mPaymentData.getProductId(),
mPaymentData.getServerId());
if (savedInstanceState != null)
mPurchaseController.onRestore(savedInstanceState);
mPurchaseController.initialize(requireActivity());
mSubsProductDetailsLoadingManager = PurchaseFactory.createSubscriptionBillingManager();
mSubsProductDetailsLoadingManager.initialize(requireActivity());
mSubsProductDetailsLoadingManager.addCallback(mSubsProductDetailsCallback);
mSubsProductDetailsCallback.attach(this);
View root = inflater.inflate(R.layout.fragment_bookmark_payment, container, false);
View subscriptionButton = root.findViewById(R.id.buy_subs_btn);
subscriptionButton.setOnClickListener(v -> onBuySubscriptionClicked());
TextView buyInappBtn = root.findViewById(R.id.buy_inapp_btn);
buyInappBtn.setOnClickListener(v -> onBuyInappClicked());
return root;
}
private void onBuySubscriptionClicked()
{
SubscriptionType type = SubscriptionType.getTypeByBookmarksGroup(mPaymentData.getGroup());
if (type.equals(SubscriptionType.BOOKMARKS_SIGHTS))
{
BookmarksSightsSubscriptionActivity.startForResult
(this, PurchaseUtils.REQ_CODE_PAY_SUBSCRIPTION, Statistics.ParamValue.CARD);
return;
}
BookmarksAllSubscriptionActivity.startForResult
(this, PurchaseUtils.REQ_CODE_PAY_SUBSCRIPTION, Statistics.ParamValue.CARD);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK)
return;
if (requestCode == PurchaseUtils.REQ_CODE_PAY_SUBSCRIPTION)
{
Intent intent = new Intent();
intent.putExtra(PurchaseUtils.EXTRA_IS_SUBSCRIPTION, true);
requireActivity().setResult(Activity.RESULT_OK, intent);
requireActivity().finish();
}
}
private void onBuyInappClicked()
{
Statistics.INSTANCE.trackPurchasePreviewSelect(mPaymentData.getServerId(),
mPaymentData.getProductId());
Statistics.INSTANCE.trackPurchaseEvent(Statistics.EventName.INAPP_PURCHASE_PREVIEW_PAY,
mPaymentData.getServerId(),
Statistics.STATISTICS_CHANNEL_REALTIME);
startPurchaseTransaction();
}
@Override
public boolean onBackPressed()
{
if (mState == BookmarkPaymentState.VALIDATION)
{
Toast.makeText(requireContext(), R.string.purchase_please_wait_toast, Toast.LENGTH_SHORT)
.show();
return true;
}
Statistics.INSTANCE.trackPurchaseEvent(Statistics.EventName.INAPP_PURCHASE_PREVIEW_CANCEL,
mPaymentData.getServerId());
return super.onBackPressed();
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
if (savedInstanceState == null)
Statistics.INSTANCE.trackPurchasePreviewShow(mPaymentData.getServerId(),
PrivateVariables.bookmarksVendor(),
mPaymentData.getProductId());
LOGGER.d(TAG, "onViewCreated savedInstanceState = " + savedInstanceState);
setInitialPaymentData();
loadImage();
if (savedInstanceState != null)
{
mProductDetails = savedInstanceState.getParcelable(EXTRA_PRODUCT_DETAILS);
if (mProductDetails != null)
updateProductDetails();
mSubsProductDetails = savedInstanceState.getParcelable(EXTRA_SUBS_PRODUCT_DETAILS);
if (mSubsProductDetails != null)
updateSubsProductDetails();
mValidationResult = savedInstanceState.getBoolean(EXTRA_VALIDATION_RESULT);
BookmarkPaymentState savedState
= BookmarkPaymentState.values()[savedInstanceState.getInt(EXTRA_CURRENT_STATE)];
activateState(savedState);
return;
}
activateState(BookmarkPaymentState.PRODUCT_DETAILS_LOADING);
mPurchaseController.queryProductDetails();
SubscriptionType type = SubscriptionType.getTypeByBookmarksGroup(mPaymentData.getGroup());
List<String> subsProductIds =
Collections.singletonList(type.getMonthlyProductId());
mSubsProductDetailsLoadingManager.queryProductDetails(subsProductIds);
}
@Override
public void onDestroyView()
{
super.onDestroyView();
mPurchaseController.destroy();
mSubsProductDetailsLoadingManager.removeCallback(mSubsProductDetailsCallback);
mSubsProductDetailsCallback.detach();
mSubsProductDetailsLoadingManager.destroy();
}
private void startPurchaseTransaction()
{
activateState(BookmarkPaymentState.TRANSACTION_STARTING);
Framework.nativeStartPurchaseTransaction(mPaymentData.getServerId(),
PrivateVariables.bookmarksVendor());
}
void launchBillingFlow()
{
mPurchaseController.launchPurchaseFlow(mPaymentData.getProductId());
activateState(BookmarkPaymentState.PAYMENT_IN_PROGRESS);
}
@Override
public void onStart()
{
super.onStart();
PurchaseOperationObservable observable = PurchaseOperationObservable.from(requireContext());
observable.addTransactionObserver(mPurchaseCallback);
mPurchaseController.addCallback(mPurchaseCallback);
mPurchaseCallback.attach(this);
}
@Override
public void onStop()
{
super.onStop();
PurchaseOperationObservable observable = PurchaseOperationObservable.from(requireContext());
observable.removeTransactionObserver(mPurchaseCallback);
mPurchaseController.removeCallback();
mPurchaseCallback.detach();
}
@Override
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
LOGGER.d(TAG, "onSaveInstanceState");
outState.putInt(EXTRA_CURRENT_STATE, mState.ordinal());
outState.putParcelable(EXTRA_PRODUCT_DETAILS, mProductDetails);
outState.putParcelable(EXTRA_SUBS_PRODUCT_DETAILS, mSubsProductDetails);
mPurchaseController.onSave(outState);
}
@Override
public void activateState(@NonNull BookmarkPaymentState state)
{
if (state == mState)
return;
LOGGER.i(TAG, "Activate state: " + state);
mState = state;
mState.activate(this);
}
private void loadImage()
{
if (TextUtils.isEmpty(mPaymentData.getImgUrl()))
return;
ImageView imageView = getViewOrThrow().findViewById(R.id.image);
Glide.with(imageView.getContext())
.load(mPaymentData.getImgUrl())
.centerCrop()
.into(imageView);
}
private void setInitialPaymentData()
{
TextView name = getViewOrThrow().findViewById(R.id.product_catalog_name);
name.setText(mPaymentData.getName());
TextView author = getViewOrThrow().findViewById(R.id.author_name);
author.setText(mPaymentData.getAuthorName());
}
void handleProductDetails(@NonNull List<SkuDetails> details)
{
if (details.isEmpty())
return;
SkuDetails skuDetails = details.get(0);
mProductDetails = PurchaseUtils.toProductDetails(skuDetails);
}
void handleSubsProductDetails(@NonNull List<SkuDetails> details)
{
if (details.isEmpty())
return;
SkuDetails skuDetails = details.get(0);
mSubsProductDetails = PurchaseUtils.toProductDetails(skuDetails);
}
void handleValidationResult(boolean validationResult)
{
mValidationResult = validationResult;
}
@Override
public void onAlertDialogPositiveClick(int requestCode, int which)
{
handleErrorDialogEvent(requestCode);
}
@Override
public void onAlertDialogNegativeClick(int requestCode, int which)
{
// Do nothing by default.
}
@Override
public void onAlertDialogCancel(int requestCode)
{
handleErrorDialogEvent(requestCode);
}
private void handleErrorDialogEvent(int requestCode)
{
switch (requestCode)
{
case PurchaseUtils.REQ_CODE_PRODUCT_DETAILS_FAILURE:
requireActivity().finish();
break;
case PurchaseUtils.REQ_CODE_START_TRANSACTION_FAILURE:
case PurchaseUtils.REQ_CODE_PAYMENT_FAILURE:
activateState(BookmarkPaymentState.PRODUCT_DETAILS_LOADED);
break;
}
}
void updateProductDetails()
{
if (mProductDetails == null)
throw new AssertionError("Product details must be obtained at this moment!");
TextView buyButton = getViewOrThrow().findViewById(R.id.buy_inapp_btn);
String price = Utils.formatCurrencyString(mProductDetails.getPrice(),
mProductDetails.getCurrencyCode());
buyButton.setText(getString(R.string.buy_btn, price));
TextView storeName = getViewOrThrow().findViewById(R.id.product_store_name);
storeName.setText(mProductDetails.getTitle());
}
void updateSubsProductDetails()
{
if (mSubsProductDetails == null)
throw new AssertionError("Subs product details must be obtained at this moment!");
String formattedPrice = Utils.formatCurrencyString(mSubsProductDetails.getPrice(),
mSubsProductDetails.getCurrencyCode());
TextView subsButton = getViewOrThrow().findViewById(R.id.buy_subs_btn);
subsButton.setText(getString(R.string.buy_btn_for_subscription_version_2, formattedPrice));
}
void finishValidation()
{
if (mValidationResult)
requireActivity().setResult(Activity.RESULT_OK);
requireActivity().finish();
}
}
| matsprea/omim | android/src/com/mapswithme/maps/purchase/BookmarkPaymentFragment.java | Java | apache-2.0 | 13,042 |
/*
* Copyright 2010-2013 Coda Hale and Yammer, Inc., 2014-2017 Dropwizard Team
*
* 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.dropwizard.metrics;
import org.junit.Test;
import io.dropwizard.metrics.SlidingWindowReservoir;
import static org.assertj.core.api.Assertions.assertThat;
public class SlidingWindowReservoirTest {
private final SlidingWindowReservoir reservoir = new SlidingWindowReservoir(3);
@Test
public void handlesSmallDataStreams() throws Exception {
reservoir.update(1);
reservoir.update(2);
assertThat(reservoir.getSnapshot().getValues())
.containsOnly(1, 2);
}
@Test
public void onlyKeepsTheMostRecentFromBigDataStreams() throws Exception {
reservoir.update(1);
reservoir.update(2);
reservoir.update(3);
reservoir.update(4);
assertThat(reservoir.getSnapshot().getValues())
.containsOnly(2, 3, 4);
}
}
| networknt/light-4j | metrics/src/test/java/io/dropwizard/metrics/SlidingWindowReservoirTest.java | Java | apache-2.0 | 1,479 |
/*
* Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.concurrent.atomicreference;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IAtomicReference;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.annotation.ParallelTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.io.Serializable;
import java.util.concurrent.ExecutionException;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelTest.class})
public class AtomicReferenceInstanceSharingTest extends HazelcastTestSupport {
private HazelcastInstance[] instances;
private HazelcastInstance local;
private HazelcastInstance remote;
@Before
public void setUp() {
instances = createHazelcastInstanceFactory(2).newInstances();
warmUpPartitions(instances);
local = instances[0];
remote = instances[1];
}
@Test
public void invocationToLocalMember() throws ExecutionException, InterruptedException {
String localKey = generateKeyOwnedBy(local);
IAtomicReference<DummyObject> ref = local.getAtomicReference(localKey);
DummyObject inserted = new DummyObject();
ref.set(inserted);
DummyObject get1 = ref.get();
DummyObject get2 = ref.get();
assertNotNull(get1);
assertNotNull(get2);
assertNotSame(get1, get2);
assertNotSame(get1, inserted);
assertNotSame(get2, inserted);
}
public static class DummyObject implements Serializable {
}
@Test
public void invocationToRemoteMember() throws ExecutionException, InterruptedException {
String localKey = generateKeyOwnedBy(remote);
IAtomicReference<DummyObject> ref = local.getAtomicReference(localKey);
DummyObject inserted = new DummyObject();
ref.set(inserted);
DummyObject get1 = ref.get();
DummyObject get2 = ref.get();
assertNotNull(get1);
assertNotNull(get2);
assertNotSame(get1, get2);
assertNotSame(get1, inserted);
assertNotSame(get2, inserted);
}
}
| juanavelez/hazelcast | hazelcast/src/test/java/com/hazelcast/concurrent/atomicreference/AtomicReferenceInstanceSharingTest.java | Java | apache-2.0 | 2,990 |
/*
* Copyright 2010-2016 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.directory.model.transform;
import java.util.Map;
import java.util.Map.Entry;
import java.math.*;
import java.nio.ByteBuffer;
import com.amazonaws.services.directory.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* CreateConditionalForwarderResult JSON Unmarshaller
*/
public class CreateConditionalForwarderResultJsonUnmarshaller implements
Unmarshaller<CreateConditionalForwarderResult, JsonUnmarshallerContext> {
public CreateConditionalForwarderResult unmarshall(
JsonUnmarshallerContext context) throws Exception {
CreateConditionalForwarderResult createConditionalForwarderResult = new CreateConditionalForwarderResult();
return createConditionalForwarderResult;
}
private static CreateConditionalForwarderResultJsonUnmarshaller instance;
public static CreateConditionalForwarderResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new CreateConditionalForwarderResultJsonUnmarshaller();
return instance;
}
}
| flofreud/aws-sdk-java | aws-java-sdk-directory/src/main/java/com/amazonaws/services/directory/model/transform/CreateConditionalForwarderResultJsonUnmarshaller.java | Java | apache-2.0 | 1,808 |
/*
* Copyright 2020 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.controller.actions;
import com.thoughtworks.go.config.validation.GoConfigValidity;
import com.thoughtworks.go.server.web.JsonView;
import com.thoughtworks.go.server.web.SimpleJsonView;
import com.thoughtworks.go.serverhealth.ServerHealthState;
import com.thoughtworks.go.util.GoConstants;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashMap;
import java.util.Map;
import static com.thoughtworks.go.util.GoConstants.ERROR_FOR_JSON;
import static com.thoughtworks.go.util.GoConstants.RESPONSE_CHARSET_JSON;
import static javax.servlet.http.HttpServletResponse.*;
public class JsonAction implements RestfulAction {
private final int status;
private final Object json;
public static JsonAction from(ServerHealthState serverHealthState) {
if (serverHealthState.isSuccess()) {
return jsonCreated(new LinkedHashMap());
}
Map<String, Object> jsonLog = new LinkedHashMap<>();
jsonLog.put(ERROR_FOR_JSON, serverHealthState.getDescription());
return new JsonAction(serverHealthState.getType().getHttpCode(), jsonLog);
}
public static JsonAction jsonCreated(Object json) {
return new JsonAction(SC_CREATED, json);
}
public static JsonAction jsonFound(Object json) {
return new JsonAction(SC_OK, json);
}
public static JsonAction jsonOK() {
return jsonOK(new LinkedHashMap());
}
public static JsonAction jsonNotAcceptable(Object json) {
return new JsonAction(SC_NOT_ACCEPTABLE, json);
}
public static JsonAction jsonForbidden() {
return new JsonAction(SC_FORBIDDEN, new LinkedHashMap());
}
public static JsonAction jsonForbidden(String message) {
Map<String, Object> map = new LinkedHashMap<>();
map.put(ERROR_FOR_JSON, message);
return new JsonAction(SC_FORBIDDEN, map);
}
public static JsonAction jsonForbidden(Exception e) {
return jsonForbidden(e.getMessage());
}
public static JsonAction jsonBadRequest(Object json) {
return new JsonAction(SC_BAD_REQUEST, json);
}
public static JsonAction jsonNotFound(Object json) {
return new JsonAction(SC_NOT_FOUND, json);
}
public static JsonAction jsonConflict(Object json) {
return new JsonAction(SC_CONFLICT, json);
}
public static JsonAction jsonByValidity(Object json, GoConfigValidity.InvalidGoConfig configValidity) {
return (configValidity.isType(GoConfigValidity.VT_CONFLICT) ||
configValidity.isType(GoConfigValidity.VT_MERGE_OPERATION_ERROR) ||
configValidity.isType(GoConfigValidity.VT_MERGE_POST_VALIDATION_ERROR) ||
configValidity.isType(GoConfigValidity.VT_MERGE_PRE_VALIDATION_ERROR)) ? jsonConflict(json) : jsonNotFound(json);
}
/**
* @deprecated replace with createView
*/
@Override
public ModelAndView respond(HttpServletResponse response) {
return new JsonModelAndView(response, json, status);
}
private JsonAction(int status, Object json) {
this.status = status;
this.json = json;
}
public ModelAndView createView() {
SimpleJsonView view = new SimpleJsonView(status, json);
return new ModelAndView(view, JsonView.asMap(json));
}
public static JsonAction jsonOK(Map jsonMap) {
return new JsonAction(SC_OK, jsonMap);
}
private class JsonModelAndView extends ModelAndView {
@Override
public String getViewName() {
return "jsonView";
}
public JsonModelAndView(HttpServletResponse response, Object json, int status) {
super(new JsonView(), JsonView.asMap(json));
// In IE, there's a problem with caching. We want to cache if we can.
// This will force the browser to clear the cache only for this page.
// If any other pages need to clear the cache, we might want to move this
// logic to an intercepter.
response.addHeader("Cache-Control", GoConstants.CACHE_CONTROL);
response.setStatus(status);
response.setContentType(RESPONSE_CHARSET_JSON);
}
}
}
| ketan/gocd | server/src/main/java/com/thoughtworks/go/server/controller/actions/JsonAction.java | Java | apache-2.0 | 4,901 |
/*
* Copyright 2000-2017 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.util.xml.impl;
import com.intellij.ide.highlighter.DomSupportEnabled;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectFileIndex;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Factory;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vfs.*;
import com.intellij.openapi.vfs.newvfs.NewVirtualFile;
import com.intellij.pom.PomManager;
import com.intellij.pom.PomModel;
import com.intellij.pom.PomModelAspect;
import com.intellij.pom.event.PomModelEvent;
import com.intellij.pom.event.PomModelListener;
import com.intellij.pom.xml.XmlAspect;
import com.intellij.pom.xml.XmlChangeSet;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory;
import com.intellij.psi.PsiManager;
import com.intellij.psi.impl.PsiManagerEx;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlElement;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.reference.SoftReference;
import com.intellij.semantic.SemKey;
import com.intellij.semantic.SemService;
import com.intellij.util.EventDispatcher;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.xml.*;
import com.intellij.util.xml.events.DomEvent;
import com.intellij.util.xml.reflect.AbstractDomChildrenDescription;
import com.intellij.util.xml.reflect.DomGenericInfo;
import net.sf.cglib.proxy.AdvancedProxy;
import net.sf.cglib.proxy.InvocationHandler;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.ref.WeakReference;
import java.lang.reflect.Type;
import java.util.*;
/**
* @author peter
*/
public final class DomManagerImpl extends DomManager {
private static final Key<Object> MOCK = Key.create("MockElement");
static final Key<WeakReference<DomFileElementImpl>> CACHED_FILE_ELEMENT = Key.create("CACHED_FILE_ELEMENT");
static final Key<DomFileDescription> MOCK_DESCRIPTION = Key.create("MockDescription");
static final SemKey<FileDescriptionCachedValueProvider> FILE_DESCRIPTION_KEY = SemKey.createKey("FILE_DESCRIPTION_KEY");
static final SemKey<DomInvocationHandler> DOM_HANDLER_KEY = SemKey.createKey("DOM_HANDLER_KEY");
static final SemKey<IndexedElementInvocationHandler> DOM_INDEXED_HANDLER_KEY = DOM_HANDLER_KEY.subKey("DOM_INDEXED_HANDLER_KEY");
static final SemKey<CollectionElementInvocationHandler> DOM_COLLECTION_HANDLER_KEY = DOM_HANDLER_KEY.subKey("DOM_COLLECTION_HANDLER_KEY");
static final SemKey<CollectionElementInvocationHandler> DOM_CUSTOM_HANDLER_KEY = DOM_HANDLER_KEY.subKey("DOM_CUSTOM_HANDLER_KEY");
static final SemKey<AttributeChildInvocationHandler> DOM_ATTRIBUTE_HANDLER_KEY = DOM_HANDLER_KEY.subKey("DOM_ATTRIBUTE_HANDLER_KEY");
private final EventDispatcher<DomEventListener> myListeners = EventDispatcher.create(DomEventListener.class);
private final Project myProject;
private final SemService mySemService;
private final DomApplicationComponent myApplicationComponent;
private boolean myChanging;
public DomManagerImpl(Project project) {
super(project);
myProject = project;
mySemService = SemService.getSemService(project);
myApplicationComponent = DomApplicationComponent.getInstance();
final PomModel pomModel = PomManager.getModel(project);
pomModel.addModelListener(new PomModelListener() {
@Override
public void modelChanged(PomModelEvent event) {
if (myChanging) return;
final XmlChangeSet changeSet = (XmlChangeSet)event.getChangeSet(pomModel.getModelAspect(XmlAspect.class));
if (changeSet != null) {
for (XmlFile file : changeSet.getChangedFiles()) {
DomFileElementImpl<DomElement> element = getCachedFileElement(file);
if (element != null) {
fireEvent(new DomEvent(element, false));
}
}
}
}
@Override
public boolean isAspectChangeInteresting(PomModelAspect aspect) {
return aspect instanceof XmlAspect;
}
}, project);
VirtualFileManager.getInstance().addVirtualFileListener(new VirtualFileListener() {
private final List<DomEvent> myDeletionEvents = new SmartList<>();
@Override
public void contentsChanged(@NotNull VirtualFileEvent event) {
if (!event.isFromSave()) {
fireEvents(calcDomChangeEvents(event.getFile()));
}
}
@Override
public void fileMoved(@NotNull VirtualFileMoveEvent event) {
fireEvents(calcDomChangeEvents(event.getFile()));
}
@Override
public void beforeFileDeletion(@NotNull final VirtualFileEvent event) {
myDeletionEvents.addAll(calcDomChangeEvents(event.getFile()));
}
@Override
public void fileDeleted(@NotNull VirtualFileEvent event) {
if (!myDeletionEvents.isEmpty()) {
fireEvents(myDeletionEvents);
myDeletionEvents.clear();
}
}
@Override
public void propertyChanged(@NotNull VirtualFilePropertyEvent event) {
final VirtualFile file = event.getFile();
if (!file.isDirectory() && VirtualFile.PROP_NAME.equals(event.getPropertyName())) {
fireEvents(calcDomChangeEvents(file));
}
}
}, myProject);
}
public long getPsiModificationCount() {
return PsiManager.getInstance(getProject()).getModificationTracker().getModificationCount();
}
public <T extends DomInvocationHandler> void cacheHandler(SemKey<T> key, XmlElement element, T handler) {
mySemService.setCachedSemElement(key, element, handler);
}
private PsiFile getCachedPsiFile(VirtualFile file) {
return PsiManagerEx.getInstanceEx(myProject).getFileManager().getCachedPsiFile(file);
}
private List<DomEvent> calcDomChangeEvents(final VirtualFile file) {
if (!(file instanceof NewVirtualFile) || myProject.isDisposed()) {
return Collections.emptyList();
}
final List<DomEvent> events = ContainerUtil.newArrayList();
VfsUtilCore.visitChildrenRecursively(file, new VirtualFileVisitor() {
@Override
public boolean visitFile(@NotNull VirtualFile file) {
if (myProject.isDisposed() || !ProjectFileIndex.SERVICE.getInstance(myProject).isInContent(file)) {
return false;
}
if (!file.isDirectory() && StdFileTypes.XML == file.getFileType()) {
final PsiFile psiFile = getCachedPsiFile(file);
if (psiFile != null && StdFileTypes.XML.equals(psiFile.getFileType()) && psiFile instanceof XmlFile) {
final DomFileElementImpl domElement = getCachedFileElement((XmlFile)psiFile);
if (domElement != null) {
events.add(new DomEvent(domElement, false));
}
}
}
return true;
}
@Nullable
@Override
public Iterable<VirtualFile> getChildrenIterable(@NotNull VirtualFile file) {
return ((NewVirtualFile)file).getCachedChildren();
}
});
return events;
}
@SuppressWarnings({"MethodOverridesStaticMethodOfSuperclass"})
public static DomManagerImpl getDomManager(Project project) {
return (DomManagerImpl)DomManager.getDomManager(project);
}
@Override
public void addDomEventListener(DomEventListener listener, Disposable parentDisposable) {
myListeners.addListener(listener, parentDisposable);
}
@Override
public final ConverterManager getConverterManager() {
return ServiceManager.getService(ConverterManager.class);
}
@Override
public final ModelMerger createModelMerger() {
return new ModelMergerImpl();
}
final void fireEvent(DomEvent event) {
if (mySemService.isInsideAtomicChange()) return;
incModificationCount();
myListeners.getMulticaster().eventOccured(event);
}
private void fireEvents(Collection<DomEvent> events) {
for (DomEvent event : events) {
fireEvent(event);
}
}
@Override
public final DomGenericInfo getGenericInfo(final Type type) {
return myApplicationComponent.getStaticGenericInfo(type);
}
@Nullable
public static DomInvocationHandler getDomInvocationHandler(DomElement proxy) {
if (proxy instanceof DomFileElement) {
return null;
}
if (proxy instanceof DomInvocationHandler) {
return (DomInvocationHandler)proxy;
}
final InvocationHandler handler = AdvancedProxy.getInvocationHandler(proxy);
if (handler instanceof StableInvocationHandler) {
//noinspection unchecked
final DomElement element = ((StableInvocationHandler<DomElement>)handler).getWrappedElement();
return element == null ? null : getDomInvocationHandler(element);
}
if (handler instanceof DomInvocationHandler) {
return (DomInvocationHandler)handler;
}
return null;
}
@NotNull
public static DomInvocationHandler getNotNullHandler(DomElement proxy) {
DomInvocationHandler handler = getDomInvocationHandler(proxy);
if (handler == null) {
throw new AssertionError("null handler for " + proxy);
}
return handler;
}
public static StableInvocationHandler getStableInvocationHandler(Object proxy) {
return (StableInvocationHandler)AdvancedProxy.getInvocationHandler(proxy);
}
public DomApplicationComponent getApplicationComponent() {
return myApplicationComponent;
}
@Override
public final Project getProject() {
return myProject;
}
@Override
@NotNull
public final <T extends DomElement> DomFileElementImpl<T> getFileElement(final XmlFile file, final Class<T> aClass, String rootTagName) {
//noinspection unchecked
if (file.getUserData(MOCK_DESCRIPTION) == null) {
file.putUserData(MOCK_DESCRIPTION, new MockDomFileDescription<>(aClass, rootTagName, file.getViewProvider().getVirtualFile()));
mySemService.clearCache();
}
final DomFileElementImpl<T> fileElement = getFileElement(file);
assert fileElement != null;
return fileElement;
}
@SuppressWarnings({"unchecked"})
@NotNull
final <T extends DomElement> FileDescriptionCachedValueProvider<T> getOrCreateCachedValueProvider(final XmlFile xmlFile) {
//noinspection ConstantConditions
return mySemService.getSemElement(FILE_DESCRIPTION_KEY, xmlFile);
}
public final Set<DomFileDescription> getFileDescriptions(String rootTagName) {
return myApplicationComponent.getFileDescriptions(rootTagName);
}
public final Set<DomFileDescription> getAcceptingOtherRootTagNameDescriptions() {
return myApplicationComponent.getAcceptingOtherRootTagNameDescriptions();
}
@NotNull
@NonNls
public final String getComponentName() {
return getClass().getName();
}
final void runChange(Runnable change) {
final boolean b = setChanging(true);
try {
change.run();
}
finally {
setChanging(b);
}
}
final boolean setChanging(final boolean changing) {
boolean oldChanging = myChanging;
if (changing) {
assert !oldChanging;
}
myChanging = changing;
return oldChanging;
}
@Override
@Nullable
public final <T extends DomElement> DomFileElementImpl<T> getFileElement(XmlFile file) {
if (file == null) return null;
if (!(file.getFileType() instanceof DomSupportEnabled)) return null;
final VirtualFile virtualFile = file.getVirtualFile();
if (virtualFile != null && virtualFile.isDirectory()) return null;
return this.<T>getOrCreateCachedValueProvider(file).getFileElement();
}
@Nullable
static <T extends DomElement> DomFileElementImpl<T> getCachedFileElement(@NotNull XmlFile file) {
//noinspection unchecked
return SoftReference.dereference(file.getUserData(CACHED_FILE_ELEMENT));
}
@Override
@Nullable
public final <T extends DomElement> DomFileElementImpl<T> getFileElement(XmlFile file, Class<T> domClass) {
final DomFileDescription description = getDomFileDescription(file);
if (description != null && myApplicationComponent.assignabilityCache.isAssignable(domClass, description.getRootElementClass())) {
return getFileElement(file);
}
return null;
}
@Override
@Nullable
public final DomElement getDomElement(final XmlTag element) {
if (myChanging) return null;
final DomInvocationHandler handler = getDomHandler(element);
return handler != null ? handler.getProxy() : null;
}
@Override
@Nullable
public GenericAttributeValue getDomElement(final XmlAttribute attribute) {
if (myChanging) return null;
final AttributeChildInvocationHandler handler = mySemService.getSemElement(DOM_ATTRIBUTE_HANDLER_KEY, attribute);
return handler == null ? null : (GenericAttributeValue)handler.getProxy();
}
@Nullable
public DomInvocationHandler getDomHandler(final XmlElement tag) {
if (tag == null) return null;
List<DomInvocationHandler> cached = mySemService.getCachedSemElements(DOM_HANDLER_KEY, tag);
if (cached != null && !cached.isEmpty()) {
return cached.get(0);
}
return mySemService.getSemElement(DOM_HANDLER_KEY, tag);
}
@Override
@Nullable
public AbstractDomChildrenDescription findChildrenDescription(@NotNull final XmlTag tag, @NotNull final DomElement parent) {
return findChildrenDescription(tag, getDomInvocationHandler(parent));
}
static AbstractDomChildrenDescription findChildrenDescription(final XmlTag tag, final DomInvocationHandler parent) {
final DomGenericInfoEx info = parent.getGenericInfo();
return info.findChildrenDescription(parent, tag.getLocalName(), tag.getNamespace(), false, tag.getName());
}
public final boolean isDomFile(@Nullable PsiFile file) {
return file instanceof XmlFile && getFileElement((XmlFile)file) != null;
}
@Nullable
public final DomFileDescription<?> getDomFileDescription(PsiElement element) {
if (element instanceof XmlElement) {
final PsiFile psiFile = element.getContainingFile();
if (psiFile instanceof XmlFile) {
return getDomFileDescription((XmlFile)psiFile);
}
}
return null;
}
@Override
public final <T extends DomElement> T createMockElement(final Class<T> aClass, final Module module, final boolean physical) {
final XmlFile file = (XmlFile)PsiFileFactory.getInstance(myProject).createFileFromText("a.xml", StdFileTypes.XML, "", (long)0, physical);
file.putUserData(MOCK_ELEMENT_MODULE, module);
file.putUserData(MOCK, new Object());
return getFileElement(file, aClass, "I_sincerely_hope_that_nobody_will_have_such_a_root_tag_name").getRootElement();
}
@Override
public final boolean isMockElement(DomElement element) {
return DomUtil.getFile(element).getUserData(MOCK) != null;
}
@Override
public final <T extends DomElement> T createStableValue(final Factory<T> provider) {
return createStableValue(provider, t -> t.isValid());
}
@Override
public final <T> T createStableValue(final Factory<T> provider, final Condition<T> validator) {
final T initial = provider.create();
assert initial != null;
final StableInvocationHandler handler = new StableInvocationHandler<>(initial, provider, validator);
final Set<Class> intf = new HashSet<>();
ContainerUtil.addAll(intf, initial.getClass().getInterfaces());
intf.add(StableElement.class);
//noinspection unchecked
return (T)AdvancedProxy.createProxy(initial.getClass().getSuperclass(), intf.toArray(new Class[intf.size()]),
handler);
}
public final <T extends DomElement> void registerFileDescription(final DomFileDescription<T> description, Disposable parentDisposable) {
registerFileDescription(description);
Disposer.register(parentDisposable, new Disposable() {
@Override
public void dispose() {
getFileDescriptions(description.getRootTagName()).remove(description);
getAcceptingOtherRootTagNameDescriptions().remove(description);
}
});
}
@Override
public final void registerFileDescription(final DomFileDescription description) {
mySemService.clearCache();
myApplicationComponent.registerFileDescription(description);
}
@Override
@NotNull
public final DomElement getResolvingScope(GenericDomValue element) {
final DomFileDescription<?> description = DomUtil.getFileElement(element).getFileDescription();
return description.getResolveScope(element);
}
@Override
@Nullable
public final DomElement getIdentityScope(DomElement element) {
final DomFileDescription description = DomUtil.getFileElement(element).getFileDescription();
return description.getIdentityScope(element);
}
@Override
public TypeChooserManager getTypeChooserManager() {
return myApplicationComponent.getTypeChooserManager();
}
public void performAtomicChange(@NotNull Runnable change) {
mySemService.performAtomicChange(change);
if (!mySemService.isInsideAtomicChange()) {
incModificationCount();
}
}
public SemService getSemService() {
return mySemService;
}
}
| ThiagoGarciaAlves/intellij-community | xml/dom-impl/src/com/intellij/util/xml/impl/DomManagerImpl.java | Java | apache-2.0 | 17,979 |
/*
* Copyright 2021 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.keycloak.quarkus.runtime.storage.database.liquibase;
import java.lang.reflect.Method;
import java.sql.Connection;
import javax.xml.parsers.SAXParserFactory;
import org.jboss.logging.Logger;
import org.keycloak.Config;
import org.keycloak.connections.jpa.updater.liquibase.conn.LiquibaseConnectionProvider;
import org.keycloak.connections.jpa.updater.liquibase.conn.LiquibaseConnectionProviderFactory;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;
import liquibase.Liquibase;
import liquibase.database.Database;
import liquibase.database.DatabaseFactory;
import liquibase.database.jvm.JdbcConnection;
import liquibase.exception.LiquibaseException;
import liquibase.parser.ChangeLogParser;
import liquibase.parser.ChangeLogParserFactory;
import liquibase.parser.core.xml.XMLChangeLogSAXParser;
import liquibase.resource.ClassLoaderResourceAccessor;
import liquibase.resource.ResourceAccessor;
public class QuarkusLiquibaseConnectionProvider implements LiquibaseConnectionProviderFactory, LiquibaseConnectionProvider {
private static final Logger logger = Logger.getLogger(QuarkusLiquibaseConnectionProvider.class);
private volatile boolean initialized = false;
private ClassLoaderResourceAccessor resourceAccessor;
@Override
public LiquibaseConnectionProvider create(KeycloakSession session) {
if (!initialized) {
synchronized (this) {
if (!initialized) {
baseLiquibaseInitialization(session);
initialized = true;
}
}
}
return this;
}
protected void baseLiquibaseInitialization(KeycloakSession session) {
resourceAccessor = new ClassLoaderResourceAccessor(getClass().getClassLoader());
// disables XML validation
for (ChangeLogParser parser : ChangeLogParserFactory.getInstance().getParsers()) {
if (parser instanceof XMLChangeLogSAXParser) {
Method getSaxParserFactory = null;
try {
getSaxParserFactory = XMLChangeLogSAXParser.class.getDeclaredMethod("getSaxParserFactory");
getSaxParserFactory.setAccessible(true);
SAXParserFactory saxParserFactory = (SAXParserFactory) getSaxParserFactory.invoke(parser);
saxParserFactory.setValidating(false);
saxParserFactory.setSchema(null);
} catch (Exception e) {
logger.warnf("Failed to disable liquibase XML validations");
} finally {
if (getSaxParserFactory != null) {
getSaxParserFactory.setAccessible(false);
}
}
}
}
}
@Override
public void init(Config.Scope config) {
}
@Override
public void postInit(KeycloakSessionFactory factory) {
}
@Override
public void close() {
}
@Override
public String getId() {
return "quarkus";
}
@Override
public Liquibase getLiquibase(Connection connection, String defaultSchema) throws LiquibaseException {
Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
if (defaultSchema != null) {
database.setDefaultSchemaName(defaultSchema);
}
String changelog = QuarkusJpaUpdaterProvider.CHANGELOG;
logger.debugf("Using changelog file %s and changelogTableName %s", changelog, database.getDatabaseChangeLogTableName());
return new Liquibase(changelog, resourceAccessor, database);
}
@Override
public Liquibase getLiquibaseForCustomUpdate(Connection connection, String defaultSchema, String changelogLocation, ClassLoader classloader, String changelogTableName) throws LiquibaseException {
Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
if (defaultSchema != null) {
database.setDefaultSchemaName(defaultSchema);
}
ResourceAccessor resourceAccessor = new ClassLoaderResourceAccessor(classloader);
database.setDatabaseChangeLogTableName(changelogTableName);
logger.debugf("Using changelog file %s and changelogTableName %s", changelogLocation, database.getDatabaseChangeLogTableName());
return new Liquibase(changelogLocation, resourceAccessor, database);
}
@Override
public int order() {
return 100;
}
}
| stianst/keycloak | quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/storage/database/liquibase/QuarkusLiquibaseConnectionProvider.java | Java | apache-2.0 | 5,267 |
package org.apereo.cas.web.flow.actions;
import org.apereo.cas.authentication.CoreAuthenticationTestUtils;
import org.apereo.cas.authentication.principal.ResponseBuilderLocator;
import org.apereo.cas.authentication.principal.WebApplicationService;
import org.apereo.cas.authentication.principal.WebApplicationServiceResponseBuilder;
import org.apereo.cas.config.CasCoreServicesConfiguration;
import org.apereo.cas.config.CasCoreUtilConfiguration;
import org.apereo.cas.services.ServicesManager;
import org.apereo.cas.web.flow.CasWebflowConstants;
import org.apereo.cas.web.support.WebUtils;
import lombok.val;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.context.junit4.rules.SpringClassRule;
import org.springframework.test.context.junit4.rules.SpringMethodRule;
import org.springframework.webflow.context.servlet.ServletExternalContext;
import org.springframework.webflow.test.MockRequestContext;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
/**
* This is {@link RedirectToServiceActionTests}.
*
* @author Misagh Moayyed
* @since 5.3.0
*/
@SpringBootTest(classes = {
RefreshAutoConfiguration.class,
CasCoreServicesConfiguration.class,
CasCoreUtilConfiguration.class
})
public class RedirectToServiceActionTests {
@ClassRule
public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule();
@Rule
public final SpringMethodRule springMethodRule = new SpringMethodRule();
@Autowired
@Qualifier("servicesManager")
private ServicesManager servicesManager;
@Test
public void verifyAction() throws Exception {
val context = new MockRequestContext();
val request = new MockHttpServletRequest();
context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, new MockHttpServletResponse()));
WebUtils.putAuthentication(CoreAuthenticationTestUtils.getAuthentication(), context);
WebUtils.putService(context, CoreAuthenticationTestUtils.getWebApplicationService());
val locator = mock(ResponseBuilderLocator.class);
when(locator.locate(any(WebApplicationService.class))).thenReturn(new WebApplicationServiceResponseBuilder(this.servicesManager));
val redirectToServiceAction = new RedirectToServiceAction(locator);
val event = redirectToServiceAction.execute(context);
assertEquals(CasWebflowConstants.TRANSITION_ID_REDIRECT, event.getId());
}
}
| robertoschwald/cas | core/cas-server-core-webflow/src/test/java/org/apereo/cas/web/flow/actions/RedirectToServiceActionTests.java | Java | apache-2.0 | 2,947 |
package org.camunda.bpm.engine.rest.wink;
import org.camunda.bpm.engine.rest.AbstractMessageRestServiceTest;
import org.camunda.bpm.engine.rest.util.WinkTomcatServerBootstrap;
import org.junit.AfterClass;
import org.junit.BeforeClass;
public class MessageRestServiceTest extends AbstractMessageRestServiceTest {
protected static WinkTomcatServerBootstrap serverBootstrap;
@BeforeClass
public static void setUpEmbeddedRuntime() {
serverBootstrap = new WinkTomcatServerBootstrap();
serverBootstrap.start();
}
@AfterClass
public static void tearDownEmbeddedRuntime() {
serverBootstrap.stop();
}
}
| tkaefer/camunda-bpm-platform | engine-rest/src/test/java/org/camunda/bpm/engine/rest/wink/MessageRestServiceTest.java | Java | apache-2.0 | 629 |
/*
* JBoss, Home of Professional Open Source
* Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of 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.as.quickstart.deltaspike.partialbean;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import javax.enterprise.context.ApplicationScoped;
/**
* This class implements a dynamic DeltaSpike Partial Bean. It is bound to
* one or more abstract classes or interfaces via the Binding Annotation
* (@ExamplePartialBeanBinding below).
*
* All abstract, unimplemented methods from those beans will be implemented
* via the invoke method.
*
*/
@ExamplePartialBeanBinding
@ApplicationScoped
public class ExamplePartialBeanImplementation implements InvocationHandler {
/**
* In our example, this method will be invoked when the "sayHello" method is called.
*
* @param proxy The object upon which the method is being invoked.
* @param method The method being invoked (sayHello in this QuickStart)
* @param args The arguments being passed in to the invoked method
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return "Hello " + args[0];
}
}
| jboss-developer/jboss-wfk-quickstarts | deltaspike-partialbean-basic/src/main/java/org/jboss/as/quickstart/deltaspike/partialbean/ExamplePartialBeanImplementation.java | Java | apache-2.0 | 1,876 |
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc. and/or its affiliates, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of 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.hibernate.validator.cfg.defs;
import javax.validation.constraints.Pattern;
import org.hibernate.validator.cfg.ConstraintDef;
import org.hibernate.validator.constraints.Email;
/**
* @author Hardy Ferentschik
*/
public class EmailDef extends ConstraintDef<EmailDef, Email> {
public EmailDef() {
super( Email.class );
}
public EmailDef regexp(String regexp) {
addParameter( "regexp", regexp );
return this;
}
public EmailDef flags(Pattern.Flag... flags) {
addParameter( "flags", flags );
return this;
}
}
| jmartisk/hibernate-validator | engine/src/main/java/org/hibernate/validator/cfg/defs/EmailDef.java | Java | apache-2.0 | 1,337 |
/*
* Copyright (c) 2010. All rights reserved.
*/
package ro.isdc.wro.model.resource.processor;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.net.URL;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import ro.isdc.wro.config.Context;
import ro.isdc.wro.model.resource.ResourceType;
import ro.isdc.wro.model.resource.processor.impl.css.ConformColorsCssProcessor;
import ro.isdc.wro.util.WroTestUtils;
/**
* TestConformColorsCssProcessor.
*
* @author Alex Objelean
* @created Created on Aug 15, 2010
*/
public class TestConformColorsCssProcessor {
private ResourcePreProcessor processor;
@BeforeClass
public static void onBeforeClass() {
assertEquals(0, Context.countActive());
}
@AfterClass
public static void onAfterClass() {
assertEquals(0, Context.countActive());
}
@Before
public void setUp() {
processor = new ConformColorsCssProcessor();
}
@Test
public void testFromFolder()
throws Exception {
final URL url = getClass().getResource("conformColors");
final File testFolder = new File(url.getFile(), "test");
final File expectedFolder = new File(url.getFile(), "expected");
WroTestUtils.compareFromDifferentFoldersByExtension(testFolder, expectedFolder, "css", processor);
}
@Test
public void shouldSupportCorrectResourceTypes() {
WroTestUtils.assertProcessorSupportResourceTypes(processor, ResourceType.CSS);
}
}
| UAK-35/wro4j | wro4j-core/src/test/java/ro/isdc/wro/model/resource/processor/TestConformColorsCssProcessor.java | Java | apache-2.0 | 1,512 |
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT 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.wso2.carbon.mss.examples.petstore.util.fe.view;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
/**
* Bean classes used for JSF model.
*/
@ManagedBean
@SessionScoped
public class NavigationBean implements Serializable {
private static final long serialVersionUID = -8628674465932953415L;
public String redirectToStoreWelcome() {
return "pet/list.xhtml?faces-redirect=true";
}
public String redirectToAdminWelcome() {
return "pet/index.xhtml?faces-redirect=true";
}
public String toLogin() {
return "/login.xhtml";
}
public String backtoList() {
return "list";
}
}
| dakshika/product-mss | samples/petstore/frontend-util/src/main/java/org/wso2/carbon/mss/examples/petstore/util/fe/view/NavigationBean.java | Java | apache-2.0 | 1,401 |
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT 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.wso2.carbon.identity.oauth2.validators;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationRequestDTO;
import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO;
import static org.testng.Assert.assertEquals;
public class OAuth2TokenValidationMessageContextTest {
private OAuth2TokenValidationMessageContext oAuth2TokenValidationMessageContext;
private OAuth2TokenValidationRequestDTO requestDTO;
private OAuth2TokenValidationResponseDTO responseDTO;
@BeforeMethod
public void setUp() throws Exception {
requestDTO = new OAuth2TokenValidationRequestDTO();
responseDTO = new OAuth2TokenValidationResponseDTO();
oAuth2TokenValidationMessageContext = new OAuth2TokenValidationMessageContext(requestDTO, responseDTO);
}
@Test
public void testGetRequestDTO() throws Exception {
assertEquals(oAuth2TokenValidationMessageContext.getRequestDTO(), requestDTO);
}
@Test
public void testGetResponseDTO() throws Exception {
assertEquals(oAuth2TokenValidationMessageContext.getResponseDTO(), responseDTO);
}
@Test
public void testAddProperty() throws Exception {
oAuth2TokenValidationMessageContext.addProperty("testProperty", "testValue");
assertEquals(oAuth2TokenValidationMessageContext.getProperty("testProperty"), "testValue");
}
@Test
public void testGetProperty() throws Exception {
oAuth2TokenValidationMessageContext.addProperty("testProperty", "testValue");
assertEquals(oAuth2TokenValidationMessageContext.getProperty("testProperty"), "testValue");
}
}
| darshanasbg/identity-inbound-auth-oauth | components/org.wso2.carbon.identity.oauth/src/test/java/org/wso2/carbon/identity/oauth2/validators/OAuth2TokenValidationMessageContextTest.java | Java | apache-2.0 | 2,398 |
/*
Copyright 2011-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.security.zynamics.binnavi.disassembly;
import com.google.security.zynamics.zylib.gui.zygraph.edges.IViewEdgeListener;
/**
* Interface for objects that want to be notified about changes in edges.
*/
public interface INaviEdgeListener extends IViewEdgeListener {
/**
* Invoked after the global comment of an edge changed.
*
* @param naviEdge The edge whose global comment changed.
*/
void changedGlobalComment(CNaviViewEdge naviEdge);
/**
* Invoked after the local comment of an edge changed.
*
* @param naviEdge The edge whose local comment changed.
*/
void changedLocalComment(CNaviViewEdge naviEdge);
}
| chubbymaggie/binnavi | src/main/java/com/google/security/zynamics/binnavi/disassembly/INaviEdgeListener.java | Java | apache-2.0 | 1,248 |
package com.bazaarvoice.emodb.common.dropwizard.leader;
import com.bazaarvoice.curator.recipes.leader.LeaderService;
import com.bazaarvoice.emodb.common.dropwizard.task.TaskRegistry;
import com.bazaarvoice.emodb.common.zookeeper.leader.PartitionedLeaderService;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.Service;
import com.google.inject.Inject;
import io.dropwizard.servlets.tasks.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.PrintWriter;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentMap;
/**
* Shows the current status of leadership processes managed by {@link LeaderService}. Allows terminating
* individual leadership processes, but such that they can be restarted only by restarting the entire server.
*/
public class LeaderServiceTask extends Task {
private static final Logger _log = LoggerFactory.getLogger(LeaderServiceTask.class);
private final ConcurrentMap<String, LeaderService> _selectorMap = Maps.newConcurrentMap();
@Inject
public LeaderServiceTask(TaskRegistry tasks) {
super("leader");
tasks.addTask(this);
}
public void register(final String name, final LeaderService leaderService) {
_selectorMap.put(name, leaderService);
// Unregister automatically to avoid memory leaks.
leaderService.addListener(new AbstractServiceListener() {
@Override
public void terminated(Service.State from) {
unregister(name, leaderService);
}
@Override
public void failed(Service.State from, Throwable failure) {
unregister(name, leaderService);
}
}, MoreExecutors.sameThreadExecutor());
}
public void register(final String name, final PartitionedLeaderService partitionedLeaderService) {
int partition = 0;
for (LeaderService leaderService : partitionedLeaderService.getPartitionLeaderServices()) {
register(String.format("%s-%d", name, partition++), leaderService);
}
}
public void unregister(String name, LeaderService leaderService) {
_selectorMap.remove(name, leaderService);
}
@Override
public void execute(ImmutableMultimap<String, String> parameters, PrintWriter out) throws Exception {
// The 'release' argument tells a server to give up leadership and let a new leader be elected, possibly
// re-electing the current server. This is useful for rebalancing leader-controlled activities.
for (String name : parameters.get("release")) {
LeaderService leaderService = _selectorMap.get(name);
if (leaderService == null) {
out.printf("Unknown leader process: %s%n", name);
continue;
}
Service actualService = leaderService.getCurrentDelegateService().orNull();
if (actualService == null || !actualService.isRunning()) {
out.printf("Process is not currently elected leader: %s%n", name);
continue;
}
_log.warn("Temporarily releasing leadership for process: {}", name);
out.printf("Temporarily releasing leadership for process: %s, cluster will elect a new leader.%n", name);
actualService.stopAndWait();
}
// The 'terminate' argument tells a server to give up leadership permanently (or until the server restarts).
for (String name : parameters.get("terminate")) {
LeaderService leaderService = _selectorMap.get(name);
if (leaderService == null) {
out.printf("Unknown leader process: %s%n", name);
continue;
}
_log.warn("Terminating leader process for: {}", name);
out.printf("Terminating leader process for: %s. Restart the server to restart the leader process.%n", name);
leaderService.stopAndWait();
}
// Print current status.
for (Map.Entry<String, LeaderService> entry : new TreeMap<>(_selectorMap).entrySet()) {
String name = entry.getKey();
LeaderService leaderService = entry.getValue();
out.printf("%s: %s (leader=%s)%n", name,
describeState(leaderService.state(), leaderService.hasLeadership()),
getLeaderId(leaderService));
}
}
private String describeState(Service.State state, boolean hasLeadership) {
if (state == Service.State.RUNNING && !hasLeadership) {
return "waiting to win leadership election";
} else {
return state.name();
}
}
private String getLeaderId(LeaderService leaderService) {
try {
return leaderService.getLeader().getId();
} catch (Exception e) {
return "<unknown>";
}
}
}
| billkalter/emodb | common/dropwizard/src/main/java/com/bazaarvoice/emodb/common/dropwizard/leader/LeaderServiceTask.java | Java | apache-2.0 | 5,047 |
package org.elasticsearch.action.get;
import com.bazaarvoice.elasticsearch.client.core.spi.RestExecutor;
import com.bazaarvoice.elasticsearch.client.core.spi.RestResponse;
import com.bazaarvoice.elasticsearch.client.core.util.UrlBuilder;
import org.elasticsearch.action.AbstractRestClientAction;
import org.elasticsearch.common.base.Function;
import org.elasticsearch.common.util.concurrent.Futures;
import org.elasticsearch.common.util.concurrent.ListenableFuture;
import static com.bazaarvoice.elasticsearch.client.core.util.StringFunctions.booleanToString;
import static com.bazaarvoice.elasticsearch.client.core.util.StringFunctions.commaDelimitedToString;
import static com.bazaarvoice.elasticsearch.client.core.util.UrlBuilder.urlEncode;
import static com.bazaarvoice.elasticsearch.client.core.util.Validation.notNull;
import static org.elasticsearch.common.base.Optional.fromNullable;
/**
* The inverse of {@link org.elasticsearch.rest.action.get.RestGetAction}
*
* @param <ResponseType>
*/
public class GetRest<ResponseType> extends AbstractRestClientAction<GetRequest, ResponseType> {
public GetRest(final String protocol, final String host, final int port, final RestExecutor executor, final Function<RestResponse, ResponseType> responseTransform) {
super(protocol, host, port, executor, responseTransform);
}
@Override public ListenableFuture<ResponseType> act(GetRequest request) {
UrlBuilder url = UrlBuilder.create()
.protocol(protocol).host(host).port(port)
.path(urlEncode(notNull(request.index())))
.seg(urlEncode(notNull(request.type())))
.seg(urlEncode(notNull(request.id())))
.paramIfPresent("refresh", fromNullable(request.refresh()).transform(booleanToString))
.paramIfPresent("routing", fromNullable(request.routing()))
// note parent(string) seems just to set the routing, so we don't need to provide it here
.paramIfPresent("preference", fromNullable(request.preference()))
.paramIfPresent("realtime", fromNullable(request.realtime()).transform(booleanToString))
.paramIfPresent("fields", fromNullable(request.fields()).transform(commaDelimitedToString));
return Futures.transform(executor.get(url.url()), responseTransform);
}
}
| bazaarvoice/es-client-java | es-rest-client-1.3/core/src/main/java/org/elasticsearch/action/get/GetRest.java | Java | apache-2.0 | 2,328 |
/*
* 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.pdfbox.tools;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
/**
* This will take a text file and ouput a pdf with that text.
*
* @author Ben Litchfield
*/
public class TextToPDF
{
/**
* The scaling factor for font units to PDF units
*/
private static final int FONTSCALE = 1000;
/**
* The default font
*/
private static final PDType1Font DEFAULT_FONT = PDType1Font.HELVETICA;
/**
* The default font size
*/
private static final int DEFAULT_FONT_SIZE = 10;
/**
* The line height as a factor of the font size
*/
private static final float LINE_HEIGHT_FACTOR = 1.05f;
private int fontSize = DEFAULT_FONT_SIZE;
private PDFont font = DEFAULT_FONT;
private static final Map<String, PDType1Font> STANDARD_14 = new HashMap<String, PDType1Font>();
static
{
STANDARD_14.put(PDType1Font.TIMES_ROMAN.getBaseFont(), PDType1Font.TIMES_ROMAN);
STANDARD_14.put(PDType1Font.TIMES_BOLD.getBaseFont(), PDType1Font.TIMES_BOLD);
STANDARD_14.put(PDType1Font.TIMES_ITALIC.getBaseFont(), PDType1Font.TIMES_ITALIC);
STANDARD_14.put(PDType1Font.TIMES_BOLD_ITALIC.getBaseFont(), PDType1Font.TIMES_BOLD_ITALIC);
STANDARD_14.put(PDType1Font.HELVETICA.getBaseFont(), PDType1Font.HELVETICA);
STANDARD_14.put(PDType1Font.HELVETICA_BOLD.getBaseFont(), PDType1Font.HELVETICA_BOLD);
STANDARD_14.put(PDType1Font.HELVETICA_OBLIQUE.getBaseFont(), PDType1Font.HELVETICA_OBLIQUE);
STANDARD_14.put(PDType1Font.HELVETICA_BOLD_OBLIQUE.getBaseFont(), PDType1Font.HELVETICA_BOLD_OBLIQUE);
STANDARD_14.put(PDType1Font.COURIER.getBaseFont(), PDType1Font.COURIER);
STANDARD_14.put(PDType1Font.COURIER_BOLD.getBaseFont(), PDType1Font.COURIER_BOLD);
STANDARD_14.put(PDType1Font.COURIER_OBLIQUE.getBaseFont(), PDType1Font.COURIER_OBLIQUE);
STANDARD_14.put(PDType1Font.COURIER_BOLD_OBLIQUE.getBaseFont(), PDType1Font.COURIER_BOLD_OBLIQUE);
STANDARD_14.put(PDType1Font.SYMBOL.getBaseFont(), PDType1Font.SYMBOL);
STANDARD_14.put(PDType1Font.ZAPF_DINGBATS.getBaseFont(), PDType1Font.ZAPF_DINGBATS);
}
/**
* Create a PDF document with some text.
*
* @param text The stream of text data.
*
* @return The document with the text in it.
*
* @throws IOException If there is an error writing the data.
*/
public PDDocument createPDFFromText( Reader text ) throws IOException
{
PDDocument doc = new PDDocument();
createPDFFromText(doc, text);
return doc;
}
/**
* Create a PDF document with some text.
*
* @param text The stream of text data.
*
* @throws IOException If there is an error writing the data.
*/
public void createPDFFromText( PDDocument doc, Reader text ) throws IOException
{
try
{
final int margin = 40;
float height = font.getBoundingBox().getHeight() / FONTSCALE;
//calculate font height and increase by a factor.
height = height*fontSize*LINE_HEIGHT_FACTOR;
BufferedReader data = new BufferedReader( text );
String nextLine = null;
PDPage page = new PDPage();
PDPageContentStream contentStream = null;
float y = -1;
float maxStringLength = page.getMediaBox().getWidth() - 2*margin;
// There is a special case of creating a PDF document from an empty string.
boolean textIsEmpty = true;
while( (nextLine = data.readLine()) != null )
{
// The input text is nonEmpty. New pages will be created and added
// to the PDF document as they are needed, depending on the length of
// the text.
textIsEmpty = false;
String[] lineWords = nextLine.trim().split( " " );
int lineIndex = 0;
while( lineIndex < lineWords.length )
{
StringBuilder nextLineToDraw = new StringBuilder();
float lengthIfUsingNextWord = 0;
do
{
nextLineToDraw.append( lineWords[lineIndex] );
nextLineToDraw.append( " " );
lineIndex++;
if( lineIndex < lineWords.length )
{
String lineWithNextWord = nextLineToDraw.toString() + lineWords[lineIndex];
lengthIfUsingNextWord =
(font.getStringWidth( lineWithNextWord )/FONTSCALE) * fontSize;
}
}
while( lineIndex < lineWords.length &&
lengthIfUsingNextWord < maxStringLength );
if( y < margin )
{
// We have crossed the end-of-page boundary and need to extend the
// document by another page.
page = new PDPage();
doc.addPage( page );
if( contentStream != null )
{
contentStream.endText();
contentStream.close();
}
contentStream = new PDPageContentStream(doc, page);
contentStream.setFont( font, fontSize );
contentStream.beginText();
y = page.getMediaBox().getHeight() - margin + height;
contentStream.newLineAtOffset(
margin, y);
}
if( contentStream == null )
{
throw new IOException( "Error:Expected non-null content stream." );
}
contentStream.newLineAtOffset(0, -height);
y -= height;
contentStream.showText(nextLineToDraw.toString());
}
}
// If the input text was the empty string, then the above while loop will have short-circuited
// and we will not have added any PDPages to the document.
// So in order to make the resultant PDF document readable by Adobe Reader etc, we'll add an empty page.
if (textIsEmpty)
{
doc.addPage(page);
}
if( contentStream != null )
{
contentStream.endText();
contentStream.close();
}
}
catch( IOException io )
{
if( doc != null )
{
doc.close();
}
throw io;
}
}
/**
* This will create a PDF document with some text in it.
* <br />
* see usage() for commandline
*
* @param args Command line arguments.
*
* @throws IOException If there is an error with the PDF.
*/
public static void main(String[] args) throws IOException
{
// suppress the Dock icon on OS X
System.setProperty("apple.awt.UIElement", "true");
TextToPDF app = new TextToPDF();
PDDocument doc = new PDDocument();
try
{
if( args.length < 2 )
{
app.usage();
}
else
{
for( int i=0; i<args.length-2; i++ )
{
if( args[i].equals( "-standardFont" ))
{
i++;
app.setFont( getStandardFont( args[i] ));
}
else if( args[i].equals( "-ttf" ))
{
i++;
PDFont font = PDType0Font.load( doc, new File( args[i]) );
app.setFont( font );
}
else if( args[i].equals( "-fontSize" ))
{
i++;
app.setFontSize( Integer.parseInt( args[i] ) );
}
else
{
throw new IOException( "Unknown argument:" + args[i] );
}
}
app.createPDFFromText( doc, new FileReader( args[args.length-1] ) );
doc.save( args[args.length-2] );
}
}
finally
{
doc.close();
}
}
/**
* This will print out a message telling how to use this example.
*/
private void usage()
{
String[] std14 = getStandard14Names();
StringBuilder message = new StringBuilder();
message.append("Usage: jar -jar pdfbox-app-x.y.z.jar TextToPDF [options] <outputfile> <textfile>\n");
message.append("\nOptions:\n");
message.append(" -standardFont <name> : " + DEFAULT_FONT.getBaseFont() + " (default)\n");
for (String std14String : std14)
{
message.append(" " + std14String + "\n");
}
message.append(" -ttf <ttf file> : The TTF font to use.\n");
message.append(" -fontSize <fontSize> : default: " + DEFAULT_FONT_SIZE );
System.err.println(message.toString());
System.exit(1);
}
/**
* A convenience method to get one of the standard 14 font from name.
*
* @param name The name of the font to get.
*
* @return The font that matches the name or null if it does not exist.
*/
private static PDType1Font getStandardFont(String name)
{
return STANDARD_14.get(name);
}
/**
* This will get the names of the standard 14 fonts.
*
* @return An array of the names of the standard 14 fonts.
*/
private static String[] getStandard14Names()
{
return STANDARD_14.keySet().toArray(new String[14]);
}
/**
* @return Returns the font.
*/
public PDFont getFont()
{
return font;
}
/**
* @param aFont The font to set.
*/
public void setFont(PDFont aFont)
{
this.font = aFont;
}
/**
* @return Returns the fontSize.
*/
public int getFontSize()
{
return fontSize;
}
/**
* @param aFontSize The fontSize to set.
*/
public void setFontSize(int aFontSize)
{
this.fontSize = aFontSize;
}
}
| benmccann/pdfbox | tools/src/main/java/org/apache/pdfbox/tools/TextToPDF.java | Java | apache-2.0 | 11,926 |
/*
* Copyright 2012 International Business Machines Corp.
*
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package javax.batch.api.chunk.listener;
import java.util.List;
/**
* The AbstractItemWriteListener provides default
* implementations of less commonly implemented methods.
*/
public abstract class AbstractItemWriteListener implements
ItemWriteListener {
/**
* Override this method if the ItemWriteListener
* will do something before the items are written.
* The default implementation does nothing.
*
* @param items specifies the items about to be
* written.
* @throws Exception (or subclass) if an error occurs.
*/
@Override
public void beforeWrite(List<Object> items) throws Exception {}
/**
* Override this method if the ItemWriteListener
* will do something after the items are written.
* The default implementation does nothing.
*
* @param items specifies the items about to be
* written.
* @throws Exception (or subclass) if an error occurs.
*/
@Override
public void afterWrite(List<Object> items) throws Exception {}
/**
* Override this method if the ItemWriteListener
* will do something when the ItemWriter writeItems
* method throws an exception.
* The default implementation does nothing.
*
* @param items specifies the items about to be
* written.
* @param ex specifies the exception thrown by the item
* writer.
* @throws Exception (or subclass) if an error occurs.
*/
@Override
public void onWriteError(List<Object> items, Exception ex) throws Exception {}
}
| sidgoyal/standards.jsr352.jbatch | javax.batch/src/main/java/javax/batch/api/chunk/listener/AbstractItemWriteListener.java | Java | apache-2.0 | 2,264 |
/*
* #%L
* SparkCommerce Framework Web
* %%
* Copyright (C) 2009 - 2013 Spark Commerce
* %%
* 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.sparkcommerce.core.payment.service;
import org.sparkcommerce.common.payment.PaymentGatewayType;
import org.springframework.stereotype.Service;
/**
* In order to use load this demo service, you will need to component scan
* the package "com.mycompany.sample".
*
* This should NOT be used in production, and is meant solely for demonstration
* purposes only.
*
* @author Elbert Bautista (elbertbautista)
*/
@Service("blNullPaymentGatewayConfiguration")
public class NullPaymentGatewayConfigurationImpl implements NullPaymentGatewayConfiguration {
protected int failureReportingThreshold = 1;
protected boolean performAuthorizeAndCapture = true;
@Override
public String getTransparentRedirectUrl() {
return "/null-checkout/process";
}
@Override
public String getTransparentRedirectReturnUrl() {
return "/null-checkout/return";
}
@Override
public boolean isPerformAuthorizeAndCapture() {
return true;
}
@Override
public void setPerformAuthorizeAndCapture(boolean performAuthorizeAndCapture) {
this.performAuthorizeAndCapture = performAuthorizeAndCapture;
}
@Override
public int getFailureReportingThreshold() {
return failureReportingThreshold;
}
@Override
public void setFailureReportingThreshold(int failureReportingThreshold) {
this.failureReportingThreshold = failureReportingThreshold;
}
@Override
public boolean handlesAuthorize() {
return true;
}
@Override
public boolean handlesCapture() {
return false;
}
@Override
public boolean handlesAuthorizeAndCapture() {
return true;
}
@Override
public boolean handlesReverseAuthorize() {
return false;
}
@Override
public boolean handlesVoid() {
return false;
}
@Override
public boolean handlesRefund() {
return false;
}
@Override
public boolean handlesPartialCapture() {
return false;
}
@Override
public boolean handlesMultipleShipment() {
return false;
}
@Override
public boolean handlesRecurringPayment() {
return false;
}
@Override
public boolean handlesSavedCustomerPayment() {
return false;
}
@Override
public boolean handlesMultiplePayments() {
return false;
}
@Override
public PaymentGatewayType getGatewayType() {
return NullPaymentGatewayType.NULL_GATEWAY;
}
}
| akdasari/SparkIntegration | src/test/java/org/sparkcommerce/core/payment/service/NullPaymentGatewayConfigurationImpl.java | Java | apache-2.0 | 3,194 |
package org.zstack.sdk.zwatch.thirdparty.api;
public class QueryThirdpartyAlertResult {
public java.util.List inventories;
public void setInventories(java.util.List inventories) {
this.inventories = inventories;
}
public java.util.List getInventories() {
return this.inventories;
}
public java.lang.Long total;
public void setTotal(java.lang.Long total) {
this.total = total;
}
public java.lang.Long getTotal() {
return this.total;
}
}
| zstackorg/zstack | sdk/src/main/java/org/zstack/sdk/zwatch/thirdparty/api/QueryThirdpartyAlertResult.java | Java | apache-2.0 | 513 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.discovery.zen.publish;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.Version;
import org.elasticsearch.cluster.ClusterChangedEvent;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.ClusterStateListener;
import org.elasticsearch.cluster.Diff;
import org.elasticsearch.cluster.block.ClusterBlocks;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Randomness;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.discovery.Discovery;
import org.elasticsearch.discovery.DiscoverySettings;
import org.elasticsearch.discovery.zen.DiscoveryNodesProvider;
import org.elasticsearch.env.NodeEnvironment;
import org.elasticsearch.node.Node;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.junit.annotations.TestLogging;
import org.elasticsearch.test.transport.MockTransportService;
import org.elasticsearch.threadpool.TestThreadPool;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.BytesTransportRequest;
import org.elasticsearch.transport.TransportChannel;
import org.elasticsearch.transport.TransportConnectionListener;
import org.elasticsearch.transport.TransportResponse;
import org.elasticsearch.transport.TransportResponseOptions;
import org.elasticsearch.transport.TransportService;
import org.junit.After;
import org.junit.Before;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.emptyIterable;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasToString;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
@TestLogging("discovery.zen.publish:TRACE")
public class PublishClusterStateActionTests extends ESTestCase {
private static final ClusterName CLUSTER_NAME = ClusterName.CLUSTER_NAME_SETTING.getDefault(Settings.EMPTY);
protected ThreadPool threadPool;
protected Map<String, MockNode> nodes = new HashMap<>();
public static class MockNode implements PublishClusterStateAction.NewPendingClusterStateListener, DiscoveryNodesProvider {
public final DiscoveryNode discoveryNode;
public final MockTransportService service;
public MockPublishAction action;
public final ClusterStateListener listener;
public volatile ClusterState clusterState;
private final ESLogger logger;
public MockNode(DiscoveryNode discoveryNode, MockTransportService service, @Nullable ClusterStateListener listener, ESLogger logger) {
this.discoveryNode = discoveryNode;
this.service = service;
this.listener = listener;
this.logger = logger;
this.clusterState = ClusterState.builder(CLUSTER_NAME).nodes(DiscoveryNodes.builder().put(discoveryNode).localNodeId(discoveryNode.getId()).build()).build();
}
public MockNode setAsMaster() {
this.clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes()).masterNodeId(discoveryNode.getId())).build();
return this;
}
public MockNode resetMasterId() {
this.clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes()).masterNodeId(null)).build();
return this;
}
public void connectTo(DiscoveryNode node) {
service.connectToNode(node);
}
@Override
public void onNewClusterState(String reason) {
ClusterState newClusterState = action.pendingStatesQueue().getNextClusterStateToProcess();
logger.debug("[{}] received version [{}], uuid [{}]", discoveryNode.getName(), newClusterState.version(), newClusterState.stateUUID());
if (listener != null) {
ClusterChangedEvent event = new ClusterChangedEvent("", newClusterState, clusterState);
listener.clusterChanged(event);
}
if (clusterState.nodes().getMasterNode() == null || newClusterState.supersedes(clusterState)) {
clusterState = newClusterState;
}
action.pendingStatesQueue().markAsProcessed(newClusterState);
}
@Override
public DiscoveryNodes nodes() {
return clusterState.nodes();
}
}
public MockNode createMockNode(final String name) throws Exception {
return createMockNode(name, Settings.EMPTY);
}
public MockNode createMockNode(String name, Settings settings) throws Exception {
return createMockNode(name, settings, null);
}
public MockNode createMockNode(String name, final Settings basSettings, @Nullable ClusterStateListener listener) throws Exception {
final Settings settings = Settings.builder()
.put("name", name)
.put(TransportService.TRACE_LOG_INCLUDE_SETTING.getKey(), "", TransportService.TRACE_LOG_EXCLUDE_SETTING.getKey(), "NOTHING")
.put(basSettings)
.build();
MockTransportService service = buildTransportService(settings);
DiscoveryNode discoveryNode = DiscoveryNode.createLocal(settings, service.boundAddress().publishAddress(),
NodeEnvironment.generateNodeId(settings));
MockNode node = new MockNode(discoveryNode, service, listener, logger);
node.action = buildPublishClusterStateAction(settings, service, () -> node.clusterState, node);
final CountDownLatch latch = new CountDownLatch(nodes.size() * 2 + 1);
TransportConnectionListener waitForConnection = new TransportConnectionListener() {
@Override
public void onNodeConnected(DiscoveryNode node) {
latch.countDown();
}
@Override
public void onNodeDisconnected(DiscoveryNode node) {
fail("disconnect should not be called " + node);
}
};
node.service.addConnectionListener(waitForConnection);
for (MockNode curNode : nodes.values()) {
curNode.service.addConnectionListener(waitForConnection);
curNode.connectTo(node.discoveryNode);
node.connectTo(curNode.discoveryNode);
}
node.connectTo(node.discoveryNode);
assertThat("failed to wait for all nodes to connect", latch.await(5, TimeUnit.SECONDS), equalTo(true));
for (MockNode curNode : nodes.values()) {
curNode.service.removeConnectionListener(waitForConnection);
}
node.service.removeConnectionListener(waitForConnection);
if (nodes.put(name, node) != null) {
fail("Node with the name " + name + " already exist");
}
return node;
}
public MockTransportService service(String name) {
MockNode node = nodes.get(name);
if (node != null) {
return node.service;
}
return null;
}
public PublishClusterStateAction action(String name) {
MockNode node = nodes.get(name);
if (node != null) {
return node.action;
}
return null;
}
@Override
@Before
public void setUp() throws Exception {
super.setUp();
threadPool = new TestThreadPool(getClass().getName());
}
@Override
@After
public void tearDown() throws Exception {
super.tearDown();
for (MockNode curNode : nodes.values()) {
curNode.action.close();
curNode.service.close();
}
terminate(threadPool);
}
protected MockTransportService buildTransportService(Settings settings) {
MockTransportService transportService = MockTransportService.local(Settings.EMPTY, Version.CURRENT, threadPool);
transportService.start();
transportService.acceptIncomingRequests();
return transportService;
}
protected MockPublishAction buildPublishClusterStateAction(
Settings settings,
MockTransportService transportService,
Supplier<ClusterState> clusterStateSupplier,
PublishClusterStateAction.NewPendingClusterStateListener listener
) {
DiscoverySettings discoverySettings =
new DiscoverySettings(settings, new ClusterSettings(settings, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS));
return new MockPublishAction(
settings,
transportService,
clusterStateSupplier,
listener,
discoverySettings,
CLUSTER_NAME);
}
public void testSimpleClusterStatePublishing() throws Exception {
MockNode nodeA = createMockNode("nodeA", Settings.EMPTY).setAsMaster();
MockNode nodeB = createMockNode("nodeB", Settings.EMPTY);
// Initial cluster state
ClusterState clusterState = nodeA.clusterState;
// cluster state update - add nodeB
DiscoveryNodes discoveryNodes = DiscoveryNodes.builder(clusterState.nodes()).put(nodeB.discoveryNode).build();
ClusterState previousClusterState = clusterState;
clusterState = ClusterState.builder(clusterState).nodes(discoveryNodes).incrementVersion().build();
publishStateAndWait(nodeA.action, clusterState, previousClusterState);
assertSameStateFromFull(nodeB.clusterState, clusterState);
// cluster state update - add block
previousClusterState = clusterState;
clusterState = ClusterState.builder(clusterState).blocks(ClusterBlocks.builder().addGlobalBlock(MetaData.CLUSTER_READ_ONLY_BLOCK)).incrementVersion().build();
publishStateAndWait(nodeA.action, clusterState, previousClusterState);
assertSameStateFromDiff(nodeB.clusterState, clusterState);
assertThat(nodeB.clusterState.blocks().global().size(), equalTo(1));
// cluster state update - remove block
previousClusterState = clusterState;
clusterState = ClusterState.builder(clusterState).blocks(ClusterBlocks.EMPTY_CLUSTER_BLOCK).incrementVersion().build();
publishStateAndWait(nodeA.action, clusterState, previousClusterState);
assertSameStateFromDiff(nodeB.clusterState, clusterState);
assertTrue(nodeB.clusterState.wasReadFromDiff());
// Adding new node - this node should get full cluster state while nodeB should still be getting diffs
MockNode nodeC = createMockNode("nodeC", Settings.EMPTY);
// cluster state update 3 - register node C
previousClusterState = clusterState;
discoveryNodes = DiscoveryNodes.builder(discoveryNodes).put(nodeC.discoveryNode).build();
clusterState = ClusterState.builder(clusterState).nodes(discoveryNodes).incrementVersion().build();
publishStateAndWait(nodeA.action, clusterState, previousClusterState);
assertSameStateFromDiff(nodeB.clusterState, clusterState);
// First state
assertSameStateFromFull(nodeC.clusterState, clusterState);
// cluster state update 4 - update settings
previousClusterState = clusterState;
MetaData metaData = MetaData.builder(clusterState.metaData()).transientSettings(Settings.builder().put("foo", "bar").build()).build();
clusterState = ClusterState.builder(clusterState).metaData(metaData).incrementVersion().build();
publishStateAndWait(nodeA.action, clusterState, previousClusterState);
assertSameStateFromDiff(nodeB.clusterState, clusterState);
assertThat(nodeB.clusterState.blocks().global().size(), equalTo(0));
assertSameStateFromDiff(nodeC.clusterState, clusterState);
assertThat(nodeC.clusterState.blocks().global().size(), equalTo(0));
// cluster state update - skipping one version change - should request full cluster state
previousClusterState = ClusterState.builder(clusterState).incrementVersion().build();
clusterState = ClusterState.builder(clusterState).incrementVersion().build();
publishStateAndWait(nodeA.action, clusterState, previousClusterState);
assertSameStateFromFull(nodeB.clusterState, clusterState);
assertSameStateFromFull(nodeC.clusterState, clusterState);
assertFalse(nodeC.clusterState.wasReadFromDiff());
// node A steps down from being master
nodeA.resetMasterId();
nodeB.resetMasterId();
nodeC.resetMasterId();
// node B becomes the master and sends a version of the cluster state that goes back
discoveryNodes = DiscoveryNodes.builder(discoveryNodes)
.put(nodeA.discoveryNode)
.put(nodeB.discoveryNode)
.put(nodeC.discoveryNode)
.masterNodeId(nodeB.discoveryNode.getId())
.localNodeId(nodeB.discoveryNode.getId())
.build();
previousClusterState = ClusterState.builder(new ClusterName("test")).nodes(discoveryNodes).build();
clusterState = ClusterState.builder(clusterState).nodes(discoveryNodes).incrementVersion().build();
publishStateAndWait(nodeB.action, clusterState, previousClusterState);
assertSameStateFromFull(nodeA.clusterState, clusterState);
assertSameStateFromFull(nodeC.clusterState, clusterState);
}
public void testUnexpectedDiffPublishing() throws Exception {
MockNode nodeA = createMockNode("nodeA", Settings.EMPTY, event -> {
fail("Shouldn't send cluster state to myself");
}).setAsMaster();
MockNode nodeB = createMockNode("nodeB", Settings.EMPTY);
// Initial cluster state with both states - the second node still shouldn't get diff even though it's present in the previous cluster state
DiscoveryNodes discoveryNodes = DiscoveryNodes.builder(nodeA.nodes()).put(nodeB.discoveryNode).build();
ClusterState previousClusterState = ClusterState.builder(CLUSTER_NAME).nodes(discoveryNodes).build();
ClusterState clusterState = ClusterState.builder(previousClusterState).incrementVersion().build();
publishStateAndWait(nodeA.action, clusterState, previousClusterState);
assertSameStateFromFull(nodeB.clusterState, clusterState);
// cluster state update - add block
previousClusterState = clusterState;
clusterState = ClusterState.builder(clusterState).blocks(ClusterBlocks.builder().addGlobalBlock(MetaData.CLUSTER_READ_ONLY_BLOCK)).incrementVersion().build();
publishStateAndWait(nodeA.action, clusterState, previousClusterState);
assertSameStateFromDiff(nodeB.clusterState, clusterState);
}
public void testDisablingDiffPublishing() throws Exception {
Settings noDiffPublishingSettings = Settings.builder().put(DiscoverySettings.PUBLISH_DIFF_ENABLE_SETTING.getKey(), false).build();
MockNode nodeA = createMockNode("nodeA", noDiffPublishingSettings, new ClusterStateListener() {
@Override
public void clusterChanged(ClusterChangedEvent event) {
fail("Shouldn't send cluster state to myself");
}
});
MockNode nodeB = createMockNode("nodeB", noDiffPublishingSettings, new ClusterStateListener() {
@Override
public void clusterChanged(ClusterChangedEvent event) {
assertFalse(event.state().wasReadFromDiff());
}
});
// Initial cluster state
DiscoveryNodes discoveryNodes = DiscoveryNodes.builder().put(nodeA.discoveryNode).localNodeId(nodeA.discoveryNode.getId()).masterNodeId(nodeA.discoveryNode.getId()).build();
ClusterState clusterState = ClusterState.builder(CLUSTER_NAME).nodes(discoveryNodes).build();
// cluster state update - add nodeB
discoveryNodes = DiscoveryNodes.builder(discoveryNodes).put(nodeB.discoveryNode).build();
ClusterState previousClusterState = clusterState;
clusterState = ClusterState.builder(clusterState).nodes(discoveryNodes).incrementVersion().build();
publishStateAndWait(nodeA.action, clusterState, previousClusterState);
// cluster state update - add block
previousClusterState = clusterState;
clusterState = ClusterState.builder(clusterState).blocks(ClusterBlocks.builder().addGlobalBlock(MetaData.CLUSTER_READ_ONLY_BLOCK)).incrementVersion().build();
publishStateAndWait(nodeA.action, clusterState, previousClusterState);
}
/**
* Test not waiting on publishing works correctly (i.e., publishing times out)
*/
public void testSimultaneousClusterStatePublishing() throws Exception {
int numberOfNodes = randomIntBetween(2, 10);
int numberOfIterations = scaledRandomIntBetween(5, 50);
Settings settings = Settings.builder().put(DiscoverySettings.PUBLISH_DIFF_ENABLE_SETTING.getKey(), randomBoolean()).build();
MockNode master = createMockNode("node0", settings, new ClusterStateListener() {
@Override
public void clusterChanged(ClusterChangedEvent event) {
assertProperMetaDataForVersion(event.state().metaData(), event.state().version());
}
}).setAsMaster();
DiscoveryNodes.Builder discoveryNodesBuilder = DiscoveryNodes.builder(master.nodes());
for (int i = 1; i < numberOfNodes; i++) {
final String name = "node" + i;
final MockNode node = createMockNode(name, settings, new ClusterStateListener() {
@Override
public void clusterChanged(ClusterChangedEvent event) {
assertProperMetaDataForVersion(event.state().metaData(), event.state().version());
}
});
discoveryNodesBuilder.put(node.discoveryNode);
}
AssertingAckListener[] listeners = new AssertingAckListener[numberOfIterations];
DiscoveryNodes discoveryNodes = discoveryNodesBuilder.build();
MetaData metaData = MetaData.EMPTY_META_DATA;
ClusterState clusterState = ClusterState.builder(CLUSTER_NAME).metaData(metaData).build();
ClusterState previousState;
for (int i = 0; i < numberOfIterations; i++) {
previousState = clusterState;
metaData = buildMetaDataForVersion(metaData, i + 1);
clusterState = ClusterState.builder(clusterState).incrementVersion().metaData(metaData).nodes(discoveryNodes).build();
listeners[i] = publishState(master.action, clusterState, previousState);
}
for (int i = 0; i < numberOfIterations; i++) {
listeners[i].await(1, TimeUnit.SECONDS);
}
// set the master cs
master.clusterState = clusterState;
for (MockNode node : nodes.values()) {
assertSameState(node.clusterState, clusterState);
assertThat(node.clusterState.nodes().getLocalNode(), equalTo(node.discoveryNode));
}
}
public void testSerializationFailureDuringDiffPublishing() throws Exception {
MockNode nodeA = createMockNode("nodeA", Settings.EMPTY, new ClusterStateListener() {
@Override
public void clusterChanged(ClusterChangedEvent event) {
fail("Shouldn't send cluster state to myself");
}
}).setAsMaster();
MockNode nodeB = createMockNode("nodeB", Settings.EMPTY);
// Initial cluster state with both states - the second node still shouldn't get diff even though it's present in the previous cluster state
DiscoveryNodes discoveryNodes = DiscoveryNodes.builder(nodeA.nodes()).put(nodeB.discoveryNode).build();
ClusterState previousClusterState = ClusterState.builder(CLUSTER_NAME).nodes(discoveryNodes).build();
ClusterState clusterState = ClusterState.builder(previousClusterState).incrementVersion().build();
publishStateAndWait(nodeA.action, clusterState, previousClusterState);
assertSameStateFromFull(nodeB.clusterState, clusterState);
// cluster state update - add block
previousClusterState = clusterState;
clusterState = ClusterState.builder(clusterState).blocks(ClusterBlocks.builder().addGlobalBlock(MetaData.CLUSTER_READ_ONLY_BLOCK)).incrementVersion().build();
ClusterState unserializableClusterState = new ClusterState(clusterState.version(), clusterState.stateUUID(), clusterState) {
@Override
public Diff<ClusterState> diff(ClusterState previousState) {
return new Diff<ClusterState>() {
@Override
public ClusterState apply(ClusterState part) {
fail("this diff shouldn't be applied");
return part;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
throw new IOException("Simulated failure of diff serialization");
}
};
}
};
try {
publishStateAndWait(nodeA.action, unserializableClusterState, previousClusterState);
fail("cluster state published despite of diff errors");
} catch (Discovery.FailedToCommitClusterStateException e) {
assertThat(e.getCause(), notNullValue());
assertThat(e.getCause().getMessage(), containsString("failed to serialize"));
}
}
public void testFailToPublishWithLessThanMinMasterNodes() throws Exception {
final int masterNodes = randomIntBetween(1, 10);
MockNode master = createMockNode("master");
DiscoveryNodes.Builder discoveryNodesBuilder = DiscoveryNodes.builder().put(master.discoveryNode);
for (int i = 1; i < masterNodes; i++) {
discoveryNodesBuilder.put(createMockNode("node" + i).discoveryNode);
}
final int dataNodes = randomIntBetween(0, 5);
final Settings dataSettings = Settings.builder().put(Node.NODE_MASTER_SETTING.getKey(), false).build();
for (int i = 0; i < dataNodes; i++) {
discoveryNodesBuilder.put(createMockNode("data_" + i, dataSettings).discoveryNode);
}
discoveryNodesBuilder.localNodeId(master.discoveryNode.getId()).masterNodeId(master.discoveryNode.getId());
DiscoveryNodes discoveryNodes = discoveryNodesBuilder.build();
MetaData metaData = MetaData.EMPTY_META_DATA;
ClusterState clusterState = ClusterState.builder(CLUSTER_NAME).metaData(metaData).nodes(discoveryNodes).build();
ClusterState previousState = master.clusterState;
try {
publishState(master.action, clusterState, previousState, masterNodes + randomIntBetween(1, 5));
fail("cluster state publishing didn't fail despite of not having enough nodes");
} catch (Discovery.FailedToCommitClusterStateException expected) {
logger.debug("failed to publish as expected", expected);
}
}
public void testPublishingWithSendingErrors() throws Exception {
int goodNodes = randomIntBetween(2, 5);
int errorNodes = randomIntBetween(1, 5);
int timeOutNodes = randomBoolean() ? 0 : randomIntBetween(1, 5); // adding timeout nodes will force timeout errors
final int numberOfMasterNodes = goodNodes + errorNodes + timeOutNodes + 1; // master
final boolean expectingToCommit = randomBoolean();
Settings.Builder settings = Settings.builder();
// make sure we have a reasonable timeout if we expect to timeout, o.w. one that will make the test "hang"
settings.put(DiscoverySettings.COMMIT_TIMEOUT_SETTING.getKey(), expectingToCommit == false && timeOutNodes > 0 ? "100ms" : "1h")
.put(DiscoverySettings.PUBLISH_TIMEOUT_SETTING.getKey(), "5ms"); // test is about committing
MockNode master = createMockNode("master", settings.build());
// randomize things a bit
int[] nodeTypes = new int[goodNodes + errorNodes + timeOutNodes];
for (int i = 0; i < goodNodes; i++) {
nodeTypes[i] = 0;
}
for (int i = goodNodes; i < goodNodes + errorNodes; i++) {
nodeTypes[i] = 1;
}
for (int i = goodNodes + errorNodes; i < nodeTypes.length; i++) {
nodeTypes[i] = 2;
}
Collections.shuffle(Arrays.asList(nodeTypes), random());
DiscoveryNodes.Builder discoveryNodesBuilder = DiscoveryNodes.builder().put(master.discoveryNode);
for (int i = 0; i < nodeTypes.length; i++) {
final MockNode mockNode = createMockNode("node" + i);
discoveryNodesBuilder.put(mockNode.discoveryNode);
switch (nodeTypes[i]) {
case 1:
mockNode.action.errorOnSend.set(true);
break;
case 2:
mockNode.action.timeoutOnSend.set(true);
break;
}
}
final int dataNodes = randomIntBetween(0, 3); // data nodes don't matter
for (int i = 0; i < dataNodes; i++) {
final MockNode mockNode = createMockNode("data_" + i, Settings.builder().put(Node.NODE_MASTER_SETTING.getKey(), false).build());
discoveryNodesBuilder.put(mockNode.discoveryNode);
if (randomBoolean()) {
// we really don't care - just chaos monkey
mockNode.action.errorOnCommit.set(randomBoolean());
mockNode.action.errorOnSend.set(randomBoolean());
mockNode.action.timeoutOnCommit.set(randomBoolean());
mockNode.action.timeoutOnSend.set(randomBoolean());
}
}
final int minMasterNodes;
final String expectedBehavior;
if (expectingToCommit) {
minMasterNodes = randomIntBetween(0, goodNodes + 1); // count master
expectedBehavior = "succeed";
} else {
minMasterNodes = randomIntBetween(goodNodes + 2, numberOfMasterNodes); // +2 because of master
expectedBehavior = timeOutNodes > 0 ? "timeout" : "fail";
}
logger.info("--> expecting commit to {}. good nodes [{}], errors [{}], timeouts [{}]. min_master_nodes [{}]",
expectedBehavior, goodNodes + 1, errorNodes, timeOutNodes, minMasterNodes);
discoveryNodesBuilder.localNodeId(master.discoveryNode.getId()).masterNodeId(master.discoveryNode.getId());
DiscoveryNodes discoveryNodes = discoveryNodesBuilder.build();
MetaData metaData = MetaData.EMPTY_META_DATA;
ClusterState clusterState = ClusterState.builder(CLUSTER_NAME).metaData(metaData).nodes(discoveryNodes).build();
ClusterState previousState = master.clusterState;
try {
publishState(master.action, clusterState, previousState, minMasterNodes);
if (expectingToCommit == false) {
fail("cluster state publishing didn't fail despite of not have enough nodes");
}
} catch (Discovery.FailedToCommitClusterStateException exception) {
logger.debug("failed to publish as expected", exception);
if (expectingToCommit) {
throw exception;
}
assertThat(exception.getMessage(), containsString(timeOutNodes > 0 ? "timed out" : "failed"));
}
}
public void testIncomingClusterStateValidation() throws Exception {
MockNode node = createMockNode("node");
logger.info("--> testing acceptances of any master when having no master");
ClusterState state = ClusterState.builder(node.clusterState)
.nodes(DiscoveryNodes.builder(node.nodes()).masterNodeId(randomAsciiOfLength(10))).incrementVersion().build();
node.action.validateIncomingState(state, null);
// now set a master node
node.clusterState = ClusterState.builder(node.clusterState).nodes(DiscoveryNodes.builder(node.nodes()).masterNodeId("master")).build();
logger.info("--> testing rejection of another master");
try {
node.action.validateIncomingState(state, node.clusterState);
fail("node accepted state from another master");
} catch (IllegalStateException OK) {
assertThat(OK.toString(), containsString("cluster state from a different master than the current one, rejecting"));
}
logger.info("--> test state from the current master is accepted");
node.action.validateIncomingState(ClusterState.builder(node.clusterState)
.nodes(DiscoveryNodes.builder(node.nodes()).masterNodeId("master")).incrementVersion().build(), node.clusterState);
logger.info("--> testing rejection of another cluster name");
try {
node.action.validateIncomingState(ClusterState.builder(new ClusterName(randomAsciiOfLength(10))).nodes(node.nodes()).build(), node.clusterState);
fail("node accepted state with another cluster name");
} catch (IllegalStateException OK) {
assertThat(OK.toString(), containsString("received state from a node that is not part of the cluster"));
}
logger.info("--> testing rejection of a cluster state with wrong local node");
try {
state = ClusterState.builder(node.clusterState)
.nodes(DiscoveryNodes.builder(node.nodes()).localNodeId("_non_existing_").build())
.incrementVersion().build();
node.action.validateIncomingState(state, node.clusterState);
fail("node accepted state with non-existence local node");
} catch (IllegalStateException OK) {
assertThat(OK.toString(), containsString("received state with a local node that does not match the current local node"));
}
try {
MockNode otherNode = createMockNode("otherNode");
state = ClusterState.builder(node.clusterState).nodes(
DiscoveryNodes.builder(node.nodes()).put(otherNode.discoveryNode).localNodeId(otherNode.discoveryNode.getId()).build()
).incrementVersion().build();
node.action.validateIncomingState(state, node.clusterState);
fail("node accepted state with existent but wrong local node");
} catch (IllegalStateException OK) {
assertThat(OK.toString(), containsString("received state with a local node that does not match the current local node"));
}
logger.info("--> testing acceptance of an old cluster state");
final ClusterState incomingState = node.clusterState;
node.clusterState = ClusterState.builder(node.clusterState).incrementVersion().build();
final IllegalStateException e =
expectThrows(IllegalStateException.class, () -> node.action.validateIncomingState(incomingState, node.clusterState));
final String message = String.format(
Locale.ROOT,
"rejecting cluster state version [%d] uuid [%s] received from [%s]",
incomingState.version(),
incomingState.stateUUID(),
incomingState.nodes().getMasterNodeId()
);
assertThat(e, hasToString("java.lang.IllegalStateException: " + message));
// an older version from a *new* master is also OK!
ClusterState previousState = ClusterState.builder(node.clusterState).incrementVersion().build();
state = ClusterState.builder(node.clusterState)
.nodes(DiscoveryNodes.builder(node.clusterState.nodes()).masterNodeId("_new_master_").build())
.build();
// remove the master of the node (but still have a previous cluster state with it)!
node.resetMasterId();
node.action.validateIncomingState(state, previousState);
}
public void testOutOfOrderCommitMessages() throws Throwable {
MockNode node = createMockNode("node").setAsMaster();
final CapturingTransportChannel channel = new CapturingTransportChannel();
List<ClusterState> states = new ArrayList<>();
final int numOfStates = scaledRandomIntBetween(3, 25);
for (int i = 1; i <= numOfStates; i++) {
states.add(ClusterState.builder(node.clusterState).version(i).stateUUID(ClusterState.UNKNOWN_UUID).build());
}
final ClusterState finalState = states.get(numOfStates - 1);
logger.info("--> publishing states");
for (ClusterState state : states) {
node.action.handleIncomingClusterStateRequest(
new BytesTransportRequest(PublishClusterStateAction.serializeFullClusterState(state, Version.CURRENT), Version.CURRENT),
channel);
assertThat(channel.response.get(), equalTo((TransportResponse) TransportResponse.Empty.INSTANCE));
assertThat(channel.error.get(), nullValue());
channel.clear();
}
logger.info("--> committing states");
long largestVersionSeen = Long.MIN_VALUE;
Randomness.shuffle(states);
for (ClusterState state : states) {
node.action.handleCommitRequest(new PublishClusterStateAction.CommitClusterStateRequest(state.stateUUID()), channel);
if (largestVersionSeen < state.getVersion()) {
assertThat(channel.response.get(), equalTo((TransportResponse) TransportResponse.Empty.INSTANCE));
if (channel.error.get() != null) {
throw channel.error.get();
}
largestVersionSeen = state.getVersion();
} else {
// older cluster states will be rejected
assertNotNull(channel.error.get());
assertThat(channel.error.get(), instanceOf(IllegalStateException.class));
}
channel.clear();
}
//now check the last state held
assertSameState(node.clusterState, finalState);
}
/**
* Tests that cluster is committed or times out. It should never be the case that we fail
* an update due to a commit timeout, but it ends up being committed anyway
*/
public void testTimeoutOrCommit() throws Exception {
Settings settings = Settings.builder()
.put(DiscoverySettings.COMMIT_TIMEOUT_SETTING.getKey(), "1ms").build(); // short but so we will sometime commit sometime timeout
MockNode master = createMockNode("master", settings);
MockNode node = createMockNode("node", settings);
ClusterState state = ClusterState.builder(master.clusterState)
.nodes(DiscoveryNodes.builder(master.clusterState.nodes()).put(node.discoveryNode).masterNodeId(master.discoveryNode.getId())).build();
for (int i = 0; i < 10; i++) {
state = ClusterState.builder(state).incrementVersion().build();
logger.debug("--> publishing version [{}], UUID [{}]", state.version(), state.stateUUID());
boolean success;
try {
publishState(master.action, state, master.clusterState, 2).await(1, TimeUnit.HOURS);
success = true;
} catch (Discovery.FailedToCommitClusterStateException OK) {
success = false;
}
logger.debug("--> publishing [{}], verifying...", success ? "succeeded" : "failed");
if (success) {
assertSameState(node.clusterState, state);
} else {
assertThat(node.clusterState.stateUUID(), not(equalTo(state.stateUUID())));
}
}
}
private MetaData buildMetaDataForVersion(MetaData metaData, long version) {
ImmutableOpenMap.Builder<String, IndexMetaData> indices = ImmutableOpenMap.builder(metaData.indices());
indices.put("test" + version, IndexMetaData.builder("test" + version).settings(Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT))
.numberOfShards((int) version).numberOfReplicas(0).build());
return MetaData.builder(metaData)
.transientSettings(Settings.builder().put("test", version).build())
.indices(indices.build())
.build();
}
private void assertProperMetaDataForVersion(MetaData metaData, long version) {
for (long i = 1; i <= version; i++) {
assertThat(metaData.index("test" + i), notNullValue());
assertThat(metaData.index("test" + i).getNumberOfShards(), equalTo((int) i));
}
assertThat(metaData.index("test" + (version + 1)), nullValue());
assertThat(metaData.transientSettings().get("test"), equalTo(Long.toString(version)));
}
public void publishStateAndWait(PublishClusterStateAction action, ClusterState state, ClusterState previousState) throws InterruptedException {
publishState(action, state, previousState).await(1, TimeUnit.SECONDS);
}
public AssertingAckListener publishState(PublishClusterStateAction action, ClusterState state, ClusterState previousState) throws InterruptedException {
final int minimumMasterNodes = randomIntBetween(-1, state.nodes().getMasterNodes().size());
return publishState(action, state, previousState, minimumMasterNodes);
}
public AssertingAckListener publishState(PublishClusterStateAction action, ClusterState state, ClusterState previousState, int minMasterNodes) throws InterruptedException {
AssertingAckListener assertingAckListener = new AssertingAckListener(state.nodes().getSize() - 1);
ClusterChangedEvent changedEvent = new ClusterChangedEvent("test update", state, previousState);
action.publish(changedEvent, minMasterNodes, assertingAckListener);
return assertingAckListener;
}
public static class AssertingAckListener implements Discovery.AckListener {
private final List<Tuple<DiscoveryNode, Throwable>> errors = new CopyOnWriteArrayList<>();
private final AtomicBoolean timeoutOccurred = new AtomicBoolean();
private final CountDownLatch countDown;
public AssertingAckListener(int nodeCount) {
countDown = new CountDownLatch(nodeCount);
}
@Override
public void onNodeAck(DiscoveryNode node, @Nullable Exception e) {
if (e != null) {
errors.add(new Tuple<>(node, e));
}
countDown.countDown();
}
@Override
public void onTimeout() {
timeoutOccurred.set(true);
// Fast forward the counter - no reason to wait here
long currentCount = countDown.getCount();
for (long i = 0; i < currentCount; i++) {
countDown.countDown();
}
}
public void await(long timeout, TimeUnit unit) throws InterruptedException {
assertThat(awaitErrors(timeout, unit), emptyIterable());
}
public List<Tuple<DiscoveryNode, Throwable>> awaitErrors(long timeout, TimeUnit unit) throws InterruptedException {
countDown.await(timeout, unit);
assertFalse(timeoutOccurred.get());
return errors;
}
}
void assertSameState(ClusterState actual, ClusterState expected) {
assertThat(actual, notNullValue());
final String reason = "\n--> actual ClusterState: " + actual.prettyPrint() + "\n--> expected ClusterState:" + expected.prettyPrint();
assertThat("unequal UUIDs" + reason, actual.stateUUID(), equalTo(expected.stateUUID()));
assertThat("unequal versions" + reason, actual.version(), equalTo(expected.version()));
}
void assertSameStateFromDiff(ClusterState actual, ClusterState expected) {
assertSameState(actual, expected);
assertTrue(actual.wasReadFromDiff());
}
void assertSameStateFromFull(ClusterState actual, ClusterState expected) {
assertSameState(actual, expected);
assertFalse(actual.wasReadFromDiff());
}
static class MockPublishAction extends PublishClusterStateAction {
AtomicBoolean timeoutOnSend = new AtomicBoolean();
AtomicBoolean errorOnSend = new AtomicBoolean();
AtomicBoolean timeoutOnCommit = new AtomicBoolean();
AtomicBoolean errorOnCommit = new AtomicBoolean();
public MockPublishAction(Settings settings, TransportService transportService, Supplier<ClusterState> clusterStateSupplier, NewPendingClusterStateListener listener, DiscoverySettings discoverySettings, ClusterName clusterName) {
super(settings, transportService, clusterStateSupplier, listener, discoverySettings, clusterName);
}
@Override
protected void handleIncomingClusterStateRequest(BytesTransportRequest request, TransportChannel channel) throws IOException {
if (errorOnSend.get()) {
throw new ElasticsearchException("forced error on incoming cluster state");
}
if (timeoutOnSend.get()) {
return;
}
super.handleIncomingClusterStateRequest(request, channel);
}
@Override
protected void handleCommitRequest(PublishClusterStateAction.CommitClusterStateRequest request, TransportChannel channel) {
if (errorOnCommit.get()) {
throw new ElasticsearchException("forced error on incoming commit");
}
if (timeoutOnCommit.get()) {
return;
}
super.handleCommitRequest(request, channel);
}
}
static class CapturingTransportChannel implements TransportChannel {
AtomicReference<TransportResponse> response = new AtomicReference<>();
AtomicReference<Throwable> error = new AtomicReference<>();
public void clear() {
response.set(null);
error.set(null);
}
@Override
public String action() {
return "_noop_";
}
@Override
public String getProfileName() {
return "_noop_";
}
@Override
public void sendResponse(TransportResponse response) throws IOException {
this.response.set(response);
assertThat(error.get(), nullValue());
}
@Override
public void sendResponse(TransportResponse response, TransportResponseOptions options) throws IOException {
this.response.set(response);
assertThat(error.get(), nullValue());
}
@Override
public void sendResponse(Exception exception) throws IOException {
this.error.set(exception);
assertThat(response.get(), nullValue());
}
@Override
public long getRequestId() {
return 0;
}
@Override
public String getChannelType() {
return "capturing";
}
}
}
| dpursehouse/elasticsearch | core/src/test/java/org/elasticsearch/discovery/zen/publish/PublishClusterStateActionTests.java | Java | apache-2.0 | 44,836 |
package com.orientechnologies.orient.core.index;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.orientechnologies.common.collection.OCompositeKey;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.impl.ODocument;
@Test
@SuppressWarnings("unchecked")
public class OSimpleKeyIndexDefinitionTest {
private OSimpleKeyIndexDefinition simpleKeyIndexDefinition;
@BeforeMethod
public void beforeMethod() {
simpleKeyIndexDefinition = new OSimpleKeyIndexDefinition(OType.INTEGER, OType.STRING);
}
@Test
public void testGetFields() {
Assert.assertTrue(simpleKeyIndexDefinition.getFields().isEmpty());
}
@Test
public void testGetClassName() {
Assert.assertNull(simpleKeyIndexDefinition.getClassName());
}
@Test
public void testCreateValueSimpleKey() {
final OSimpleKeyIndexDefinition keyIndexDefinition = new OSimpleKeyIndexDefinition(OType.INTEGER);
final Object result = keyIndexDefinition.createValue("2");
Assert.assertEquals(result, 2);
}
@Test
public void testCreateValueCompositeKeyListParam() {
final Object result = simpleKeyIndexDefinition.createValue(Arrays.asList("2", "3"));
final OCompositeKey compositeKey = new OCompositeKey(Arrays.asList(2, "3"));
Assert.assertEquals(result, compositeKey);
}
@Test
public void testCreateValueCompositeKeyNullListParam() {
final Object result = simpleKeyIndexDefinition.createValue(Arrays.asList((Object) null));
Assert.assertNull(result);
}
@Test
public void testNullParamListItem() {
final Object result = simpleKeyIndexDefinition.createValue(Arrays.asList("2", null));
Assert.assertNull(result);
}
@Test
public void testWrongParamTypeListItem() {
final Object result = simpleKeyIndexDefinition.createValue(Arrays.asList("a", "3"));
Assert.assertNull(result);
}
@Test
public void testCreateValueCompositeKey() {
final Object result = simpleKeyIndexDefinition.createValue("2", "3");
final OCompositeKey compositeKey = new OCompositeKey(Arrays.asList(2, "3"));
Assert.assertEquals(result, compositeKey);
}
@Test
public void testCreateValueCompositeKeyNullParamList() {
final Object result = simpleKeyIndexDefinition.createValue((List<?>) null);
Assert.assertNull(result);
}
@Test
public void testCreateValueCompositeKeyNullParam() {
final Object result = simpleKeyIndexDefinition.createValue((Object) null);
Assert.assertNull(result);
}
@Test
public void testCreateValueCompositeKeyEmptyList() {
final Object result = simpleKeyIndexDefinition.createValue(Collections.<Object> emptyList());
Assert.assertNull(result);
}
@Test
public void testNullParamItem() {
final Object result = simpleKeyIndexDefinition.createValue("2", null);
Assert.assertNull(result);
}
@Test
public void testWrongParamType() {
final Object result = simpleKeyIndexDefinition.createValue("a", "3");
Assert.assertNull(result);
}
@Test
public void testParamCount() {
Assert.assertEquals(simpleKeyIndexDefinition.getParamCount(), 2);
}
@Test
public void testParamCountOneItem() {
final OSimpleKeyIndexDefinition keyIndexDefinition = new OSimpleKeyIndexDefinition(OType.INTEGER);
Assert.assertEquals(keyIndexDefinition.getParamCount(), 1);
}
@Test
public void testGetKeyTypes() {
Assert.assertEquals(simpleKeyIndexDefinition.getTypes(), new OType[] { OType.INTEGER, OType.STRING });
}
@Test
public void testGetKeyTypesOneType() {
final OSimpleKeyIndexDefinition keyIndexDefinition = new OSimpleKeyIndexDefinition(OType.BOOLEAN);
Assert.assertEquals(keyIndexDefinition.getTypes(), new OType[] { OType.BOOLEAN });
}
@Test
public void testReload() {
final ODatabaseDocumentTx databaseDocumentTx = new ODatabaseDocumentTx("memory:osimplekeyindexdefinitiontest");
databaseDocumentTx.create();
final ODocument storeDocument = simpleKeyIndexDefinition.toStream();
storeDocument.save();
final ODocument loadDocument = databaseDocumentTx.load(storeDocument.getIdentity());
final OSimpleKeyIndexDefinition loadedKeyIndexDefinition = new OSimpleKeyIndexDefinition();
loadedKeyIndexDefinition.fromStream(loadDocument);
databaseDocumentTx.drop();
Assert.assertEquals(loadedKeyIndexDefinition, simpleKeyIndexDefinition);
}
@Test(expectedExceptions = OIndexException.class)
public void testGetDocumentValueToIndex() {
simpleKeyIndexDefinition.getDocumentValueToIndex(new ODocument());
}
}
| nengxu/OrientDB | core/src/test/java/com/orientechnologies/orient/core/index/OSimpleKeyIndexDefinitionTest.java | Java | apache-2.0 | 4,965 |
/*
* Copyright 2000-2010 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.lang.ant.refactoring;
import com.intellij.codeInsight.TargetElementUtilBase;
import com.intellij.lang.ant.dom.AntDomFileDescription;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.IndexNotReadyException;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiReference;
import com.intellij.psi.xml.XmlFile;
import com.intellij.refactoring.rename.PsiElementRenameHandler;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
/**
* @author Eugene Zhuravlev
* Date: Mar 19, 2007
*/
public final class AntRenameHandler extends PsiElementRenameHandler {
public boolean isAvailableOnDataContext(final DataContext dataContext) {
final PsiElement[] elements = getElements(dataContext);
return elements != null && elements.length > 1;
}
public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file, final DataContext dataContext) {
final PsiElement[] elements = getElements(dataContext);
if (elements != null && elements.length > 0) {
invoke(project, new PsiElement[]{elements[0]}, dataContext);
}
}
public void invoke(@NotNull final Project project, @NotNull final PsiElement[] elements, final DataContext dataContext) {
super.invoke(project, elements, dataContext);
}
@Nullable
private static PsiElement[] getElements(DataContext dataContext) {
final PsiFile psiFile = CommonDataKeys.PSI_FILE.getData(dataContext);
if (!(psiFile instanceof XmlFile && AntDomFileDescription.isAntFile((XmlFile)psiFile))) {
return null;
}
final Editor editor = LangDataKeys.EDITOR.getData(dataContext);
if (editor == null) {
return null;
}
return getPsiElementsIn(editor, psiFile);
}
@Nullable
private static PsiElement[] getPsiElementsIn(final Editor editor, final PsiFile psiFile) {
try {
final PsiReference reference = TargetElementUtilBase.findReference(editor, editor.getCaretModel().getOffset());
if (reference == null) {
return null;
}
final Collection<PsiElement> candidates = TargetElementUtilBase.getInstance().getTargetCandidates(reference);
return ContainerUtil.toArray(candidates, new PsiElement[candidates.size()]);
}
catch (IndexNotReadyException e) {
return null;
}
}
}
| IllusionRom-deprecated/android_platform_tools_idea | plugins/ant/src/com/intellij/lang/ant/refactoring/AntRenameHandler.java | Java | apache-2.0 | 3,289 |
/*
* Copyright 2011 Christopher Pheby
*
* 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.jadira.bindings.core.binder;
import java.lang.annotation.Annotation;
import java.net.URL;
import org.jadira.bindings.core.api.Binding;
import org.jadira.bindings.core.api.Converter;
import org.jadira.bindings.core.api.FromUnmarshaller;
import org.jadira.bindings.core.api.ToMarshaller;
public interface RegisterableBinder {
/**
* Register the configuration file (bindings.xml) at the given URL
* @param nextLocation The URL to register
*/
void registerConfiguration(URL nextLocation);
/**
* Register a Binding with the given source and target class.
* A binding unifies a marshaller and an unmarshaller and both must be available to resolve a binding.
*
* The source class is considered the owning class of the binding. The source can be marshalled
* into the target class. Similarly, the target can be unmarshalled to produce an instance of the source type.
* @param key The converter key
* @param converter The binding to be registered
* @param <S> Source type
* @param <T> Target type
*/
<S, T> void registerBinding(ConverterKey<S,T> key, Binding<S, T> converter);
/**
* Register an UnMarshaller with the given source and target class.
* The unmarshaller is used as follows: Instances of the source can be marshalled into the target class.
* @param key The converter key
* @param converter The FromUnmarshaller to be registered
* @param <S> Source type
* @param <T> Target type
*/
<S, T> void registerUnmarshaller(ConverterKey<S,T> key, FromUnmarshaller<S, T> converter);
/**
* Register a Marshaller with the given source and target class.
* The marshaller is used as follows: Instances of the source can be marshalled into the target class.
* @param key The converter key
* @param converter The ToMarshaller to be registered
* @param <S> Source type
* @param <T> Target type
*/
<S, T> void registerMarshaller(ConverterKey<S,T> key, ToMarshaller<S, T> converter);
/**
* Register a Converter with the given input and output classes. Instances of the input class can be converted into
* instances of the output class
* @param key The converter key
* @param converter The Converter to be registered
* @param <S> Source type
* @param <T> Target type
*/
<S, T> void registerConverter(ConverterKey<S,T> key, Converter<S, T> converter);
/**
* Register a Binding with the given source and target class.
* A binding unifies a marshaller and an unmarshaller and both must be available to resolve a binding.
*
* The source class is considered the owning class of the binding. The source can be marshalled
* into the target class. Similarly, the target can be unmarshalled to produce an instance of the source type.
* @param sourceClass The source (owning) class
* @param targetClass The target (foreign) class
* @param converter The binding to be registered
* @param <S> Source type
* @param <T> Target type
*/
<S, T> void registerBinding(final Class<S> sourceClass, Class<T> targetClass, Binding<S, T> converter);
/**
* Register an UnMarshaller with the given source and target class.
* The unmarshaller is used as follows: Instances of the source can be marshalled into the target class.
* @param sourceClass The source (input) class
* @param targetClass The target (output) class
* @param converter The FromUnmarshaller to be registered
* @param <S> Source type
* @param <T> Target type
*/
<S, T> void registerUnmarshaller(Class<S> sourceClass, Class<T> targetClass, FromUnmarshaller<S, T> converter);
/**
* Register a Marshaller with the given source and target class.
* The marshaller is used as follows: Instances of the source can be marshalled into the target class.
* @param sourceClass The source (input) class
* @param targetClass The target (output) class
* @param converter The ToMarshaller to be registered
* @param <S> Source type
* @param <T> Target type
*/
<S, T> void registerMarshaller(Class<S> sourceClass, Class<T> targetClass, ToMarshaller<S, T> converter);
/**
* Register a Converter with the given input and output classes. Instances of the input class can be converted into
* instances of the output class
* @param sourceClass The source (input) class
* @param targetClass The target (output) class
* @param converter The Converter to be registered
* @param <S> Source type
* @param <T> Target type
*/
<S, T> void registerConverter(final Class<S> sourceClass, Class<T> targetClass, Converter<S, T> converter);
/**
* Register a Binding with the given source and target class.
* A binding unifies a marshaller and an unmarshaller and both must be available to resolve a binding.
*
* The source class is considered the owning class of the binding. The source can be marshalled
* into the target class. Similarly, the target can be unmarshalled to produce an instance of the source type.
* @param sourceClass The source (owning) class
* @param targetClass The target (foreign) class
* @param converter The binding to be registered
* @param qualifier The qualifier for which the binding must be registered
* @param <S> Source type
* @param <T> Target type
*/
<S, T> void registerBinding(final Class<S> sourceClass, Class<T> targetClass, Binding<S, T> converter, Class<? extends Annotation> qualifier);
/**
* Register an UnMarshaller with the given source and target class.
* The unmarshaller is used as follows: Instances of the source can be marshalled into the target class.
* @param sourceClass The source (input) class
* @param targetClass The target (output) class
* @param converter The FromUnmarshaller to be registered
* @param qualifier The qualifier for which the unmarshaller must be registered
* @param <S> Source type
* @param <T> Target type
*/
<S, T> void registerUnmarshaller(Class<S> sourceClass, Class<T> targetClass, FromUnmarshaller<S, T> converter, Class<? extends Annotation> qualifier);
/**
* Register a Marshaller with the given source and target class.
* The marshaller is used as follows: Instances of the source can be marshalled into the target class.
* @param sourceClass The source (input) class
* @param targetClass The target (output) class
* @param converter The ToMarshaller to be registered
* @param qualifier The qualifier for which the marshaller must be registered
* @param <S> Source type
* @param <T> Target type
*/
<S, T> void registerMarshaller(Class<S> sourceClass, Class<T> targetClass, ToMarshaller<S, T> converter, Class<? extends Annotation> qualifier);
/**
* Register a Converter with the given input and output classes. Instances of the input class can be converted into
* instances of the output class
* @param sourceClass The source (input) class
* @param targetClass The target (output) class
* @param converter The Converter to be registered
* @param qualifier The qualifier for which the converter must be registered
* @param <S> Source type
* @param <T> Target type
*/
<S, T> void registerConverter(final Class<S> sourceClass, Class<T> targetClass, Converter<S, T> converter, Class<? extends Annotation> qualifier);
/**
* Inspect each of the supplied classes, processing any of the annotated methods found
* @param classesToInspect
*/
void registerAnnotatedClasses(Class<?>... classesToInspect);
/**
* Return an iterable collection of ConverterKeys, one for each currently registered conversion
*/
Iterable<ConverterKey<?, ?>> getConverterEntries();
}
| JadiraOrg/jadira | bindings/src/main/java/org/jadira/bindings/core/binder/RegisterableBinder.java | Java | apache-2.0 | 8,392 |
/*
* Copyright 2014 Guidewire Software, Inc.
*/
package gw.plugin.ij.intentions;
import com.intellij.codeInsight.CodeInsightUtilBase;
import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiWhiteSpace;
import com.intellij.psi.util.PsiMatcherImpl;
import gw.internal.gosu.parser.Expression;
import gw.internal.gosu.parser.expressions.NumericLiteral;
import gw.lang.parser.IStatement;
import gw.lang.parser.statements.IAssignmentStatement;
import gw.lang.parser.statements.IStatementList;
import gw.lang.parser.statements.IWhileStatement;
import gw.plugin.ij.lang.psi.api.statements.IGosuVariable;
import gw.plugin.ij.lang.psi.impl.statements.GosuForEachStatementImpl;
import gw.plugin.ij.lang.psi.impl.statements.GosuWhileStatementImpl;
import gw.plugin.ij.lang.psi.util.GosuPsiParseUtil;
import gw.plugin.ij.util.GosuBundle;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static com.intellij.psi.util.PsiMatchers.hasClass;
public class WhileToForFix extends LocalQuickFixAndIntentionActionOnPsiElement {
String ident;
Expression rhs;
private IGosuVariable declarationEqualToZero;
private IAssignmentStatement increment;
public WhileToForFix(PsiElement whileStmt, String ident, Expression rhs, IGosuVariable declarationEqualToZero, IAssignmentStatement increment) {
super(whileStmt);
this.ident = ident;
this.rhs = rhs;
this.declarationEqualToZero = declarationEqualToZero;
this.increment = increment;
}
@Override
public void invoke(@NotNull Project project, @NotNull PsiFile file, @Nullable("is null when called from inspection") Editor editor, @NotNull PsiElement startElement, @NotNull PsiElement endElement) {
if (!CodeInsightUtilBase.prepareFileForWrite(startElement.getContainingFile())) {
return;
}
IWhileStatement parsedElement = ((GosuWhileStatementImpl) startElement).getParsedElement();
if (parsedElement == null) {
return;
}
IStatement statement = parsedElement.getStatement();
IStatement[] statements = ((IStatementList) statement).getStatements();
StringBuilder forStmt = new StringBuilder();
forStmt.append("for (");
forStmt.append(ident);
forStmt.append(" in 0..");
if(rhs instanceof NumericLiteral) {
Object res = rhs.evaluate();
if(res instanceof Integer) {
forStmt.append(((Integer)res)-1);
}
} else {
forStmt.append("|" + rhs);
}
forStmt.append(") {\n");
String indent = getIndet(parsedElement, statements);
for (IStatement statement1 : statements) {
if (statement1 != increment) {
forStmt.append(indent);
forStmt.append(statement1.getLocation().getTextFromTokens());
forStmt.append("\n");
}
}
forStmt.append("}");
PsiElement stub = GosuPsiParseUtil.parseProgramm(forStmt.toString(), startElement, file.getManager(), null);
PsiElement newForStmt = new PsiMatcherImpl(stub)
.descendant(hasClass(GosuForEachStatementImpl.class))
.getElement();
if (newForStmt != null) {
declarationEqualToZero.delete();
startElement.replace(newForStmt);
}
}
private String getIndet(IWhileStatement parsedElement, IStatement[] statements) {
int whileColum = parsedElement.getLocation().getColumn();
int column = statements[1].getLocation().getColumn() - whileColum;
if(column < 0) {
return " ";
}
StringBuilder out = new StringBuilder();
for(int i = 0; i <= column; i++) {
out.append(" ");
}
return out.toString();
}
private void removeVarDecl(PsiElement whileStmt, String ident) {
PsiElement prev = whileStmt.getPrevSibling();
while (prev instanceof PsiWhiteSpace) {
prev = prev.getPrevSibling();
}
if (prev instanceof IGosuVariable && ((IGosuVariable) prev).getName().equals(ident)) {
prev.delete();
}
}
@Override
public boolean isAvailable(@NotNull Project project,
@NotNull PsiFile file,
@NotNull PsiElement startElement,
@NotNull PsiElement endElement) {
return startElement instanceof GosuWhileStatementImpl;
}
@NotNull
@Override
public String getText() {
return GosuBundle.message("inspection.while.to.for");
}
@NotNull
@Override
public String getFamilyName() {
return GosuBundle.message("inspection.group.name.statement.issues");
}
}
| pdalbora/gosu-lang | idea-gosu-plugin/src/main/java/gw/plugin/ij/intentions/WhileToForFix.java | Java | apache-2.0 | 4,712 |
/*
* 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.uima.annotator.regex;
import java.util.regex.Pattern;
/**
* RegexVariables interface.
*/
public interface RegexVariables {
public static final String VARIABLE_START = "\\v";
public static final String VARIABLE_REGEX_BEGIN = "\\\\v\\{";
public static final String VARIABLE_REGEX_END = "\\}";
public static final Pattern VARIABLE_REGEX_PATTERN = Pattern
.compile(VARIABLE_REGEX_BEGIN + "(\\w+)" + VARIABLE_REGEX_END);
/**
* Adds a variable to the Variables object.
*
* @param varName
* variable name
*
* @param varValue
* variable value
*/
public void addVariable(String varName, String varValue);
/**
* returns the value of the specified variable or <code>null</code> if the
* variable does not exist
*
* @param varName
* variable name
*
* @return returns the variable value of <code>null</code> if the variable
* does not exist
*
*/
public String getVariableValue(String varName);
} | jgrivolla/uima-addons | RegularExpressionAnnotator/src/main/java/org/apache/uima/annotator/regex/RegexVariables.java | Java | apache-2.0 | 1,870 |
/*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.client.block.stream;
import alluxio.conf.AlluxioConfiguration;
import alluxio.conf.PropertyKey;
import alluxio.exception.status.AlluxioStatusException;
import alluxio.exception.status.UnauthenticatedException;
import alluxio.grpc.BlockWorkerGrpc;
import alluxio.grpc.CacheRequest;
import alluxio.grpc.ClearMetricsRequest;
import alluxio.grpc.ClearMetricsResponse;
import alluxio.grpc.CreateLocalBlockRequest;
import alluxio.grpc.CreateLocalBlockResponse;
import alluxio.grpc.DataMessageMarshaller;
import alluxio.grpc.DataMessageMarshallerProvider;
import alluxio.grpc.GrpcChannel;
import alluxio.grpc.GrpcChannelBuilder;
import alluxio.grpc.GrpcNetworkGroup;
import alluxio.grpc.GrpcSerializationUtils;
import alluxio.grpc.GrpcServerAddress;
import alluxio.grpc.MoveBlockRequest;
import alluxio.grpc.MoveBlockResponse;
import alluxio.grpc.OpenLocalBlockRequest;
import alluxio.grpc.OpenLocalBlockResponse;
import alluxio.grpc.ReadRequest;
import alluxio.grpc.ReadResponse;
import alluxio.grpc.RemoveBlockRequest;
import alluxio.grpc.RemoveBlockResponse;
import alluxio.grpc.WriteRequest;
import alluxio.grpc.WriteResponse;
import alluxio.resource.AlluxioResourceLeakDetectorFactory;
import alluxio.retry.RetryPolicy;
import alluxio.retry.RetryUtils;
import alluxio.security.user.UserState;
import com.google.common.base.Preconditions;
import com.google.common.io.Closer;
import io.grpc.StatusRuntimeException;
import io.grpc.stub.StreamObserver;
import io.netty.util.ResourceLeakDetector;
import io.netty.util.ResourceLeakTracker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
/**
* Default implementation of {@link BlockWorkerClient}.
*/
public class DefaultBlockWorkerClient implements BlockWorkerClient {
private static final Logger LOG =
LoggerFactory.getLogger(DefaultBlockWorkerClient.class.getName());
private static final ResourceLeakDetector<DefaultBlockWorkerClient> DETECTOR =
AlluxioResourceLeakDetectorFactory.instance()
.newResourceLeakDetector(DefaultBlockWorkerClient.class);
private GrpcChannel mStreamingChannel;
private GrpcChannel mRpcChannel;
private GrpcServerAddress mAddress;
private final long mRpcTimeoutMs;
private BlockWorkerGrpc.BlockWorkerStub mStreamingAsyncStub;
private BlockWorkerGrpc.BlockWorkerBlockingStub mRpcBlockingStub;
private BlockWorkerGrpc.BlockWorkerStub mRpcAsyncStub;
@Nullable
private final ResourceLeakTracker<DefaultBlockWorkerClient> mTracker;
/**
* Creates a client instance for communicating with block worker.
*
* @param userState the user state
* @param address the address of the worker
* @param alluxioConf Alluxio configuration
*/
public DefaultBlockWorkerClient(UserState userState, GrpcServerAddress address,
AlluxioConfiguration alluxioConf) throws IOException {
RetryPolicy retryPolicy = RetryUtils.defaultClientRetry(
alluxioConf.getDuration(PropertyKey.USER_RPC_RETRY_MAX_DURATION),
alluxioConf.getDuration(PropertyKey.USER_RPC_RETRY_BASE_SLEEP_MS),
alluxioConf.getDuration(PropertyKey.USER_RPC_RETRY_MAX_SLEEP_MS));
UnauthenticatedException lastException = null;
// TODO(feng): unify worker client with AbstractClient
while (retryPolicy.attempt()) {
try {
// Disables channel pooling for data streaming to achieve better throughput.
// Channel is still reused due to client pooling.
mStreamingChannel = GrpcChannelBuilder.newBuilder(address, alluxioConf)
.setSubject(userState.getSubject())
.setNetworkGroup(GrpcNetworkGroup.STREAMING)
.setClientType("DefaultBlockWorkerClient-Stream")
.build();
mStreamingChannel.intercept(new StreamSerializationClientInterceptor());
// Uses default pooling strategy for RPC calls for better scalability.
mRpcChannel = GrpcChannelBuilder.newBuilder(address, alluxioConf)
.setSubject(userState.getSubject())
.setNetworkGroup(GrpcNetworkGroup.RPC)
.setClientType("DefaultBlockWorkerClient-Rpc")
.build();
lastException = null;
break;
} catch (StatusRuntimeException e) {
close();
throw AlluxioStatusException.fromStatusRuntimeException(e);
} catch (UnauthenticatedException e) {
close();
userState.relogin();
lastException = e;
}
}
if (lastException != null) {
throw lastException;
}
mStreamingAsyncStub = BlockWorkerGrpc.newStub(mStreamingChannel);
mRpcBlockingStub = BlockWorkerGrpc.newBlockingStub(mRpcChannel);
mRpcAsyncStub = BlockWorkerGrpc.newStub(mRpcChannel);
mAddress = address;
mRpcTimeoutMs = alluxioConf.getMs(PropertyKey.USER_RPC_RETRY_MAX_DURATION);
mTracker = DETECTOR.track(this);
}
@Override
public boolean isShutdown() {
return mStreamingChannel.isShutdown() || mRpcChannel.isShutdown();
}
@Override
public boolean isHealthy() {
return !isShutdown() && mStreamingChannel.isHealthy() && mRpcChannel.isHealthy();
}
@Override
public void close() throws IOException {
try (Closer closer = Closer.create()) {
closer.register(() -> {
if (mStreamingChannel != null) {
mStreamingChannel.shutdown();
}
});
closer.register(() -> {
if (mRpcChannel != null) {
mRpcChannel.shutdown();
}
});
closer.register(() -> {
if (mTracker != null) {
mTracker.close(this);
}
});
}
}
@Override
public StreamObserver<WriteRequest> writeBlock(StreamObserver<WriteResponse> responseObserver) {
if (responseObserver instanceof DataMessageMarshallerProvider) {
DataMessageMarshaller<WriteRequest> marshaller =
((DataMessageMarshallerProvider<WriteRequest, WriteResponse>) responseObserver)
.getRequestMarshaller();
Preconditions.checkNotNull(marshaller, "marshaller");
return mStreamingAsyncStub
.withOption(GrpcSerializationUtils.OVERRIDDEN_METHOD_DESCRIPTOR,
BlockWorkerGrpc.getWriteBlockMethod().toBuilder()
.setRequestMarshaller(marshaller)
.build())
.writeBlock(responseObserver);
} else {
return mStreamingAsyncStub.writeBlock(responseObserver);
}
}
@Override
public StreamObserver<ReadRequest> readBlock(StreamObserver<ReadResponse> responseObserver) {
if (responseObserver instanceof DataMessageMarshallerProvider) {
DataMessageMarshaller<ReadResponse> marshaller =
((DataMessageMarshallerProvider<ReadRequest, ReadResponse>) responseObserver)
.getResponseMarshaller();
Preconditions.checkNotNull(marshaller);
return mStreamingAsyncStub
.withOption(GrpcSerializationUtils.OVERRIDDEN_METHOD_DESCRIPTOR,
BlockWorkerGrpc.getReadBlockMethod().toBuilder()
.setResponseMarshaller(marshaller)
.build())
.readBlock(responseObserver);
} else {
return mStreamingAsyncStub.readBlock(responseObserver);
}
}
@Override
public StreamObserver<CreateLocalBlockRequest> createLocalBlock(
StreamObserver<CreateLocalBlockResponse> responseObserver) {
return mStreamingAsyncStub.createLocalBlock(responseObserver);
}
@Override
public StreamObserver<OpenLocalBlockRequest> openLocalBlock(
StreamObserver<OpenLocalBlockResponse> responseObserver) {
return mStreamingAsyncStub.openLocalBlock(responseObserver);
}
@Override
public RemoveBlockResponse removeBlock(final RemoveBlockRequest request) {
return mRpcBlockingStub.withDeadlineAfter(mRpcTimeoutMs, TimeUnit.MILLISECONDS)
.removeBlock(request);
}
@Override
public MoveBlockResponse moveBlock(MoveBlockRequest request) {
return mRpcBlockingStub.withDeadlineAfter(mRpcTimeoutMs, TimeUnit.MILLISECONDS)
.moveBlock(request);
}
@Override
public ClearMetricsResponse clearMetrics(ClearMetricsRequest request) {
return mRpcBlockingStub.withDeadlineAfter(mRpcTimeoutMs, TimeUnit.MILLISECONDS)
.clearMetrics(request);
}
@Override
public void cache(CacheRequest request) {
boolean async = request.getAsync();
try {
mRpcBlockingStub.withDeadlineAfter(mRpcTimeoutMs, TimeUnit.MILLISECONDS).cache(request);
} catch (Exception e) {
if (!async) {
throw e;
}
LOG.warn("Error sending async cache request {} to worker {}.", request, mAddress, e);
}
}
}
| wwjiang007/alluxio | core/client/fs/src/main/java/alluxio/client/block/stream/DefaultBlockWorkerClient.java | Java | apache-2.0 | 9,174 |
/*
* Copyright (c) 2005-2010 Grameen Foundation USA
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* See also http://www.apache.org/licenses/LICENSE-2.0.html for an
* explanation of the license and how it is applied.
*/
package org.mifos.test.acceptance.framework.loan;
public class CreateLoanAccountSearchParameters {
private String searchString;
private String loanProduct;
public String getSearchString() {
return this.searchString;
}
public void setSearchString(String searchString) {
this.searchString = searchString;
}
public String getLoanProduct() {
return this.loanProduct;
}
public void setLoanProduct(String loanProduct) {
this.loanProduct = loanProduct;
}
}
| vorburger/mifos-head | acceptanceTests/src/test/java/org/mifos/test/acceptance/framework/loan/CreateLoanAccountSearchParameters.java | Java | apache-2.0 | 1,290 |
/*
* Copyright 2014 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.realm.internal.test;
import io.realm.internal.DefineTable;
/**
* A helper class containing model(s) for simple code generation tests.
*/
class CodeGenTest {
@DefineTable // this is enabled only for occasional local tests
class someModel {
String name;
int age;
}
}
| ShikaSD/realm-java | realm/realm-library/src/androidTest/java/io/realm/internal/test/CodeGenTest.java | Java | apache-2.0 | 901 |
/*
* $Id: WrapperClassBean.java 799110 2009-07-29 22:44:26Z musachy $
*
* 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.struts2.json;
import java.util.List;
import java.util.Map;
public class WrapperClassBean {
private String stringField;
private Integer intField;
private int nullIntField;
private Boolean booleanField;
private boolean primitiveBooleanField1;
private boolean primitiveBooleanField2;
private boolean primitiveBooleanField3;
private Character charField;
private Long longField;
private Float floatField;
private Double doubleField;
private Object objectField;
private Byte byteField;
private List<SimpleValue> listField;
private List<Map<String, Long>> listMapField;
private Map<String, List<Long>> mapListField;
private Map<String, Long>[] arrayMapField;
public List<SimpleValue> getListField() {
return listField;
}
public void setListField(List<SimpleValue> listField) {
this.listField = listField;
}
public List<Map<String, Long>> getListMapField() {
return listMapField;
}
public void setListMapField(List<Map<String, Long>> listMapField) {
this.listMapField = listMapField;
}
public Map<String, List<Long>> getMapListField() {
return mapListField;
}
public void setMapListField(Map<String, List<Long>> mapListField) {
this.mapListField = mapListField;
}
public Map<String, Long>[] getArrayMapField() {
return arrayMapField;
}
public void setArrayMapField(Map<String, Long>[] arrayMapField) {
this.arrayMapField = arrayMapField;
}
public Boolean getBooleanField() {
return booleanField;
}
public void setBooleanField(Boolean booleanField) {
this.booleanField = booleanField;
}
public boolean isPrimitiveBooleanField1() {
return primitiveBooleanField1;
}
public void setPrimitiveBooleanField1(boolean primitiveBooleanField1) {
this.primitiveBooleanField1 = primitiveBooleanField1;
}
public boolean isPrimitiveBooleanField2() {
return primitiveBooleanField2;
}
public void setPrimitiveBooleanField2(boolean primitiveBooleanField2) {
this.primitiveBooleanField2 = primitiveBooleanField2;
}
public boolean isPrimitiveBooleanField3() {
return primitiveBooleanField3;
}
public void setPrimitiveBooleanField3(boolean primitiveBooleanField3) {
this.primitiveBooleanField3 = primitiveBooleanField3;
}
public Byte getByteField() {
return byteField;
}
public void setByteField(Byte byteField) {
this.byteField = byteField;
}
public Character getCharField() {
return charField;
}
public void setCharField(Character charField) {
this.charField = charField;
}
public Double getDoubleField() {
return doubleField;
}
public void setDoubleField(Double doubleField) {
this.doubleField = doubleField;
}
public Float getFloatField() {
return floatField;
}
public void setFloatField(Float floatField) {
this.floatField = floatField;
}
public Integer getIntField() {
return intField;
}
public void setIntField(Integer intField) {
this.intField = intField;
}
public int getNullIntField() {
return nullIntField;
}
public void setNullIntField(int nullIntField) {
this.nullIntField = nullIntField;
}
public Long getLongField() {
return longField;
}
public void setLongField(Long longField) {
this.longField = longField;
}
public Object getObjectField() {
return objectField;
}
public void setObjectField(Object objectField) {
this.objectField = objectField;
}
public String getStringField() {
return stringField;
}
public void setStringField(String stringField) {
this.stringField = stringField;
}
}
| WillJiang/WillJiang | src/plugins/json/src/test/java/org/apache/struts2/json/WrapperClassBean.java | Java | apache-2.0 | 4,821 |
package alien4cloud.tosca.parser.mapping.generator;
import java.io.IOException;
import java.util.AbstractMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.nodes.MappingNode;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.NodeTuple;
import org.yaml.snakeyaml.nodes.ScalarNode;
import org.yaml.snakeyaml.nodes.SequenceNode;
import alien4cloud.tosca.parser.IChecker;
import alien4cloud.tosca.parser.INodeParser;
import alien4cloud.tosca.parser.KeyValueMappingTarget;
import alien4cloud.tosca.parser.MappingTarget;
import alien4cloud.tosca.parser.ParserUtils;
import alien4cloud.tosca.parser.ParsingContextExecution;
import alien4cloud.tosca.parser.ParsingError;
import alien4cloud.tosca.parser.ParsingException;
import alien4cloud.tosca.parser.ParsingResult;
import alien4cloud.tosca.parser.YamlSimpleParser;
import alien4cloud.tosca.parser.impl.ErrorCode;
import alien4cloud.tosca.parser.impl.base.CheckedTypeNodeParser;
import alien4cloud.tosca.parser.impl.base.ScalarParser;
import alien4cloud.tosca.parser.impl.base.TypeNodeParser;
import alien4cloud.tosca.parser.mapping.DefaultParser;
import com.google.common.collect.Maps;
/**
* Load type mapping definition from yaml and add it to the type mapping registry.
*/
@Slf4j
@Component
public class MappingGenerator extends DefaultParser<Map<String, INodeParser>> {
@Resource
private ApplicationContext applicationContext;
private Map<String, INodeParser> parsers = Maps.newHashMap();
private Map<String, IMappingBuilder> mappingBuilders = Maps.newHashMap();
private Map<String, IChecker> checkers = Maps.newHashMap();
@PostConstruct
public void initialize() {
Map<String, INodeParser> contextParsers = applicationContext.getBeansOfType(INodeParser.class);
// register parsers based on their class name.
for (INodeParser parser : contextParsers.values()) {
parsers.put(parser.getClass().getName(), parser);
}
Map<String, IMappingBuilder> contextMappingBuilders = applicationContext.getBeansOfType(IMappingBuilder.class);
for (IMappingBuilder mappingBuilder : contextMappingBuilders.values()) {
mappingBuilders.put(mappingBuilder.getKey(), mappingBuilder);
}
Map<String, IChecker> contextCheckers = applicationContext.getBeansOfType(IChecker.class);
for (IChecker checker : contextCheckers.values()) {
checkers.put(checker.getName(), checker);
}
}
public Map<String, INodeParser> process(String resourceLocation) throws ParsingException {
org.springframework.core.io.Resource resource = applicationContext.getResource(resourceLocation);
YamlSimpleParser<Map<String, INodeParser>> nodeParser = new YamlSimpleParser<>(this);
try {
ParsingResult<Map<String, INodeParser>> result = nodeParser.parseFile(resource.getURI().toString(), resource.getFilename(),
resource.getInputStream(), null);
if (result.getContext().getParsingErrors().isEmpty()) {
return result.getResult();
}
throw new ParsingException(resource.getFilename(), result.getContext().getParsingErrors());
} catch (IOException e) {
log.error("Failed to open stream", e);
throw new ParsingException(resource.getFilename(), new ParsingError(ErrorCode.MISSING_FILE, "Unable to load file.", null, e.getMessage(), null,
resourceLocation));
}
}
public Map<String, INodeParser> parse(Node node, ParsingContextExecution context) {
Map<String, INodeParser> parsers = Maps.newHashMap();
if (node instanceof SequenceNode) {
SequenceNode types = (SequenceNode) node;
for (Node mapping : types.getValue()) {
Map.Entry<String, INodeParser<?>> entry = processTypeMapping(mapping, context);
if (entry != null) {
parsers.put(entry.getKey(), entry.getValue());
}
}
} else {
context.getParsingErrors().add(
new ParsingError(ErrorCode.SYNTAX_ERROR, "Mapping should be a sequence of type mappings", node.getStartMark(), "Actually was "
+ node.getClass().getSimpleName(), node.getEndMark(), ""));
}
return parsers;
}
private Map.Entry<String, INodeParser<?>> processTypeMapping(Node node, ParsingContextExecution context) {
try {
return doProcessTypeMapping(node, context);
} catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
log.error("Failed to load class while parsing mapping", e);
context.getParsingErrors().add(
new ParsingError(ErrorCode.SYNTAX_ERROR, "Unable to load class", node.getStartMark(), e.getMessage(), node.getEndMark(), ""));
return null;
}
}
private Map.Entry<String, INodeParser<?>> doProcessTypeMapping(Node node, ParsingContextExecution context) throws ClassNotFoundException,
IllegalAccessException, InstantiationException {
if (node instanceof MappingNode) {
MappingNode mapping = (MappingNode) node;
String yamlType = null;
INodeParser<?> parser = null;
for (NodeTuple tuple : mapping.getValue()) {
if (yamlType == null) {
yamlType = ParserUtils.getScalar(tuple.getKeyNode(), context);
String type = ParserUtils.getScalar(tuple.getValueNode(), context);
if (type.startsWith("__")) {
parser = getWrapperParser(type, mapping, context);
return new AbstractMap.SimpleEntry<String, INodeParser<?>>(yamlType, parser);
}
parser = this.parsers.get(type);
if (parser != null) {
log.debug("Mapping yaml type <" + yamlType + "> using parser <" + type + ">");
return new AbstractMap.SimpleEntry<String, INodeParser<?>>(yamlType, parser);
}
parser = buildTypeNodeParser(yamlType, type);
// log.debug("Mapping yaml type <" + yamlType + "> to class <" + type + ">");
// Class<?> javaClass = Class.forName(type);
// parser = new TypeNodeParser<>(javaClass, yamlType);
} else {
// process a mapping
map(tuple, (TypeNodeParser) parser, context);
}
}
return new AbstractMap.SimpleEntry<String, INodeParser<?>>(yamlType, parser);
} else {
context.getParsingErrors().add(
new ParsingError(ErrorCode.SYNTAX_ERROR, "Unable to process type mapping.", node.getStartMark(),
"Mapping must be defined using a mapping node.", node.getEndMark(), ""));
}
return null;
}
private TypeNodeParser<?> buildTypeNodeParser(String yamlType, String javaType) throws ClassNotFoundException {
String realJavaType = javaType;
IChecker checker = null;
if (javaType.contains("|")) {
realJavaType = javaType.substring(0, javaType.indexOf("|"));
String checkerName = javaType.substring(javaType.indexOf("|") + 1);
log.debug(String.format("After parsing <%s>, realJavaType is <%s>, checkerName is <%s>", javaType, realJavaType, checkerName));
checker = checkers.get(checkerName);
if (checker == null) {
log.warn(String.format("Can not find checker <%s>, using a standard TypeNodeParser", checkerName));
}
}
Class<?> javaClass = Class.forName(realJavaType);
if (checker == null) {
log.debug("Mapping yaml type <" + yamlType + "> to class <" + realJavaType + ">");
return new TypeNodeParser<>(javaClass, yamlType);
} else {
// TODO check that the type are compatible
log.debug("Mapping yaml type <" + yamlType + "> to class <" + realJavaType + "> using checker " + checker.toString());
return new CheckedTypeNodeParser<>(javaClass, yamlType, checker);
}
}
private INodeParser<?> getWrapperParser(String wrapperKey, MappingNode mapping, ParsingContextExecution context) {
IMappingBuilder builder = this.mappingBuilders.get(wrapperKey.substring(2));
return builder.buildMapping(mapping, context).getParser();
}
private void map(NodeTuple tuple, TypeNodeParser<?> parser, ParsingContextExecution context) {
String key = ParserUtils.getScalar(tuple.getKeyNode(), context);
int positionMappingIndex = positionMappingIndex(key);
if (positionMappingIndex > -1) {
mapPositionMapping(positionMappingIndex, tuple.getValueNode(), parser, context);
} else {
MappingTarget mappingTarget = getMappingTarget(tuple.getValueNode(), context);
if (mappingTarget != null) {
parser.getYamlToObjectMapping().put(key, mappingTarget);
}
}
}
private MappingTarget getMappingTarget(Node mappingNode, ParsingContextExecution context) {
if (mappingNode instanceof ScalarNode) {
// create a scalar mapping
String value = ParserUtils.getScalar(mappingNode, context);
return new MappingTarget(value, parsers.get(ScalarParser.class.getName()));
} else if (mappingNode instanceof MappingNode) {
return mapMappingNode((MappingNode) mappingNode, context);
}
return null;
}
private int positionMappingIndex(String key) {
if (key.startsWith("__")) {
try {
int position = Integer.valueOf(key.substring(2));
return position;
} catch (NumberFormatException e) {
// not a position mapping
return -1;
}
}
return -1;
}
private void mapPositionMapping(Integer index, Node positionMapping, TypeNodeParser<?> parser, ParsingContextExecution context) {
if (positionMapping instanceof MappingNode) {
MappingNode mappingNode = (MappingNode) positionMapping;
String key = null;
MappingTarget valueMappingTarget = null;
for (NodeTuple tuple : mappingNode.getValue()) {
String tupleKey = ParserUtils.getScalar(tuple.getKeyNode(), context);
if (tupleKey.equals("key")) {
key = ParserUtils.getScalar(tuple.getValueNode(), context);
} else if (tupleKey.equals("value")) {
valueMappingTarget = getMappingTarget(tuple.getValueNode(), context);
} else {
context.getParsingErrors().add(
new ParsingError(ErrorCode.SYNTAX_ERROR, "Unknown key for position mapping.", tuple.getKeyNode().getStartMark(), tupleKey, tuple
.getKeyNode().getEndMark(), ""));
}
}
if (valueMappingTarget == null) {
return;
}
if (key == null) {
parser.getYamlOrderedToObjectMapping().put(index, valueMappingTarget);
} else {
parser.getYamlOrderedToObjectMapping().put(index, new KeyValueMappingTarget(key, valueMappingTarget.getPath(), valueMappingTarget.getParser()));
}
} else {
context.getParsingErrors().add(
new ParsingError(ErrorCode.SYNTAX_ERROR, "Position mapping must be a mapping node with key and value fields.", positionMapping
.getStartMark(), "", positionMapping.getEndMark(), ""));
}
}
private MappingTarget mapMappingNode(MappingNode mappingNode, ParsingContextExecution context) {
String key = ParserUtils.getScalar(mappingNode.getValue().get(0).getKeyNode(), context);
IMappingBuilder mappingBuilder = mappingBuilders.get(key);
if (mappingBuilder != null) {
log.debug("Mapping yaml key <" + key + "> using mapping builder " + mappingBuilder.getClass().getName());
return mappingBuilder.buildMapping(mappingNode, context);
}
context.getParsingErrors().add(
new ParsingError(ErrorCode.SYNTAX_ERROR, "No mapping target found for key", mappingNode.getValue().get(0).getKeyNode().getStartMark(), key,
mappingNode.getValue().get(0).getKeyNode().getEndMark(), ""));
return null;
}
} | loicalbertin/alien4cloud | alien4cloud-core/src/main/java/alien4cloud/tosca/parser/mapping/generator/MappingGenerator.java | Java | apache-2.0 | 12,944 |
/*
* 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.carbondata.core.writer.sortindex;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import org.apache.carbondata.core.carbon.CarbonTableIdentifier;
import org.apache.carbondata.core.carbon.ColumnIdentifier;
import org.apache.carbondata.core.datastorage.store.filesystem.CarbonFile;
import org.apache.carbondata.core.datastorage.store.impl.FileFactory;
import org.apache.carbondata.core.reader.sortindex.CarbonDictionarySortIndexReader;
import org.apache.carbondata.core.reader.sortindex.CarbonDictionarySortIndexReaderImpl;
import org.apache.carbondata.core.util.CarbonUtil;
import org.apache.carbondata.core.writer.CarbonDictionaryWriter;
import org.apache.carbondata.core.writer.CarbonDictionaryWriterImpl;
import org.apache.commons.lang.ArrayUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* class contains the unit test cases of the dictionary sort index & sort index inverted writing
*/
public class CarbonDictionarySortIndexWriterImplTest {
private String hdfsStorePath;
@Before public void setUp() throws Exception {
hdfsStorePath = "target/carbonStore";
}
@After public void tearDown() throws Exception {
//deleteStorePath();
}
/**
* s
* Method to test the write of sortIndex file.
*
* @throws Exception
*/
@Test public void write() throws Exception {
String storePath = hdfsStorePath;
CarbonTableIdentifier carbonTableIdentifier = new CarbonTableIdentifier("testSchema", "carbon", UUID.randomUUID().toString());
ColumnIdentifier columnIdentifier = new ColumnIdentifier("Name", null, null);
String metaFolderPath =hdfsStorePath+File.separator+carbonTableIdentifier.getDatabaseName()+File.separator+carbonTableIdentifier.getTableName()+File.separator+"Metadata";
CarbonUtil.checkAndCreateFolder(metaFolderPath);
CarbonDictionaryWriter dictionaryWriter = new CarbonDictionaryWriterImpl(hdfsStorePath,
carbonTableIdentifier, columnIdentifier);
CarbonDictionarySortIndexWriter dictionarySortIndexWriter =
new CarbonDictionarySortIndexWriterImpl(carbonTableIdentifier, columnIdentifier, storePath);
List<int[]> indexList = prepareExpectedData();
int[] data = indexList.get(0);
for(int i=0;i<data.length;i++) {
dictionaryWriter.write(String.valueOf(data[i]));
}
dictionaryWriter.close();
dictionaryWriter.commit();
List<Integer> sortIndex = Arrays.asList(ArrayUtils.toObject(indexList.get(0)));
List<Integer> invertedSortIndex = Arrays.asList(ArrayUtils.toObject(indexList.get(1)));
dictionarySortIndexWriter.writeSortIndex(sortIndex);
dictionarySortIndexWriter.writeInvertedSortIndex(invertedSortIndex);
dictionarySortIndexWriter.close();
CarbonDictionarySortIndexReader carbonDictionarySortIndexReader =
new CarbonDictionarySortIndexReaderImpl(carbonTableIdentifier, columnIdentifier, storePath);
List<Integer> actualSortIndex = carbonDictionarySortIndexReader.readSortIndex();
List<Integer> actualInvertedSortIndex = carbonDictionarySortIndexReader.readInvertedSortIndex();
for (int i = 0; i < actualSortIndex.size(); i++) {
Assert.assertEquals(sortIndex.get(i), actualSortIndex.get(i));
Assert.assertEquals(invertedSortIndex.get(i), actualInvertedSortIndex.get(i));
}
}
/**
* @throws Exception
*/
@Test public void writingEmptyValue() throws Exception {
String storePath = hdfsStorePath;
CarbonTableIdentifier carbonTableIdentifier = new CarbonTableIdentifier("testSchema", "carbon", UUID.randomUUID().toString());
ColumnIdentifier columnIdentifier = new ColumnIdentifier("Name", null, null);
CarbonDictionarySortIndexWriter dictionarySortIndexWriter =
new CarbonDictionarySortIndexWriterImpl(carbonTableIdentifier, columnIdentifier, storePath);
List<Integer> sortIndex = new ArrayList<>();
List<Integer> invertedSortIndex = new ArrayList<>();
dictionarySortIndexWriter.writeSortIndex(sortIndex);
dictionarySortIndexWriter.writeInvertedSortIndex(invertedSortIndex);
dictionarySortIndexWriter.close();
CarbonDictionarySortIndexReader carbonDictionarySortIndexReader =
new CarbonDictionarySortIndexReaderImpl(carbonTableIdentifier, columnIdentifier, storePath);
List<Integer> actualSortIndex = carbonDictionarySortIndexReader.readSortIndex();
List<Integer> actualInvertedSortIndex = carbonDictionarySortIndexReader.readInvertedSortIndex();
for (int i = 0; i < actualSortIndex.size(); i++) {
Assert.assertEquals(sortIndex.get(i), actualSortIndex.get(i));
Assert.assertEquals(invertedSortIndex.get(i), actualInvertedSortIndex.get(i));
}
}
private List<int[]> prepareExpectedData() {
List<int[]> indexList = new ArrayList<>(2);
int[] sortIndex = { 0, 3, 2, 4, 1 };
int[] sortIndexInverted = { 0, 2, 4, 1, 2 };
indexList.add(0, sortIndex);
indexList.add(1, sortIndexInverted);
return indexList;
}
/**
* this method will delete the store path
*/
private void deleteStorePath() {
FileFactory.FileType fileType = FileFactory.getFileType(this.hdfsStorePath);
CarbonFile carbonFile = FileFactory.getCarbonFile(this.hdfsStorePath, fileType);
deleteRecursiveSilent(carbonFile);
}
/**
* this method will delete the folders recursively
*/
private static void deleteRecursiveSilent(CarbonFile f) {
if (f.isDirectory()) {
if (f.listFiles() != null) {
for (CarbonFile c : f.listFiles()) {
deleteRecursiveSilent(c);
}
}
}
if (f.exists() && !f.delete()) {
return;
}
}
}
| foryou2030/incubator-carbondata | core/src/test/java/org/apache/carbondata/core/writer/sortindex/CarbonDictionarySortIndexWriterImplTest.java | Java | apache-2.0 | 6,533 |
/**
* Copyright (C) 2015 Born Informatik AG (www.born.ch)
*
* 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.wte4j.impl.service;
import org.wte4j.WteException;
/**
* Map JDBC types (as defined in <code>java.sql.Types</code>) to Java types. The
* mappings have been taken from [1]
* "JDBC 4.0 Specification, JSR 221, November 7, 2006, Appendix B, Table B-3"
*
*/
final class MapperSqlType {
private MapperSqlType() {
};
public static Class<?> map(int jdbcType) {
switch (jdbcType) {
case java.sql.Types.BIT:
case java.sql.Types.BOOLEAN:
return java.lang.Boolean.class;
case java.sql.Types.TINYINT:
case java.sql.Types.SMALLINT:
case java.sql.Types.INTEGER:
return java.lang.Integer.class;
case java.sql.Types.BIGINT:
return java.lang.Long.class;
case java.sql.Types.FLOAT:
case java.sql.Types.DOUBLE:
return java.lang.Double.class;
case java.sql.Types.REAL:
return java.lang.Float.class;
case java.sql.Types.NUMERIC: // according to [1] Table B-1
case java.sql.Types.DECIMAL:
return java.math.BigDecimal.class;
case java.sql.Types.CHAR:
case java.sql.Types.VARCHAR:
case java.sql.Types.LONGVARCHAR:
return java.lang.String.class;
case java.sql.Types.DATE:
return java.sql.Date.class;
case java.sql.Types.TIME:
return java.sql.Time.class;
case java.sql.Types.TIMESTAMP:
return java.sql.Timestamp.class;
case java.sql.Types.STRUCT:
return java.sql.Struct.class;
case java.sql.Types.ARRAY:
return java.sql.Array.class;
case java.sql.Types.BLOB:
return java.sql.Blob.class;
case java.sql.Types.CLOB:
return java.sql.Clob.class;
case java.sql.Types.REF:
return java.sql.Ref.class;
case java.sql.Types.DATALINK:
return java.net.URL.class;
case java.sql.Types.ROWID:
return java.sql.RowId.class;
case java.sql.Types.NULL:
case java.sql.Types.OTHER:
case java.sql.Types.JAVA_OBJECT:
case java.sql.Types.DISTINCT:
case java.sql.Types.BINARY:
case java.sql.Types.VARBINARY:
case java.sql.Types.LONGVARBINARY:
default:
throw new WteException("invalid or unmapped SQL type (" + jdbcType
+ ")");
}
}
}
| bbrehman/wte4j | wte4j-core/src/main/java/org/wte4j/impl/service/MapperSqlType.java | Java | apache-2.0 | 2,743 |
/*
* Copyright 2014 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 io.netty.handler.ssl;
import io.netty.buffer.ByteBuf;
import io.netty.util.internal.NativeLibraryLoader;
import io.netty.util.internal.SystemPropertyUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import org.apache.tomcat.jni.Buffer;
import org.apache.tomcat.jni.Library;
import org.apache.tomcat.jni.Pool;
import org.apache.tomcat.jni.SSL;
import org.apache.tomcat.jni.SSLContext;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Locale;
import java.util.Set;
/**
* Tells if <a href="http://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and its OpenSSL support
* are available.
*/
public final class OpenSsl {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(OpenSsl.class);
private static final String LINUX = "linux";
private static final String UNKNOWN = "unknown";
private static final Throwable UNAVAILABILITY_CAUSE;
private static final Set<String> AVAILABLE_CIPHER_SUITES;
static {
Throwable cause = null;
// Test if netty-tcnative is in the classpath first.
try {
Class.forName("org.apache.tomcat.jni.SSL", false, OpenSsl.class.getClassLoader());
} catch (ClassNotFoundException t) {
cause = t;
logger.debug(
"netty-tcnative not in the classpath; " +
OpenSslEngine.class.getSimpleName() + " will be unavailable.");
}
// If in the classpath, try to load the native library and initialize netty-tcnative.
if (cause == null) {
try {
// The JNI library was not already loaded. Load it now.
loadTcNative();
} catch (Throwable t) {
cause = t;
logger.debug(
"Failed to load netty-tcnative; " +
OpenSslEngine.class.getSimpleName() + " will be unavailable, unless the " +
"application has already loaded the symbols by some other means. " +
"See http://netty.io/wiki/forked-tomcat-native.html for more information.", t);
}
try {
initializeTcNative();
// The library was initialized successfully. If loading the library failed above,
// reset the cause now since it appears that the library was loaded by some other
// means.
cause = null;
} catch (Throwable t) {
if (cause == null) {
cause = t;
}
logger.debug(
"Failed to initialize netty-tcnative; " +
OpenSslEngine.class.getSimpleName() + " will be unavailable. " +
"See http://netty.io/wiki/forked-tomcat-native.html for more information.", t);
}
}
UNAVAILABILITY_CAUSE = cause;
if (cause == null) {
final Set<String> availableCipherSuites = new LinkedHashSet<String>(128);
final long aprPool = Pool.create(0);
try {
final long sslCtx = SSLContext.make(aprPool, SSL.SSL_PROTOCOL_ALL, SSL.SSL_MODE_SERVER);
try {
SSLContext.setOptions(sslCtx, SSL.SSL_OP_ALL);
SSLContext.setCipherSuite(sslCtx, "ALL");
final long ssl = SSL.newSSL(sslCtx, true);
try {
for (String c: SSL.getCiphers(ssl)) {
// Filter out bad input.
if (c == null || c.length() == 0 || availableCipherSuites.contains(c)) {
continue;
}
availableCipherSuites.add(c);
}
} finally {
SSL.freeSSL(ssl);
}
} finally {
SSLContext.free(sslCtx);
}
} catch (Exception e) {
logger.warn("Failed to get the list of available OpenSSL cipher suites.", e);
} finally {
Pool.destroy(aprPool);
}
AVAILABLE_CIPHER_SUITES = Collections.unmodifiableSet(availableCipherSuites);
} else {
AVAILABLE_CIPHER_SUITES = Collections.emptySet();
}
}
/**
* Returns {@code true} if and only if
* <a href="http://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and its OpenSSL support
* are available.
*/
public static boolean isAvailable() {
return UNAVAILABILITY_CAUSE == null;
}
/**
* Returns {@code true} if the used version of openssl supports
* <a href="https://tools.ietf.org/html/rfc7301">ALPN</a>.
*/
public static boolean isAlpnSupported() {
return version() >= 0x10002000L;
}
/**
* Returns the version of the used available OpenSSL library or {@code -1} if {@link #isAvailable()}
* returns {@code false}.
*/
public static int version() {
if (isAvailable()) {
return SSL.version();
}
return -1;
}
/**
* Returns the version string of the used available OpenSSL library or {@code null} if {@link #isAvailable()}
* returns {@code false}.
*/
public static String versionString() {
if (isAvailable()) {
return SSL.versionString();
}
return null;
}
/**
* Ensure that <a href="http://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and
* its OpenSSL support are available.
*
* @throws UnsatisfiedLinkError if unavailable
*/
public static void ensureAvailability() {
if (UNAVAILABILITY_CAUSE != null) {
throw (Error) new UnsatisfiedLinkError(
"failed to load the required native library").initCause(UNAVAILABILITY_CAUSE);
}
}
/**
* Returns the cause of unavailability of
* <a href="http://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and its OpenSSL support.
*
* @return the cause if unavailable. {@code null} if available.
*/
public static Throwable unavailabilityCause() {
return UNAVAILABILITY_CAUSE;
}
/**
* Returns all the available OpenSSL cipher suites.
* Please note that the returned array may include the cipher suites that are insecure or non-functional.
*/
public static Set<String> availableCipherSuites() {
return AVAILABLE_CIPHER_SUITES;
}
/**
* Returns {@code true} if and only if the specified cipher suite is available in OpenSSL.
* Both Java-style cipher suite and OpenSSL-style cipher suite are accepted.
*/
public static boolean isCipherSuiteAvailable(String cipherSuite) {
String converted = CipherSuiteConverter.toOpenSsl(cipherSuite);
if (converted != null) {
cipherSuite = converted;
}
return AVAILABLE_CIPHER_SUITES.contains(cipherSuite);
}
static boolean isError(long errorCode) {
return errorCode != SSL.SSL_ERROR_NONE;
}
static long memoryAddress(ByteBuf buf) {
assert buf.isDirect();
return buf.hasMemoryAddress() ? buf.memoryAddress() : Buffer.address(buf.nioBuffer());
}
private OpenSsl() { }
private static void loadTcNative() throws Exception {
String os = normalizeOs(SystemPropertyUtil.get("os.name", ""));
String arch = normalizeArch(SystemPropertyUtil.get("os.arch", ""));
Set<String> libNames = new LinkedHashSet<String>(3);
// First, try loading the platform-specific library. Platform-specific
// libraries will be available if using a tcnative uber jar.
libNames.add("netty-tcnative-" + os + '-' + arch);
if (LINUX.equalsIgnoreCase(os)) {
// Fedora SSL lib so naming (libssl.so.10 vs libssl.so.1.0.0)..
libNames.add("netty-tcnative-" + os + '-' + arch + "-fedora");
}
// finally the default library.
libNames.add("netty-tcnative");
NativeLibraryLoader.loadFirstAvailable(SSL.class.getClassLoader(),
libNames.toArray(new String[libNames.size()]));
}
private static void initializeTcNative() throws Exception {
Library.initialize("provided");
SSL.initialize(null);
}
private static String normalizeOs(String value) {
value = normalize(value);
if (value.startsWith("aix")) {
return "aix";
}
if (value.startsWith("hpux")) {
return "hpux";
}
if (value.startsWith("os400")) {
// Avoid the names such as os4000
if (value.length() <= 5 || !Character.isDigit(value.charAt(5))) {
return "os400";
}
}
if (value.startsWith(LINUX)) {
return LINUX;
}
if (value.startsWith("macosx") || value.startsWith("osx")) {
return "osx";
}
if (value.startsWith("freebsd")) {
return "freebsd";
}
if (value.startsWith("openbsd")) {
return "openbsd";
}
if (value.startsWith("netbsd")) {
return "netbsd";
}
if (value.startsWith("solaris") || value.startsWith("sunos")) {
return "sunos";
}
if (value.startsWith("windows")) {
return "windows";
}
return UNKNOWN;
}
private static String normalizeArch(String value) {
value = normalize(value);
if (value.matches("^(x8664|amd64|ia32e|em64t|x64)$")) {
return "x86_64";
}
if (value.matches("^(x8632|x86|i[3-6]86|ia32|x32)$")) {
return "x86_32";
}
if (value.matches("^(ia64|itanium64)$")) {
return "itanium_64";
}
if (value.matches("^(sparc|sparc32)$")) {
return "sparc_32";
}
if (value.matches("^(sparcv9|sparc64)$")) {
return "sparc_64";
}
if (value.matches("^(arm|arm32)$")) {
return "arm_32";
}
if ("aarch64".equals(value)) {
return "aarch_64";
}
if (value.matches("^(ppc|ppc32)$")) {
return "ppc_32";
}
if ("ppc64".equals(value)) {
return "ppc_64";
}
if ("ppc64le".equals(value)) {
return "ppcle_64";
}
if ("s390".equals(value)) {
return "s390_32";
}
if ("s390x".equals(value)) {
return "s390_64";
}
return UNKNOWN;
}
private static String normalize(String value) {
return value.toLowerCase(Locale.US).replaceAll("[^a-z0-9]+", "");
}
}
| yrcourage/netty | handler/src/main/java/io/netty/handler/ssl/OpenSsl.java | Java | apache-2.0 | 11,625 |
/**
*
* Copyright 2017 Paul Schaub, 2020 Florian Schmaus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.omemo;
import static org.jivesoftware.smackx.omemo.util.OmemoConstants.OMEMO_NAMESPACE_V_AXOLOTL;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.WeakHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.Manager;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.MessageBuilder;
import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smack.util.Async;
import org.jivesoftware.smackx.carbons.CarbonManager;
import org.jivesoftware.smackx.carbons.packet.CarbonExtension;
import org.jivesoftware.smackx.disco.ServiceDiscoveryManager;
import org.jivesoftware.smackx.hints.element.StoreHint;
import org.jivesoftware.smackx.mam.MamManager;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.jivesoftware.smackx.muc.MultiUserChatManager;
import org.jivesoftware.smackx.muc.RoomInfo;
import org.jivesoftware.smackx.omemo.element.OmemoBundleElement;
import org.jivesoftware.smackx.omemo.element.OmemoDeviceListElement;
import org.jivesoftware.smackx.omemo.element.OmemoDeviceListElement_VAxolotl;
import org.jivesoftware.smackx.omemo.element.OmemoElement;
import org.jivesoftware.smackx.omemo.exceptions.CannotEstablishOmemoSessionException;
import org.jivesoftware.smackx.omemo.exceptions.CorruptedOmemoKeyException;
import org.jivesoftware.smackx.omemo.exceptions.CryptoFailedException;
import org.jivesoftware.smackx.omemo.exceptions.NoOmemoSupportException;
import org.jivesoftware.smackx.omemo.exceptions.NoRawSessionException;
import org.jivesoftware.smackx.omemo.exceptions.UndecidedOmemoIdentityException;
import org.jivesoftware.smackx.omemo.internal.OmemoCachedDeviceList;
import org.jivesoftware.smackx.omemo.internal.OmemoDevice;
import org.jivesoftware.smackx.omemo.listener.OmemoMessageListener;
import org.jivesoftware.smackx.omemo.listener.OmemoMucMessageListener;
import org.jivesoftware.smackx.omemo.trust.OmemoFingerprint;
import org.jivesoftware.smackx.omemo.trust.OmemoTrustCallback;
import org.jivesoftware.smackx.omemo.trust.TrustState;
import org.jivesoftware.smackx.omemo.util.MessageOrOmemoMessage;
import org.jivesoftware.smackx.omemo.util.OmemoConstants;
import org.jivesoftware.smackx.pep.PepEventListener;
import org.jivesoftware.smackx.pep.PepManager;
import org.jivesoftware.smackx.pubsub.PubSubException;
import org.jivesoftware.smackx.pubsub.PubSubManager;
import org.jivesoftware.smackx.pubsub.packet.PubSub;
import org.jxmpp.jid.BareJid;
import org.jxmpp.jid.DomainBareJid;
import org.jxmpp.jid.EntityBareJid;
import org.jxmpp.jid.EntityFullJid;
/**
* Manager that allows sending messages encrypted with OMEMO.
* This class also provides some methods useful for a client that implements OMEMO.
*
* @author Paul Schaub
*/
public final class OmemoManager extends Manager {
private static final Logger LOGGER = Logger.getLogger(OmemoManager.class.getName());
private static final Integer UNKNOWN_DEVICE_ID = -1;
private static final WeakHashMap<XMPPConnection, TreeMap<Integer, OmemoManager>> INSTANCES = new WeakHashMap<>();
private final OmemoService<?, ?, ?, ?, ?, ?, ?, ?, ?> service;
private final HashSet<OmemoMessageListener> omemoMessageListeners = new HashSet<>();
private final HashSet<OmemoMucMessageListener> omemoMucMessageListeners = new HashSet<>();
private final PepManager pepManager;
private OmemoTrustCallback trustCallback;
private BareJid ownJid;
private Integer deviceId;
/**
* Private constructor.
*
* @param connection connection
* @param deviceId deviceId
*/
private OmemoManager(XMPPConnection connection, Integer deviceId) {
super(connection);
service = OmemoService.getInstance();
pepManager = PepManager.getInstanceFor(connection);
this.deviceId = deviceId;
if (connection.isAuthenticated()) {
initBareJidAndDeviceId(this);
} else {
connection.addConnectionListener(new ConnectionListener() {
@Override
public void authenticated(XMPPConnection connection, boolean resumed) {
initBareJidAndDeviceId(OmemoManager.this);
}
});
}
service.registerRatchetForManager(this);
// StanzaListeners
resumeStanzaAndPEPListeners();
}
/**
* Return an OmemoManager instance for the given connection and deviceId.
* If there was an OmemoManager for the connection and id before, return it. Otherwise create a new OmemoManager
* instance and return it.
*
* @param connection XmppConnection.
* @param deviceId MUST NOT be null and MUST be greater than 0.
*
* @return OmemoManager instance for the given connection and deviceId.
*/
public static synchronized OmemoManager getInstanceFor(XMPPConnection connection, Integer deviceId) {
if (deviceId == null || deviceId < 1) {
throw new IllegalArgumentException("DeviceId MUST NOT be null and MUST be greater than 0.");
}
TreeMap<Integer, OmemoManager> managersOfConnection = INSTANCES.get(connection);
if (managersOfConnection == null) {
managersOfConnection = new TreeMap<>();
INSTANCES.put(connection, managersOfConnection);
}
OmemoManager manager = managersOfConnection.get(deviceId);
if (manager == null) {
manager = new OmemoManager(connection, deviceId);
managersOfConnection.put(deviceId, manager);
}
return manager;
}
/**
* Returns an OmemoManager instance for the given connection. If there was one manager for the connection before,
* return it. If there were multiple managers before, return the one with the lowest deviceId.
* If there was no manager before, return a new one. As soon as the connection gets authenticated, the manager
* will look for local deviceIDs and select the lowest one as its id. If there are not local deviceIds, the manager
* will assign itself a random id.
*
* @param connection XmppConnection.
*
* @return OmemoManager instance for the given connection and a determined deviceId.
*/
public static synchronized OmemoManager getInstanceFor(XMPPConnection connection) {
TreeMap<Integer, OmemoManager> managers = INSTANCES.get(connection);
if (managers == null) {
managers = new TreeMap<>();
INSTANCES.put(connection, managers);
}
OmemoManager manager;
if (managers.size() == 0) {
manager = new OmemoManager(connection, UNKNOWN_DEVICE_ID);
managers.put(UNKNOWN_DEVICE_ID, manager);
} else {
manager = managers.get(managers.firstKey());
}
return manager;
}
/**
* Set a TrustCallback for this particular OmemoManager.
* TrustCallbacks are used to query and modify trust decisions.
*
* @param callback trustCallback.
*/
public void setTrustCallback(OmemoTrustCallback callback) {
if (trustCallback != null) {
throw new IllegalStateException("TrustCallback can only be set once.");
}
trustCallback = callback;
}
/**
* Return the TrustCallback of this manager.
*
* @return callback that is used for trust decisions.
*/
OmemoTrustCallback getTrustCallback() {
return trustCallback;
}
/**
* Initializes the OmemoManager. This method must be called before the manager can be used.
*
* @throws CorruptedOmemoKeyException if the OMEMO key is corrupted.
* @throws InterruptedException if the calling thread was interrupted.
* @throws SmackException.NoResponseException if there was no response from the remote entity.
* @throws SmackException.NotConnectedException if the XMPP connection is not connected.
* @throws XMPPException.XMPPErrorException if there was an XMPP error returned.
* @throws SmackException.NotLoggedInException if the XMPP connection is not authenticated.
* @throws PubSubException.NotALeafNodeException if a PubSub leaf node operation was attempted on a non-leaf node.
* @throws IOException if an I/O error occurred.
*/
public synchronized void initialize()
throws SmackException.NotLoggedInException, CorruptedOmemoKeyException, InterruptedException,
SmackException.NoResponseException, SmackException.NotConnectedException, XMPPException.XMPPErrorException,
PubSubException.NotALeafNodeException, IOException {
if (!connection().isAuthenticated()) {
throw new SmackException.NotLoggedInException();
}
if (getTrustCallback() == null) {
throw new IllegalStateException("No TrustCallback set.");
}
getOmemoService().init(new LoggedInOmemoManager(this));
}
/**
* Initialize the manager without blocking. Once the manager is successfully initialized, the finishedCallback will
* be notified. It will also get notified, if an error occurs.
*
* @param finishedCallback callback that gets called once the manager is initialized.
*/
public void initializeAsync(final InitializationFinishedCallback finishedCallback) {
Async.go(new Runnable() {
@Override
public void run() {
try {
initialize();
finishedCallback.initializationFinished(OmemoManager.this);
} catch (Exception e) {
finishedCallback.initializationFailed(e);
}
}
});
}
/**
* Return a set of all OMEMO capable devices of a contact.
* Note, that this method does not explicitly refresh the device list of the contact, so it might be outdated.
*
* @see #requestDeviceListUpdateFor(BareJid)
*
* @param contact contact we want to get a set of device of.
* @return set of known devices of that contact.
*
* @throws IOException if an I/O error occurred.
*/
public Set<OmemoDevice> getDevicesOf(BareJid contact) throws IOException {
OmemoCachedDeviceList list = getOmemoService().getOmemoStoreBackend().loadCachedDeviceList(getOwnDevice(), contact);
HashSet<OmemoDevice> devices = new HashSet<>();
for (int deviceId : list.getActiveDevices()) {
devices.add(new OmemoDevice(contact, deviceId));
}
return devices;
}
/**
* OMEMO encrypt a cleartext message for a single recipient.
* Note that this method does NOT set the 'to' attribute of the message.
*
* @param recipient recipients bareJid
* @param message text to encrypt
* @return encrypted message
*
* @throws CryptoFailedException when something crypto related fails
* @throws UndecidedOmemoIdentityException When there are undecided devices
* @throws InterruptedException if the calling thread was interrupted.
* @throws SmackException.NotConnectedException if the XMPP connection is not connected.
* @throws SmackException.NoResponseException if there was no response from the remote entity.
* @throws SmackException.NotLoggedInException if the XMPP connection is not authenticated.
* @throws IOException if an I/O error occurred.
*/
public OmemoMessage.Sent encrypt(BareJid recipient, String message)
throws CryptoFailedException, UndecidedOmemoIdentityException,
InterruptedException, SmackException.NotConnectedException,
SmackException.NoResponseException, SmackException.NotLoggedInException, IOException {
Set<BareJid> recipients = new HashSet<>();
recipients.add(recipient);
return encrypt(recipients, message);
}
/**
* OMEMO encrypt a cleartext message for multiple recipients.
*
* @param recipients recipients barejids
* @param message text to encrypt
* @return encrypted message.
*
* @throws CryptoFailedException When something crypto related fails
* @throws UndecidedOmemoIdentityException When there are undecided devices.
* @throws InterruptedException if the calling thread was interrupted.
* @throws SmackException.NotConnectedException if the XMPP connection is not connected.
* @throws SmackException.NoResponseException if there was no response from the remote entity.
* @throws SmackException.NotLoggedInException if the XMPP connection is not authenticated.
* @throws IOException if an I/O error occurred.
*/
public synchronized OmemoMessage.Sent encrypt(Set<BareJid> recipients, String message)
throws CryptoFailedException, UndecidedOmemoIdentityException,
InterruptedException, SmackException.NotConnectedException,
SmackException.NoResponseException, SmackException.NotLoggedInException, IOException {
LoggedInOmemoManager guard = new LoggedInOmemoManager(this);
Set<OmemoDevice> devices = getDevicesOf(getOwnJid());
for (BareJid recipient : recipients) {
devices.addAll(getDevicesOf(recipient));
}
return service.createOmemoMessage(guard, devices, message);
}
/**
* Encrypt a message for all recipients in the MultiUserChat.
*
* @param muc multiUserChat
* @param message message to send
* @return encrypted message
*
* @throws UndecidedOmemoIdentityException when there are undecided devices.
* @throws CryptoFailedException if the OMEMO cryptography failed.
* @throws XMPPException.XMPPErrorException if there was an XMPP error returned.
* @throws SmackException.NotConnectedException if the XMPP connection is not connected.
* @throws InterruptedException if the calling thread was interrupted.
* @throws SmackException.NoResponseException if there was no response from the remote entity.
* @throws NoOmemoSupportException When the muc doesn't support OMEMO.
* @throws SmackException.NotLoggedInException if the XMPP connection is not authenticated.
* @throws IOException if an I/O error occurred.
*/
public synchronized OmemoMessage.Sent encrypt(MultiUserChat muc, String message)
throws UndecidedOmemoIdentityException, CryptoFailedException,
XMPPException.XMPPErrorException, SmackException.NotConnectedException, InterruptedException,
SmackException.NoResponseException, NoOmemoSupportException,
SmackException.NotLoggedInException, IOException {
if (!multiUserChatSupportsOmemo(muc)) {
throw new NoOmemoSupportException();
}
Set<BareJid> recipients = new HashSet<>();
for (EntityFullJid e : muc.getOccupants()) {
recipients.add(muc.getOccupant(e).getJid().asBareJid());
}
return encrypt(recipients, message);
}
/**
* Manually decrypt an OmemoElement.
* This method should only be used for use-cases, where the internal listeners don't pick up on an incoming message.
* (for example MAM query results).
*
* @param sender bareJid of the message sender (must be the jid of the contact who sent the message)
* @param omemoElement omemoElement
* @return decrypted OmemoMessage
*
* @throws SmackException.NotLoggedInException if the Manager is not authenticated
* @throws CorruptedOmemoKeyException if our or their key is corrupted
* @throws NoRawSessionException if the message was not a preKeyMessage, but we had no session with the contact
* @throws CryptoFailedException if decryption fails
* @throws IOException if an I/O error occurred.
*/
public OmemoMessage.Received decrypt(BareJid sender, OmemoElement omemoElement)
throws SmackException.NotLoggedInException, CorruptedOmemoKeyException, NoRawSessionException,
CryptoFailedException, IOException {
LoggedInOmemoManager managerGuard = new LoggedInOmemoManager(this);
return getOmemoService().decryptMessage(managerGuard, sender, omemoElement);
}
/**
* Decrypt messages from a MAM query.
*
* @param mamQuery The MAM query
* @return list of decrypted OmemoMessages
*
* @throws SmackException.NotLoggedInException if the Manager is not authenticated.
* @throws IOException if an I/O error occurred.
*/
public List<MessageOrOmemoMessage> decryptMamQueryResult(MamManager.MamQuery mamQuery)
throws SmackException.NotLoggedInException, IOException {
return new ArrayList<>(getOmemoService().decryptMamQueryResult(new LoggedInOmemoManager(this), mamQuery));
}
/**
* Trust that a fingerprint belongs to an OmemoDevice.
* The fingerprint must be the lowercase, hexadecimal fingerprint of the identityKey of the device and must
* be of length 64.
*
* @param device device
* @param fingerprint fingerprint
*/
public void trustOmemoIdentity(OmemoDevice device, OmemoFingerprint fingerprint) {
if (trustCallback == null) {
throw new IllegalStateException("No TrustCallback set.");
}
trustCallback.setTrust(device, fingerprint, TrustState.trusted);
}
/**
* Distrust the fingerprint/OmemoDevice tuple.
* The fingerprint must be the lowercase, hexadecimal fingerprint of the identityKey of the device and must
* be of length 64.
*
* @param device device
* @param fingerprint fingerprint
*/
public void distrustOmemoIdentity(OmemoDevice device, OmemoFingerprint fingerprint) {
if (trustCallback == null) {
throw new IllegalStateException("No TrustCallback set.");
}
trustCallback.setTrust(device, fingerprint, TrustState.untrusted);
}
/**
* Returns true, if the fingerprint/OmemoDevice tuple is trusted, otherwise false.
* The fingerprint must be the lowercase, hexadecimal fingerprint of the identityKey of the device and must
* be of length 64.
*
* @param device device
* @param fingerprint fingerprint
* @return <code>true</code> if this is a trusted OMEMO identity.
*/
public boolean isTrustedOmemoIdentity(OmemoDevice device, OmemoFingerprint fingerprint) {
if (trustCallback == null) {
throw new IllegalStateException("No TrustCallback set.");
}
return trustCallback.getTrust(device, fingerprint) == TrustState.trusted;
}
/**
* Returns true, if the fingerprint/OmemoDevice tuple is decided by the user.
* The fingerprint must be the lowercase, hexadecimal fingerprint of the identityKey of the device and must
* be of length 64.
*
* @param device device
* @param fingerprint fingerprint
* @return <code>true</code> if the trust is decided for the identity.
*/
public boolean isDecidedOmemoIdentity(OmemoDevice device, OmemoFingerprint fingerprint) {
if (trustCallback == null) {
throw new IllegalStateException("No TrustCallback set.");
}
return trustCallback.getTrust(device, fingerprint) != TrustState.undecided;
}
/**
* Send a ratchet update message. This can be used to advance the ratchet of a session in order to maintain forward
* secrecy.
*
* @param recipient recipient
*
* @throws CorruptedOmemoKeyException When the used identityKeys are corrupted
* @throws CryptoFailedException When something fails with the crypto
* @throws CannotEstablishOmemoSessionException When we can't establish a session with the recipient
* @throws SmackException.NotLoggedInException if the XMPP connection is not authenticated.
* @throws InterruptedException if the calling thread was interrupted.
* @throws SmackException.NoResponseException if there was no response from the remote entity.
* @throws NoSuchAlgorithmException if no such algorithm is available.
* @throws SmackException.NotConnectedException if the XMPP connection is not connected.
* @throws IOException if an I/O error occurred.
*/
public synchronized void sendRatchetUpdateMessage(OmemoDevice recipient)
throws SmackException.NotLoggedInException, CorruptedOmemoKeyException, InterruptedException,
SmackException.NoResponseException, NoSuchAlgorithmException, SmackException.NotConnectedException,
CryptoFailedException, CannotEstablishOmemoSessionException, IOException {
XMPPConnection connection = connection();
MessageBuilder message = connection.getStanzaFactory()
.buildMessageStanza()
.to(recipient.getJid());
OmemoElement element = getOmemoService().createRatchetUpdateElement(new LoggedInOmemoManager(this), recipient);
message.addExtension(element);
// Set MAM Storage hint
StoreHint.set(message);
connection.sendStanza(message.build());
}
/**
* Returns true, if the contact has any active devices published in a deviceList.
*
* @param contact contact
* @return true if contact has at least one OMEMO capable device.
*
* @throws SmackException.NotConnectedException if the XMPP connection is not connected.
* @throws InterruptedException if the calling thread was interrupted.
* @throws SmackException.NoResponseException if there was no response from the remote entity.
* @throws PubSubException.NotALeafNodeException if a PubSub leaf node operation was attempted on a non-leaf node.
* @throws XMPPException.XMPPErrorException if there was an XMPP error returned.
* @throws IOException if an I/O error occurred.
*/
public synchronized boolean contactSupportsOmemo(BareJid contact)
throws InterruptedException, PubSubException.NotALeafNodeException, XMPPException.XMPPErrorException,
SmackException.NotConnectedException, SmackException.NoResponseException, IOException {
OmemoCachedDeviceList deviceList = getOmemoService().refreshDeviceList(connection(), getOwnDevice(), contact);
return !deviceList.getActiveDevices().isEmpty();
}
/**
* Returns true, if the MUC with the EntityBareJid multiUserChat is non-anonymous and members only (prerequisite
* for OMEMO encryption in MUC).
*
* @param multiUserChat MUC
* @return true if chat supports OMEMO
*
* @throws XMPPException.XMPPErrorException if there was an XMPP protocol level error
* @throws SmackException.NotConnectedException if the connection is not connected
* @throws InterruptedException if the thread is interrupted
* @throws SmackException.NoResponseException if the server does not respond
*/
public boolean multiUserChatSupportsOmemo(MultiUserChat multiUserChat)
throws XMPPException.XMPPErrorException, SmackException.NotConnectedException, InterruptedException,
SmackException.NoResponseException {
EntityBareJid jid = multiUserChat.getRoom();
RoomInfo roomInfo = MultiUserChatManager.getInstanceFor(connection()).getRoomInfo(jid);
return roomInfo.isNonanonymous() && roomInfo.isMembersOnly();
}
/**
* Returns true, if the Server supports PEP.
*
* @param connection XMPPConnection
* @param server domainBareJid of the server to test
* @return true if server supports pep
*
* @throws XMPPException.XMPPErrorException if there was an XMPP error returned.
* @throws SmackException.NotConnectedException if the XMPP connection is not connected.
* @throws InterruptedException if the calling thread was interrupted.
* @throws SmackException.NoResponseException if there was no response from the remote entity.
*/
public static boolean serverSupportsOmemo(XMPPConnection connection, DomainBareJid server)
throws XMPPException.XMPPErrorException, SmackException.NotConnectedException, InterruptedException,
SmackException.NoResponseException {
return ServiceDiscoveryManager.getInstanceFor(connection)
.discoverInfo(server).containsFeature(PubSub.NAMESPACE);
}
/**
* Return the fingerprint of our identity key.
*
* @return our own OMEMO fingerprint
*
* @throws SmackException.NotLoggedInException if we don't know our bareJid yet.
* @throws CorruptedOmemoKeyException if our identityKey is corrupted.
* @throws IOException if an I/O error occurred.
*/
public synchronized OmemoFingerprint getOwnFingerprint()
throws SmackException.NotLoggedInException, CorruptedOmemoKeyException, IOException {
if (getOwnJid() == null) {
throw new SmackException.NotLoggedInException();
}
return getOmemoService().getOmemoStoreBackend().getFingerprint(getOwnDevice());
}
/**
* Get the fingerprint of a contacts device.
*
* @param device contacts OmemoDevice
* @return fingerprint of the given OMEMO device.
*
* @throws CannotEstablishOmemoSessionException if we have no session yet, and are unable to create one.
* @throws SmackException.NotLoggedInException if the XMPP connection is not authenticated.
* @throws CorruptedOmemoKeyException if the copy of the fingerprint we have is corrupted.
* @throws SmackException.NotConnectedException if the XMPP connection is not connected.
* @throws InterruptedException if the calling thread was interrupted.
* @throws SmackException.NoResponseException if there was no response from the remote entity.
* @throws IOException if an I/O error occurred.
*/
public synchronized OmemoFingerprint getFingerprint(OmemoDevice device)
throws CannotEstablishOmemoSessionException, SmackException.NotLoggedInException,
CorruptedOmemoKeyException, SmackException.NotConnectedException, InterruptedException,
SmackException.NoResponseException, IOException {
if (getOwnJid() == null) {
throw new SmackException.NotLoggedInException();
}
if (device.equals(getOwnDevice())) {
return getOwnFingerprint();
}
return getOmemoService().getOmemoStoreBackend()
.getFingerprintAndMaybeBuildSession(new LoggedInOmemoManager(this), device);
}
/**
* Return all OmemoFingerprints of active devices of a contact.
* TODO: Make more fail-safe
*
* @param contact contact
* @return Map of all active devices of the contact and their fingerprints.
*
* @throws SmackException.NotLoggedInException if the XMPP connection is not authenticated.
* @throws CorruptedOmemoKeyException if the OMEMO key is corrupted.
* @throws CannotEstablishOmemoSessionException if no OMEMO session could be established.
* @throws SmackException.NotConnectedException if the XMPP connection is not connected.
* @throws InterruptedException if the calling thread was interrupted.
* @throws SmackException.NoResponseException if there was no response from the remote entity.
* @throws IOException if an I/O error occurred.
*/
public synchronized HashMap<OmemoDevice, OmemoFingerprint> getActiveFingerprints(BareJid contact)
throws SmackException.NotLoggedInException, CorruptedOmemoKeyException,
CannotEstablishOmemoSessionException, SmackException.NotConnectedException, InterruptedException,
SmackException.NoResponseException, IOException {
if (getOwnJid() == null) {
throw new SmackException.NotLoggedInException();
}
HashMap<OmemoDevice, OmemoFingerprint> fingerprints = new HashMap<>();
OmemoCachedDeviceList deviceList = getOmemoService().getOmemoStoreBackend().loadCachedDeviceList(getOwnDevice(),
contact);
for (int id : deviceList.getActiveDevices()) {
OmemoDevice device = new OmemoDevice(contact, id);
OmemoFingerprint fingerprint = getFingerprint(device);
if (fingerprint != null) {
fingerprints.put(device, fingerprint);
}
}
return fingerprints;
}
/**
* Add an OmemoMessageListener. This listener will be informed about incoming OMEMO messages
* (as well as KeyTransportMessages) and OMEMO encrypted message carbons.
*
* @param listener OmemoMessageListener
*/
public void addOmemoMessageListener(OmemoMessageListener listener) {
omemoMessageListeners.add(listener);
}
/**
* Remove an OmemoMessageListener.
*
* @param listener OmemoMessageListener
*/
public void removeOmemoMessageListener(OmemoMessageListener listener) {
omemoMessageListeners.remove(listener);
}
/**
* Add an OmemoMucMessageListener. This listener will be informed about incoming OMEMO encrypted MUC messages.
*
* @param listener OmemoMessageListener.
*/
public void addOmemoMucMessageListener(OmemoMucMessageListener listener) {
omemoMucMessageListeners.add(listener);
}
/**
* Remove an OmemoMucMessageListener.
*
* @param listener OmemoMucMessageListener
*/
public void removeOmemoMucMessageListener(OmemoMucMessageListener listener) {
omemoMucMessageListeners.remove(listener);
}
/**
* Request a deviceList update from contact contact.
*
* @param contact contact we want to obtain the deviceList from.
*
* @throws InterruptedException if the calling thread was interrupted.
* @throws PubSubException.NotALeafNodeException if a PubSub leaf node operation was attempted on a non-leaf node.
* @throws XMPPException.XMPPErrorException if there was an XMPP error returned.
* @throws SmackException.NotConnectedException if the XMPP connection is not connected.
* @throws SmackException.NoResponseException if there was no response from the remote entity.
* @throws IOException if an I/O error occurred.
*/
public synchronized void requestDeviceListUpdateFor(BareJid contact)
throws InterruptedException, PubSubException.NotALeafNodeException, XMPPException.XMPPErrorException,
SmackException.NotConnectedException, SmackException.NoResponseException, IOException {
getOmemoService().refreshDeviceList(connection(), getOwnDevice(), contact);
}
/**
* Publish a new device list with just our own deviceId in it.
*
* @throws SmackException.NotLoggedInException if the XMPP connection is not authenticated.
* @throws InterruptedException if the calling thread was interrupted.
* @throws XMPPException.XMPPErrorException if there was an XMPP error returned.
* @throws SmackException.NotConnectedException if the XMPP connection is not connected.
* @throws SmackException.NoResponseException if there was no response from the remote entity.
* @throws IOException if an I/O error occurred.
* @throws PubSubException.NotALeafNodeException if a PubSub leaf node operation was attempted on a non-leaf node.
*/
public void purgeDeviceList()
throws SmackException.NotLoggedInException, InterruptedException, XMPPException.XMPPErrorException,
SmackException.NotConnectedException, SmackException.NoResponseException, IOException, PubSubException.NotALeafNodeException {
getOmemoService().purgeDeviceList(new LoggedInOmemoManager(this));
}
public List<Exception> purgeEverything() throws NotConnectedException, InterruptedException, IOException {
List<Exception> exceptions = new ArrayList<>(5);
PubSubManager pm = PubSubManager.getInstanceFor(getConnection(), getOwnJid());
try {
requestDeviceListUpdateFor(getOwnJid());
} catch (SmackException.NoResponseException | PubSubException.NotALeafNodeException
| XMPPException.XMPPErrorException e) {
exceptions.add(e);
}
OmemoCachedDeviceList deviceList = OmemoService.getInstance().getOmemoStoreBackend()
.loadCachedDeviceList(getOwnDevice(), getOwnJid());
for (int id : deviceList.getAllDevices()) {
try {
pm.getLeafNode(OmemoConstants.PEP_NODE_BUNDLE_FROM_DEVICE_ID(id)).deleteAllItems();
} catch (SmackException.NoResponseException | PubSubException.NotALeafNodeException
| XMPPException.XMPPErrorException | PubSubException.NotAPubSubNodeException e) {
exceptions.add(e);
}
try {
pm.deleteNode(OmemoConstants.PEP_NODE_BUNDLE_FROM_DEVICE_ID(id));
} catch (SmackException.NoResponseException | XMPPException.XMPPErrorException e) {
exceptions.add(e);
}
}
try {
pm.getLeafNode(OmemoConstants.PEP_NODE_DEVICE_LIST).deleteAllItems();
} catch (SmackException.NoResponseException | PubSubException.NotALeafNodeException
| XMPPException.XMPPErrorException | PubSubException.NotAPubSubNodeException e) {
exceptions.add(e);
}
try {
pm.deleteNode(OmemoConstants.PEP_NODE_DEVICE_LIST);
} catch (SmackException.NoResponseException | XMPPException.XMPPErrorException e) {
exceptions.add(e);
}
return exceptions;
}
/**
* Rotate the signedPreKey published in our OmemoBundle and republish it. This should be done every now and
* then (7-14 days). The old signedPreKey should be kept for some more time (a month or so) to enable decryption
* of messages that have been sent since the key was changed.
*
* @throws CorruptedOmemoKeyException When the IdentityKeyPair is damaged.
* @throws InterruptedException XMPP error
* @throws XMPPException.XMPPErrorException XMPP error
* @throws SmackException.NotConnectedException XMPP error
* @throws SmackException.NoResponseException XMPP error
* @throws SmackException.NotLoggedInException if the XMPP connection is not authenticated.
* @throws IOException if an I/O error occurred.
* @throws PubSubException.NotALeafNodeException if a PubSub leaf node operation was attempted on a non-leaf node.
*/
public synchronized void rotateSignedPreKey()
throws CorruptedOmemoKeyException, SmackException.NotLoggedInException, XMPPException.XMPPErrorException,
SmackException.NotConnectedException, InterruptedException, SmackException.NoResponseException,
IOException, PubSubException.NotALeafNodeException {
if (!connection().isAuthenticated()) {
throw new SmackException.NotLoggedInException();
}
// generate key
getOmemoService().getOmemoStoreBackend().changeSignedPreKey(getOwnDevice());
// publish
OmemoBundleElement bundle = getOmemoService().getOmemoStoreBackend().packOmemoBundle(getOwnDevice());
OmemoService.publishBundle(connection(), getOwnDevice(), bundle);
}
/**
* Return true, if the given Stanza contains an OMEMO element 'encrypted'.
*
* @param stanza stanza
* @return true if stanza has extension 'encrypted'
*/
static boolean stanzaContainsOmemoElement(Stanza stanza) {
return stanza.hasExtension(OmemoElement.NAME_ENCRYPTED, OMEMO_NAMESPACE_V_AXOLOTL);
}
/**
* Throw an IllegalStateException if no OmemoService is set.
*/
private void throwIfNoServiceSet() {
if (service == null) {
throw new IllegalStateException("No OmemoService set in OmemoManager.");
}
}
/**
* Returns a pseudo random number from the interval [1, Integer.MAX_VALUE].
*
* @return a random deviceId.
*/
public static int randomDeviceId() {
return new Random().nextInt(Integer.MAX_VALUE - 1) + 1;
}
/**
* Return the BareJid of the user.
*
* @return our own bare JID.
*/
public BareJid getOwnJid() {
if (ownJid == null && connection().isAuthenticated()) {
ownJid = connection().getUser().asBareJid();
}
return ownJid;
}
/**
* Return the deviceId of this OmemoManager.
*
* @return this OmemoManagers deviceId.
*/
public synchronized Integer getDeviceId() {
return deviceId;
}
/**
* Return the OmemoDevice of the user.
*
* @return our own OmemoDevice
*/
public synchronized OmemoDevice getOwnDevice() {
BareJid jid = getOwnJid();
if (jid == null) {
return null;
}
return new OmemoDevice(jid, getDeviceId());
}
/**
* Set the deviceId of the manager to nDeviceId.
*
* @param nDeviceId new deviceId
*/
synchronized void setDeviceId(int nDeviceId) {
// Move this instance inside the HashMaps
INSTANCES.get(connection()).remove(getDeviceId());
INSTANCES.get(connection()).put(nDeviceId, this);
this.deviceId = nDeviceId;
}
/**
* Notify all registered OmemoMessageListeners about a received OmemoMessage.
*
* @param stanza original stanza
* @param decryptedMessage decrypted OmemoMessage.
*/
void notifyOmemoMessageReceived(Stanza stanza, OmemoMessage.Received decryptedMessage) {
for (OmemoMessageListener l : omemoMessageListeners) {
l.onOmemoMessageReceived(stanza, decryptedMessage);
}
}
/**
* Notify all registered OmemoMucMessageListeners of an incoming OmemoMessageElement in a MUC.
*
* @param muc MultiUserChat the message was received in.
* @param stanza Original Stanza.
* @param decryptedMessage Decrypted OmemoMessage.
*/
void notifyOmemoMucMessageReceived(MultiUserChat muc,
Stanza stanza,
OmemoMessage.Received decryptedMessage) {
for (OmemoMucMessageListener l : omemoMucMessageListeners) {
l.onOmemoMucMessageReceived(muc, stanza, decryptedMessage);
}
}
/**
* Notify all registered OmemoMessageListeners of an incoming OMEMO encrypted Carbon Copy.
* Remember: If you want to receive OMEMO encrypted carbon copies, you have to enable carbons using
* {@link CarbonManager#enableCarbons()}.
*
* @param direction direction of the carbon copy
* @param carbonCopy carbon copy itself
* @param wrappingMessage wrapping message
* @param decryptedCarbonCopy decrypted carbon copy OMEMO element
*/
void notifyOmemoCarbonCopyReceived(CarbonExtension.Direction direction,
Message carbonCopy,
Message wrappingMessage,
OmemoMessage.Received decryptedCarbonCopy) {
for (OmemoMessageListener l : omemoMessageListeners) {
l.onOmemoCarbonCopyReceived(direction, carbonCopy, wrappingMessage, decryptedCarbonCopy);
}
}
/**
* Register stanza listeners needed for OMEMO.
* This method is called automatically in the constructor and should only be used to restore the previous state
* after {@link #stopStanzaAndPEPListeners()} was called.
*/
public void resumeStanzaAndPEPListeners() {
CarbonManager carbonManager = CarbonManager.getInstanceFor(connection());
// Remove listeners to avoid them getting added twice
connection().removeAsyncStanzaListener(this::internalOmemoMessageStanzaListener);
carbonManager.removeCarbonCopyReceivedListener(this::internalOmemoCarbonCopyListener);
// Add listeners
pepManager.addPepEventListener(OmemoConstants.PEP_NODE_DEVICE_LIST, OmemoDeviceListElement.class, pepOmemoDeviceListEventListener);
connection().addAsyncStanzaListener(this::internalOmemoMessageStanzaListener, OmemoManager::isOmemoMessage);
carbonManager.addCarbonCopyReceivedListener(this::internalOmemoCarbonCopyListener);
}
/**
* Remove active stanza listeners needed for OMEMO.
*/
public void stopStanzaAndPEPListeners() {
pepManager.removePepEventListener(pepOmemoDeviceListEventListener);
connection().removeAsyncStanzaListener(this::internalOmemoMessageStanzaListener);
CarbonManager.getInstanceFor(connection()).removeCarbonCopyReceivedListener(this::internalOmemoCarbonCopyListener);
}
/**
* Build a fresh session with a contacts device.
* This might come in handy if a session is broken.
*
* @param contactsDevice OmemoDevice of a contact.
*
* @throws InterruptedException if the calling thread was interrupted.
* @throws SmackException.NoResponseException if there was no response from the remote entity.
* @throws CorruptedOmemoKeyException if our or their identityKey is corrupted.
* @throws SmackException.NotConnectedException if the XMPP connection is not connected.
* @throws CannotEstablishOmemoSessionException if no new session can be established.
* @throws SmackException.NotLoggedInException if the connection is not authenticated.
*/
public void rebuildSessionWith(OmemoDevice contactsDevice)
throws InterruptedException, SmackException.NoResponseException, CorruptedOmemoKeyException,
SmackException.NotConnectedException, CannotEstablishOmemoSessionException,
SmackException.NotLoggedInException {
if (!connection().isAuthenticated()) {
throw new SmackException.NotLoggedInException();
}
getOmemoService().buildFreshSessionWithDevice(connection(), getOwnDevice(), contactsDevice);
}
/**
* Get our connection.
*
* @return the connection of this manager
*/
XMPPConnection getConnection() {
return connection();
}
/**
* Return the OMEMO service object.
*
* @return the OmemoService object related to this OmemoManager.
*/
OmemoService<?, ?, ?, ?, ?, ?, ?, ?, ?> getOmemoService() {
throwIfNoServiceSet();
return service;
}
/**
* StanzaListener that listens for incoming Stanzas which contain OMEMO elements.
*/
private void internalOmemoMessageStanzaListener(final Stanza packet) {
Async.go(new Runnable() {
@Override
public void run() {
try {
getOmemoService().onOmemoMessageStanzaReceived(packet,
new LoggedInOmemoManager(OmemoManager.this));
} catch (SmackException.NotLoggedInException | IOException e) {
LOGGER.log(Level.SEVERE, "Exception while processing OMEMO stanza", e);
}
}
});
}
/**
* CarbonCopyListener that listens for incoming carbon copies which contain OMEMO elements.
*/
private void internalOmemoCarbonCopyListener(final CarbonExtension.Direction direction,
final Message carbonCopy,
final Message wrappingMessage) {
Async.go(new Runnable() {
@Override
public void run() {
if (isOmemoMessage(carbonCopy)) {
try {
getOmemoService().onOmemoCarbonCopyReceived(direction, carbonCopy, wrappingMessage,
new LoggedInOmemoManager(OmemoManager.this));
} catch (SmackException.NotLoggedInException | IOException e) {
LOGGER.log(Level.SEVERE, "Exception while processing OMEMO stanza", e);
}
}
}
});
}
@SuppressWarnings("UnnecessaryLambda")
private final PepEventListener<OmemoDeviceListElement> pepOmemoDeviceListEventListener =
(from, receivedDeviceList, id, message) -> {
// Device List <list>
OmemoCachedDeviceList deviceList;
try {
getOmemoService().getOmemoStoreBackend().mergeCachedDeviceList(getOwnDevice(), from,
receivedDeviceList);
if (!from.asBareJid().equals(getOwnJid())) {
return;
}
deviceList = getOmemoService().cleanUpDeviceList(getOwnDevice());
} catch (IOException e) {
LOGGER.log(Level.SEVERE,
"IOException while processing OMEMO PEP device updates. Message: " + message,
e);
return;
}
final OmemoDeviceListElement_VAxolotl newDeviceList = new OmemoDeviceListElement_VAxolotl(deviceList);
if (!newDeviceList.copyDeviceIds().equals(receivedDeviceList.copyDeviceIds())) {
LOGGER.log(Level.FINE, "Republish deviceList due to changes:" +
" Received: " + Arrays.toString(receivedDeviceList.copyDeviceIds().toArray()) +
" Published: " + Arrays.toString(newDeviceList.copyDeviceIds().toArray()));
Async.go(new Runnable() {
@Override
public void run() {
try {
OmemoService.publishDeviceList(connection(), newDeviceList);
} catch (InterruptedException | XMPPException.XMPPErrorException |
SmackException.NotConnectedException | SmackException.NoResponseException | PubSubException.NotALeafNodeException e) {
LOGGER.log(Level.WARNING, "Could not publish our deviceList upon an received update.", e);
}
}
});
}
};
/**
* StanzaFilter that filters messages containing a OMEMO element.
*/
private static boolean isOmemoMessage(Stanza stanza) {
return stanza instanceof Message && OmemoManager.stanzaContainsOmemoElement(stanza);
}
/**
* Guard class which ensures that the wrapped OmemoManager knows its BareJid.
*/
public static class LoggedInOmemoManager {
private final OmemoManager manager;
public LoggedInOmemoManager(OmemoManager manager)
throws SmackException.NotLoggedInException {
if (manager == null) {
throw new IllegalArgumentException("OmemoManager cannot be null.");
}
if (manager.getOwnJid() == null) {
if (manager.getConnection().isAuthenticated()) {
manager.ownJid = manager.getConnection().getUser().asBareJid();
} else {
throw new SmackException.NotLoggedInException();
}
}
this.manager = manager;
}
public OmemoManager get() {
return manager;
}
}
/**
* Callback which can be used to get notified, when the OmemoManager finished initializing.
*/
public interface InitializationFinishedCallback {
void initializationFinished(OmemoManager manager);
void initializationFailed(Exception cause);
}
/**
* Get the bareJid of the user from the authenticated XMPP connection.
* If our deviceId is unknown, use the bareJid to look up deviceIds available in the omemoStore.
* If there are ids available, choose the smallest one. Otherwise generate a random deviceId.
*
* @param manager OmemoManager
*/
private static void initBareJidAndDeviceId(OmemoManager manager) {
if (!manager.getConnection().isAuthenticated()) {
throw new IllegalStateException("Connection MUST be authenticated.");
}
if (manager.ownJid == null) {
manager.ownJid = manager.getConnection().getUser().asBareJid();
}
if (UNKNOWN_DEVICE_ID.equals(manager.deviceId)) {
SortedSet<Integer> storedDeviceIds = manager.getOmemoService().getOmemoStoreBackend().localDeviceIdsOf(manager.ownJid);
if (storedDeviceIds.size() > 0) {
manager.setDeviceId(storedDeviceIds.first());
} else {
manager.setDeviceId(randomDeviceId());
}
}
}
}
| igniterealtime/Smack | smack-omemo/src/main/java/org/jivesoftware/smackx/omemo/OmemoManager.java | Java | apache-2.0 | 49,782 |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.support.vectordrawable.app;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.vectordrawable.graphics.drawable.SeekableAnimatedVectorDrawable;
import com.example.android.support.vectordrawable.R;
/**
* Demonstrates usage of {@link SeekableAnimatedVectorDrawable}.
*/
public class SeekableDemo extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.seekable_demo);
final ImageView image = findViewById(R.id.image);
final Button start = findViewById(R.id.start);
final Button stop = findViewById(R.id.stop);
final SeekBar seekBar = findViewById(R.id.seek);
final SeekableAnimatedVectorDrawable avd =
SeekableAnimatedVectorDrawable.create(this, R.drawable.ic_hourglass_animation);
if (avd == null) {
finish();
return;
}
avd.registerAnimationCallback(new SeekableAnimatedVectorDrawable.AnimationCallback() {
@Override
public void onAnimationStart(@NonNull SeekableAnimatedVectorDrawable drawable) {
onAnimationRunning();
}
@Override
public void onAnimationEnd(@NonNull SeekableAnimatedVectorDrawable drawable) {
start.setEnabled(true);
start.setText(R.string.start);
stop.setEnabled(false);
seekBar.setProgress(0);
}
@Override
public void onAnimationPause(@NonNull SeekableAnimatedVectorDrawable drawable) {
start.setEnabled(true);
start.setText(R.string.resume);
stop.setEnabled(true);
}
@Override
public void onAnimationResume(@NonNull SeekableAnimatedVectorDrawable drawable) {
onAnimationRunning();
}
private void onAnimationRunning() {
start.setEnabled(true);
start.setText(R.string.pause);
stop.setEnabled(true);
}
@Override
public void onAnimationUpdate(@NonNull SeekableAnimatedVectorDrawable drawable) {
seekBar.setProgress((int) drawable.getCurrentPlayTime());
}
});
image.setImageDrawable(avd);
seekBar.setMax((int) avd.getTotalDuration());
start.setOnClickListener((v) -> {
if (!avd.isRunning()) {
avd.start();
} else if (!avd.isPaused()) {
avd.pause();
} else {
avd.resume();
}
});
stop.setOnClickListener((v) -> avd.stop());
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
avd.setCurrentPlayTime(progress);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
}
| AndroidX/androidx | vectordrawable/integration-tests/testapp/src/main/java/com/example/android/support/vectordrawable/app/SeekableDemo.java | Java | apache-2.0 | 4,134 |
/*
* 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.harmony.sql.tests.javax.sql.rowset.serial;
import javax.sql.rowset.serial.SerialException;
import junit.framework.TestCase;
import org.apache.harmony.testframework.serialization.SerializationTest;
public class SerialExceptionTest extends TestCase {
/**
* @tests serialization/deserialization compatibility.
*/
public void testSerializationSelf() throws Exception {
SerializationTest.verifySelf(new SerialException());
}
/**
* @tests serialization/deserialization compatibility with RI.
*/
public void testSerializationCompatibility() throws Exception {
SerializationTest.verifyGolden(this, new SerialException());
}
}
| freeVM/freeVM | enhanced/java/classlib/modules/sql/src/test/java/org/apache/harmony/sql/tests/javax/sql/rowset/serial/SerialExceptionTest.java | Java | apache-2.0 | 1,516 |
/*
* Copyright 2020 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.domain.materials.scm;
import com.thoughtworks.go.config.materials.PluggableSCMMaterial;
import com.thoughtworks.go.domain.MaterialRevision;
import com.thoughtworks.go.domain.config.Configuration;
import com.thoughtworks.go.domain.config.ConfigurationProperty;
import com.thoughtworks.go.domain.materials.MaterialAgent;
import com.thoughtworks.go.domain.materials.Modification;
import com.thoughtworks.go.domain.scm.SCM;
import com.thoughtworks.go.plugin.access.scm.SCMExtension;
import com.thoughtworks.go.plugin.access.scm.SCMProperty;
import com.thoughtworks.go.plugin.access.scm.SCMPropertyConfiguration;
import com.thoughtworks.go.plugin.access.scm.revision.SCMRevision;
import com.thoughtworks.go.plugin.api.response.Result;
import com.thoughtworks.go.util.command.ConsoleOutputStreamConsumer;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import static com.thoughtworks.go.util.command.TaggedStreamConsumer.PREP_ERR;
public class PluggableSCMMaterialAgent implements MaterialAgent {
private SCMExtension scmExtension;
private MaterialRevision revision;
private File workingDirectory;
private final ConsoleOutputStreamConsumer consumer;
public PluggableSCMMaterialAgent(SCMExtension scmExtension,
MaterialRevision revision,
File workingDirectory,
ConsoleOutputStreamConsumer consumer) {
this.scmExtension = scmExtension;
this.revision = revision;
this.workingDirectory = workingDirectory;
this.consumer = consumer;
}
@Override
public void prepare() {
try {
PluggableSCMMaterial material = (PluggableSCMMaterial) revision.getMaterial();
Modification latestModification = revision.getLatestModification();
SCMRevision scmRevision = new SCMRevision(latestModification.getRevision(), latestModification.getModifiedTime(), null, null, latestModification.getAdditionalDataMap(), null);
File destinationFolder = material.workingDirectory(workingDirectory);
Result result = scmExtension.checkout(material.getScmConfig().getPluginConfiguration().getId(), buildSCMPropertyConfigurations(material.getScmConfig()), destinationFolder.getAbsolutePath(), scmRevision);
handleCheckoutResult(material, result);
} catch (Exception e) {
consumer.taggedErrOutput(PREP_ERR, String.format("Material %s checkout failed: %s", revision.getMaterial().getDisplayName(), e.getMessage()));
throw e;
}
}
private void handleCheckoutResult(PluggableSCMMaterial material, Result result) {
if (result.isSuccessful()) {
if (StringUtils.isNotBlank(result.getMessagesForDisplay())) {
consumer.stdOutput(result.getMessagesForDisplay());
}
} else {
consumer.taggedErrOutput(PREP_ERR, String.format("Material %s checkout failed: %s", material.getDisplayName(), result.getMessagesForDisplay()));
throw new RuntimeException(String.format("Material %s checkout failed: %s", material.getDisplayName(), result.getMessagesForDisplay()));
}
}
private SCMPropertyConfiguration buildSCMPropertyConfigurations(SCM scmConfig) {
SCMPropertyConfiguration scmPropertyConfiguration = new SCMPropertyConfiguration();
populateConfiguration(scmConfig.getConfiguration(), scmPropertyConfiguration);
return scmPropertyConfiguration;
}
private void populateConfiguration(Configuration configuration,
com.thoughtworks.go.plugin.api.config.Configuration pluginConfiguration) {
for (ConfigurationProperty configurationProperty : configuration) {
pluginConfiguration.add(new SCMProperty(configurationProperty.getConfigurationKey().getName(), configurationProperty.getValue()));
}
}
}
| arvindsv/gocd | common/src/main/java/com/thoughtworks/go/domain/materials/scm/PluggableSCMMaterialAgent.java | Java | apache-2.0 | 4,585 |
/**
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. See accompanying LICENSE file.
*/
package org.apache.oozie.service;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.oozie.CoordinatorActionBean;
import org.apache.oozie.ErrorCode;
import org.apache.oozie.WorkflowActionBean;
import org.apache.oozie.command.CommandException;
import org.apache.oozie.command.coord.CoordActionCheckCommand;
import org.apache.oozie.command.coord.CoordActionCheckXCommand;
import org.apache.oozie.command.wf.ActionCheckCommand;
import org.apache.oozie.command.wf.ActionCheckXCommand;
import org.apache.oozie.executor.jpa.CoordActionsRunningGetJPAExecutor;
import org.apache.oozie.executor.jpa.JPAExecutorException;
import org.apache.oozie.executor.jpa.WorkflowActionsRunningGetJPAExecutor;
import org.apache.oozie.util.XCallable;
import org.apache.oozie.util.XLog;
/**
* The Action Checker Service queue ActionCheckCommands to check the status of
* running actions and CoordActionCheckCommands to check the status of
* coordinator actions. The delay between checks on the same action can be
* configured.
*/
public class ActionCheckerService implements Service {
public static final String CONF_PREFIX = Service.CONF_PREFIX + "ActionCheckerService.";
/**
* The frequency at which the ActionCheckService will run.
*/
public static final String CONF_ACTION_CHECK_INTERVAL = CONF_PREFIX + "action.check.interval";
/**
* The time, in seconds, between an ActionCheck for the same action.
*/
public static final String CONF_ACTION_CHECK_DELAY = CONF_PREFIX + "action.check.delay";
/**
* The number of callables to be queued in a batch.
*/
public static final String CONF_CALLABLE_BATCH_SIZE = CONF_PREFIX + "callable.batch.size";
protected static final String INSTRUMENTATION_GROUP = "actionchecker";
protected static final String INSTR_CHECK_ACTIONS_COUNTER = "checks_wf_actions";
protected static final String INSTR_CHECK_COORD_ACTIONS_COUNTER = "checks_coord_actions";
private static boolean useXCommand = true;
/**
* {@link ActionCheckRunnable} is the runnable which is scheduled to run and
* queue Action checks.
*/
static class ActionCheckRunnable implements Runnable {
private int actionCheckDelay;
private List<XCallable<Void>> callables;
private StringBuilder msg = null;
public ActionCheckRunnable(int actionCheckDelay) {
this.actionCheckDelay = actionCheckDelay;
}
public void run() {
XLog.Info.get().clear();
XLog LOG = XLog.getLog(getClass());
msg = new StringBuilder();
try {
runWFActionCheck();
runCoordActionCheck();
}
catch (CommandException ce) {
LOG.error("Unable to run action checks, ", ce);
}
LOG.debug("QUEUING [{0}] for potential checking", msg.toString());
if (null != callables) {
boolean ret = Services.get().get(CallableQueueService.class).queueSerial(callables);
if (ret == false) {
LOG.warn("Unable to queue the callables commands for CheckerService. "
+ "Most possibly command queue is full. Queue size is :"
+ Services.get().get(CallableQueueService.class).queueSize());
}
callables = null;
}
}
/**
* check workflow actions
*
* @throws CommandException
*/
private void runWFActionCheck() throws CommandException {
JPAService jpaService = Services.get().get(JPAService.class);
if (jpaService == null) {
throw new CommandException(ErrorCode.E0610);
}
List<WorkflowActionBean> actions;
try {
actions = jpaService
.execute(new WorkflowActionsRunningGetJPAExecutor(actionCheckDelay));
}
catch (JPAExecutorException je) {
throw new CommandException(je);
}
if (actions == null || actions.size() == 0) {
return;
}
msg.append(" WF_ACTIONS : " + actions.size());
for (WorkflowActionBean action : actions) {
Services.get().get(InstrumentationService.class).get().incr(INSTRUMENTATION_GROUP,
INSTR_CHECK_ACTIONS_COUNTER, 1);
if (useXCommand) {
queueCallable(new ActionCheckXCommand(action.getId()));
}
else {
queueCallable(new ActionCheckCommand(action.getId()));
}
}
}
/**
* check coordinator actions
*
* @throws CommandException
*/
private void runCoordActionCheck() throws CommandException {
JPAService jpaService = Services.get().get(JPAService.class);
if (jpaService == null) {
throw new CommandException(ErrorCode.E0610);
}
List<CoordinatorActionBean> cactions;
try {
cactions = jpaService.execute(new CoordActionsRunningGetJPAExecutor(
actionCheckDelay));
}
catch (JPAExecutorException je) {
throw new CommandException(je);
}
if (cactions == null || cactions.size() == 0) {
return;
}
msg.append(" COORD_ACTIONS : " + cactions.size());
for (CoordinatorActionBean caction : cactions) {
Services.get().get(InstrumentationService.class).get().incr(INSTRUMENTATION_GROUP,
INSTR_CHECK_COORD_ACTIONS_COUNTER, 1);
if (useXCommand) {
queueCallable(new CoordActionCheckXCommand(caction.getId(), actionCheckDelay));
}
else {
queueCallable(new CoordActionCheckCommand(caction.getId(), actionCheckDelay));
}
}
}
/**
* Adds callables to a list. If the number of callables in the list
* reaches {@link ActionCheckerService#CONF_CALLABLE_BATCH_SIZE}, the
* entire batch is queued and the callables list is reset.
*
* @param callable the callable to queue.
*/
private void queueCallable(XCallable<Void> callable) {
if (callables == null) {
callables = new ArrayList<XCallable<Void>>();
}
callables.add(callable);
if (callables.size() == Services.get().getConf().getInt(CONF_CALLABLE_BATCH_SIZE, 10)) {
boolean ret = Services.get().get(CallableQueueService.class).queueSerial(callables);
if (ret == false) {
XLog.getLog(getClass()).warn(
"Unable to queue the callables commands for CheckerService. "
+ "Most possibly command queue is full. Queue size is :"
+ Services.get().get(CallableQueueService.class).queueSize());
}
callables = new ArrayList<XCallable<Void>>();
}
}
}
/**
* Initializes the Action Check service.
*
* @param services services instance.
*/
@Override
public void init(Services services) {
Configuration conf = services.getConf();
Runnable actionCheckRunnable = new ActionCheckRunnable(conf.getInt(CONF_ACTION_CHECK_DELAY, 600));
services.get(SchedulerService.class).schedule(actionCheckRunnable, 10,
conf.getInt(CONF_ACTION_CHECK_INTERVAL, 60), SchedulerService.Unit.SEC);
if (Services.get().getConf().getBoolean(USE_XCOMMAND, true) == false) {
useXCommand = false;
}
}
/**
* Destroy the Action Checker Services.
*/
@Override
public void destroy() {
}
/**
* Return the public interface for the action checker service.
*
* @return {@link ActionCheckerService}.
*/
@Override
public Class<? extends Service> getInterface() {
return ActionCheckerService.class;
}
}
| sunmeng007/oozie | core/src/main/java/org/apache/oozie/service/ActionCheckerService.java | Java | apache-2.0 | 9,013 |
package com.google.api.ads.dfp.jaxws.v201508;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
*
* The content partner related validation errors.
*
*
* <p>Java class for ContentPartnerError complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ContentPartnerError">
* <complexContent>
* <extension base="{https://www.google.com/apis/ads/publisher/v201508}ApiError">
* <sequence>
* <element name="reason" type="{https://www.google.com/apis/ads/publisher/v201508}ContentPartnerError.Reason" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ContentPartnerError", propOrder = {
"reason"
})
public class ContentPartnerError
extends ApiError
{
@XmlSchemaType(name = "string")
protected ContentPartnerErrorReason reason;
/**
* Gets the value of the reason property.
*
* @return
* possible object is
* {@link ContentPartnerErrorReason }
*
*/
public ContentPartnerErrorReason getReason() {
return reason;
}
/**
* Sets the value of the reason property.
*
* @param value
* allowed object is
* {@link ContentPartnerErrorReason }
*
*/
public void setReason(ContentPartnerErrorReason value) {
this.reason = value;
}
}
| shyTNT/googleads-java-lib | modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201508/ContentPartnerError.java | Java | apache-2.0 | 1,711 |
/**
* Copyright 2017 LinkedIn Corp. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package com.github.ambry.store;
import com.github.ambry.utils.Pair;
import java.util.HashMap;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;
/**
* Hold the data structures needed by {@link BlobStoreStats} to serve requests. The class also exposes helper methods
* used to modify and access the stored data structures.
*/
class ScanResults {
// A NavigableMap that stores buckets for container valid data size. The key of the map is the end time of each
// bucket and the value is the corresponding valid data size map. For example, there are two buckets with end time
// t1 and t2. Bucket with end time t2 includes all events whose operation time is greater than or equal to t1 but
// strictly less than t2.
// Each bucket except for the very first one contains the delta in valid data size that occurred prior to the bucket
// end time. The very first bucket's end time is the forecast start time for containers and it contains the valid data
// size map at the forecast start time. The very first bucket is used as a base value, requested valid data size is
// computed by applying the deltas from appropriate buckets on the base value.
private final NavigableMap<Long, Map<String, Map<String, Long>>> containerBuckets = new TreeMap<>();
// A NavigableMap that stores buckets for log segment valid data size. The rest of the structure is similar
// to containerBuckets.
private final NavigableMap<Long, NavigableMap<String, Long>> logSegmentBuckets = new TreeMap<>();
final long containerForecastStartTimeMs;
final long containerLastBucketTimeMs;
final long containerForecastEndTimeMs;
final long logSegmentForecastStartTimeMs;
final long logSegmentLastBucketTimeMs;
final long logSegmentForecastEndTimeMs;
Offset scannedEndOffset = null;
/**
* Create the bucket data structures in advance based on the given scanStartTime and segmentScanTimeOffset.
*/
ScanResults(long startTimeInMs, long logSegmentForecastOffsetMs, int bucketCount, long bucketSpanInMs) {
long containerBucketTimeMs = startTimeInMs;
long logSegmentBucketTimeMs = startTimeInMs - logSegmentForecastOffsetMs;
for (int i = 0; i < bucketCount; i++) {
containerBuckets.put(containerBucketTimeMs, new HashMap<>());
logSegmentBuckets.put(logSegmentBucketTimeMs, new TreeMap<>(LogSegmentNameHelper.COMPARATOR));
containerBucketTimeMs += bucketSpanInMs;
logSegmentBucketTimeMs += bucketSpanInMs;
}
containerForecastStartTimeMs = containerBuckets.firstKey();
containerLastBucketTimeMs = containerBuckets.lastKey();
containerForecastEndTimeMs = containerLastBucketTimeMs + bucketSpanInMs;
logSegmentForecastStartTimeMs = logSegmentBuckets.firstKey();
logSegmentLastBucketTimeMs = logSegmentBuckets.lastKey();
logSegmentForecastEndTimeMs = logSegmentLastBucketTimeMs + bucketSpanInMs;
}
/**
* Given a reference time, return the key of the appropriate container bucket whose end time is strictly greater than
* the reference time.
* @param referenceTimeInMs the reference time or operation time of an event.
* @return the appropriate bucket key (bucket end time) to indicate which bucket will an event with
* the given reference time as operation time belong to.
*/
Long getContainerBucketKey(long referenceTimeInMs) {
return containerBuckets.higherKey(referenceTimeInMs);
}
/**
* Given a reference time, return the key of the appropriate log segment bucket whose end time is strictly greater
* than the reference time.
* @param referenceTimeInMs the reference time or operation time of an event.
* @return the appropriate bucket key (bucket end time) to indicate which bucket will an event with
* the given reference time as operation time belong to.
*/
Long getLogSegmentBucketKey(long referenceTimeInMs) {
return logSegmentBuckets.higherKey(referenceTimeInMs);
}
/**
* Helper function to update the container base value bucket with the given value.
* @param serviceId the serviceId of the map entry to be updated
* @param containerId the containerId of the map entry to be updated
* @param value the value to be added
*/
void updateContainerBaseBucket(String serviceId, String containerId, long value) {
updateContainerBucket(containerBuckets.firstKey(), serviceId, containerId, value);
}
/**
* Helper function to update the log segment base value bucket with the given value.
* @param logSegmentName the log segment name of the map entry to be updated
* @param value the value to be added
*/
void updateLogSegmentBaseBucket(String logSegmentName, long value) {
updateLogSegmentBucket(logSegmentBuckets.firstKey(), logSegmentName, value);
}
/**
* Helper function to update a container bucket with the given value.
* @param bucketKey the bucket key to specify which bucket will be updated
* @param serviceId the serviceId of the map entry to be updated
* @param containerId the containerId of the map entry to be updated
* @param value the value to be added
*/
void updateContainerBucket(Long bucketKey, String serviceId, String containerId, long value) {
if (bucketKey != null && containerBuckets.containsKey(bucketKey)) {
Map<String, Map<String, Long>> existingBucketEntry = containerBuckets.get(bucketKey);
updateNestedMapHelper(existingBucketEntry, serviceId, containerId, value);
}
}
/**
* Helper function to update a log segment bucket with a given value.
* @param bucketKey the bucket key to specify which bucket will be updated
* @param logSegmentName the log segment name of the map entry to be updated
* @param value the value to be added
*/
void updateLogSegmentBucket(Long bucketKey, String logSegmentName, long value) {
if (bucketKey != null && logSegmentBuckets.containsKey(bucketKey)) {
Map<String, Long> existingBucketEntry = logSegmentBuckets.get(bucketKey);
updateMapHelper(existingBucketEntry, logSegmentName, value);
}
}
/**
* Given a reference time in milliseconds return the corresponding valid data size per log segment map by aggregating
* all buckets whose end time is less than or equal to the reference time.
* @param referenceTimeInMS the reference time in ms until which deletes and expiration are relevant
* @return a {@link Pair} whose first element is the end time of the last bucket that was aggregated and whose second
* element is the requested valid data size per log segment {@link NavigableMap}.
*/
Pair<Long, NavigableMap<String, Long>> getValidSizePerLogSegment(Long referenceTimeInMS) {
NavigableMap<String, Long> validSizePerLogSegment = new TreeMap<>(logSegmentBuckets.firstEntry().getValue());
NavigableMap<Long, NavigableMap<String, Long>> subMap =
logSegmentBuckets.subMap(logSegmentBuckets.firstKey(), false, referenceTimeInMS, true);
for (Map.Entry<Long, NavigableMap<String, Long>> bucket : subMap.entrySet()) {
for (Map.Entry<String, Long> bucketEntry : bucket.getValue().entrySet()) {
updateMapHelper(validSizePerLogSegment, bucketEntry.getKey(), bucketEntry.getValue());
}
}
Long lastReferenceBucketTimeInMs = subMap.isEmpty() ? logSegmentBuckets.firstKey() : subMap.lastKey();
return new Pair<>(lastReferenceBucketTimeInMs, validSizePerLogSegment);
}
/**
* Given a reference time in ms return the corresponding valid data size per container map by aggregating all buckets
* whose end time is less than or equal to the reference time.
* @param referenceTimeInMs the reference time in ms until which deletes and expiration are relevant.
* @return a {@link Pair} whose first element is the end time of the last bucket that was aggregated and whose second
* element is the requested valid data size per container {@link Map}.
*/
Map<String, Map<String, Long>> getValidSizePerContainer(Long referenceTimeInMs) {
Map<String, Map<String, Long>> validSizePerContainer = new HashMap<>();
for (Map.Entry<String, Map<String, Long>> accountEntry : containerBuckets.firstEntry().getValue().entrySet()) {
validSizePerContainer.put(accountEntry.getKey(), new HashMap<>(accountEntry.getValue()));
}
NavigableMap<Long, Map<String, Map<String, Long>>> subMap =
containerBuckets.subMap(containerBuckets.firstKey(), false, referenceTimeInMs, true);
for (Map.Entry<Long, Map<String, Map<String, Long>>> bucket : subMap.entrySet()) {
for (Map.Entry<String, Map<String, Long>> accountEntry : bucket.getValue().entrySet()) {
for (Map.Entry<String, Long> containerEntry : accountEntry.getValue().entrySet()) {
updateNestedMapHelper(validSizePerContainer, accountEntry.getKey(), containerEntry.getKey(),
containerEntry.getValue());
}
}
}
return validSizePerContainer;
}
/**
* Helper function to update nested map data structure.
* @param nestedMap nested {@link Map} to be updated
* @param firstKey of the nested map
* @param secondKey of the nested map
* @param value the value to be added at the corresponding entry
*/
private void updateNestedMapHelper(Map<String, Map<String, Long>> nestedMap, String firstKey, String secondKey,
Long value) {
if (!nestedMap.containsKey(firstKey)) {
nestedMap.put(firstKey, new HashMap<String, Long>());
}
updateMapHelper(nestedMap.get(firstKey), secondKey, value);
}
/**
* Helper function to update map data structure.
* @param map {@link Map} to be updated
* @param key of the map
* @param value the value to be added at the corresponding entry
*/
private void updateMapHelper(Map<String, Long> map, String key, Long value) {
Long newValue = map.containsKey(key) ? map.get(key) + value : value;
map.put(key, newValue);
}
}
| xiahome/ambry | ambry-store/src/main/java/com.github.ambry.store/ScanResults.java | Java | apache-2.0 | 10,385 |
/*
* 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.wicket.application;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import org.apache.wicket.util.collections.UrlExternalFormComparator;
import org.apache.wicket.util.file.File;
import org.apache.wicket.util.listener.IChangeListener;
import org.apache.wicket.util.time.Duration;
import org.apache.wicket.util.watch.IModificationWatcher;
import org.apache.wicket.util.watch.ModificationWatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Custom ClassLoader that reverses the classloader lookups, and that is able to notify a listener
* when a class file is changed.
*
* @author <a href="mailto:jbq@apache.org">Jean-Baptiste Quenot</a>
*/
public class ReloadingClassLoader extends URLClassLoader
{
private static final Logger log = LoggerFactory.getLogger(ReloadingClassLoader.class);
private static final Set<URL> urls = new TreeSet<URL>(new UrlExternalFormComparator());
private static final List<String> patterns = new ArrayList<String>();
private IChangeListener listener;
private final Duration pollFrequency = Duration.seconds(3);
private final IModificationWatcher watcher;
static
{
addClassLoaderUrls(ReloadingClassLoader.class.getClassLoader());
excludePattern("org.apache.wicket.*");
includePattern("org.apache.wicket.examples.*");
}
/**
*
* @param name
* @return true if class if found, false otherwise
*/
protected boolean tryClassHere(String name)
{
// don't include classes in the java or javax.servlet package
if (name != null && (name.startsWith("java.") || name.startsWith("javax.servlet")))
{
return false;
}
// Scan includes, then excludes
boolean tryHere;
// If no explicit includes, try here
if (patterns == null || patterns.size() == 0)
{
tryHere = true;
}
else
{
// See if it matches include patterns
tryHere = false;
for (String rawpattern : patterns)
{
if (rawpattern.length() <= 1)
{
continue;
}
// FIXME it seems that only "includes" are handled. "Excludes" are ignored
boolean isInclude = rawpattern.substring(0, 1).equals("+");
String pattern = rawpattern.substring(1);
if (WildcardMatcherHelper.match(pattern, name) != null)
{
tryHere = isInclude;
}
}
}
return tryHere;
}
/**
* Include a pattern
*
* @param pattern
* the pattern to include
*/
public static void includePattern(String pattern)
{
patterns.add("+" + pattern);
}
/**
* Exclude a pattern
*
* @param pattern
* the pattern to exclude
*/
public static void excludePattern(String pattern)
{
patterns.add("-" + pattern);
}
/**
* Returns the list of all configured inclusion or exclusion patterns
*
* @return list of patterns as String
*/
public static List<String> getPatterns()
{
return patterns;
}
/**
* Add the location of a directory containing class files
*
* @param url
* the URL for the directory
*/
public static void addLocation(URL url)
{
urls.add(url);
}
/**
* Returns the list of all configured locations of directories containing class files
*
* @return list of locations as URL
*/
public static Set<URL> getLocations()
{
return urls;
}
/**
* Add all the url locations we can find for the provided class loader
*
* @param loader
* class loader
*/
private static void addClassLoaderUrls(ClassLoader loader)
{
if (loader != null)
{
final Enumeration<URL> resources;
try
{
resources = loader.getResources("");
}
catch (IOException e)
{
throw new RuntimeException(e);
}
while (resources.hasMoreElements())
{
URL location = resources.nextElement();
ReloadingClassLoader.addLocation(location);
}
}
}
/**
* Create a new reloading ClassLoader from a list of URLs, and initialize the
* ModificationWatcher to detect class file modifications
*
* @param parent
* the parent classloader in case the class file cannot be loaded from the above
* locations
*/
public ReloadingClassLoader(ClassLoader parent)
{
super(new URL[] { }, parent);
// probably doubles from this class, but just in case
addClassLoaderUrls(parent);
for (URL url : urls)
{
addURL(url);
}
watcher = new ModificationWatcher(pollFrequency);
}
/**
* Gets a resource from this <code>ClassLoader</class>. If the
* resource does not exist in this one, we check the parent.
* Please note that this is the exact opposite of the
* <code>ClassLoader</code> spec. We use it to work around inconsistent class loaders from third
* party vendors.
*
* @param name
* of resource
*/
@Override
public final URL getResource(final String name)
{
URL resource = findResource(name);
ClassLoader parent = getParent();
if (resource == null && parent != null)
{
resource = parent.getResource(name);
}
return resource;
}
/**
* Loads the class from this <code>ClassLoader</class>. If the
* class does not exist in this one, we check the parent. Please
* note that this is the exact opposite of the
* <code>ClassLoader</code> spec. We use it to load the class from the same classloader as
* WicketFilter or WicketServlet. When found, the class file is watched for modifications.
*
* @param name
* the name of the class
* @param resolve
* if <code>true</code> then resolve the class
* @return the resulting <code>Class</code> object
* @exception ClassNotFoundException
* if the class could not be found
*/
@Override
public final Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException
{
// First check if it's already loaded
Class<?> clazz = findLoadedClass(name);
if (clazz == null)
{
final ClassLoader parent = getParent();
if (tryClassHere(name))
{
try
{
clazz = findClass(name);
watchForModifications(clazz);
}
catch (ClassNotFoundException cnfe)
{
if (parent == null)
{
// Propagate exception
throw cnfe;
}
}
}
if (clazz == null)
{
if (parent == null)
{
throw new ClassNotFoundException(name);
}
else
{
// Will throw a CFNE if not found in parent
// see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6500212
// clazz = parent.loadClass(name);
clazz = Class.forName(name, false, parent);
}
}
}
if (resolve)
{
resolveClass(clazz);
}
return clazz;
}
/**
* Sets the listener that will be notified when a class changes
*
* @param listener
* the listener to notify upon class change
*/
public void setListener(IChangeListener listener)
{
this.listener = listener;
}
/**
* Watch changes of a class file by locating it in the list of location URLs and adding the
* corresponding file to the ModificationWatcher
*
* @param clz
* the class to watch
*/
private void watchForModifications(Class<?> clz)
{
// Watch class in the future
Iterator<URL> locationsIterator = urls.iterator();
File clzFile = null;
while (locationsIterator.hasNext())
{
// FIXME only works for directories, but JARs etc could be checked
// as well
URL location = locationsIterator.next();
String clzLocation = location.getFile() + clz.getName().replaceAll("\\.", "/") +
".class";
log.debug("clzLocation=" + clzLocation);
clzFile = new File(clzLocation);
final File finalClzFile = clzFile;
if (clzFile.exists())
{
log.info("Watching changes of class " + clzFile);
watcher.add(clzFile, new IChangeListener()
{
@Override
public void onChange()
{
log.info("Class file " + finalClzFile + " has changed, reloading");
try
{
listener.onChange();
}
catch (Exception e)
{
log.error("Could not notify listener", e);
// If an error occurs when the listener is notified,
// remove the watched object to avoid rethrowing the
// exception at next check
// FIXME check if class file has been deleted
watcher.remove(finalClzFile);
}
}
});
break;
}
else
{
log.debug("Class file does not exist: " + clzFile);
}
}
if (clzFile != null && !clzFile.exists())
{
log.debug("Could not locate class " + clz.getName());
}
}
/**
* Remove the ModificationWatcher from the current reloading class loader
*/
public void destroy()
{
watcher.destroy();
}
}
| mafulafunk/wicket | wicket-core/src/main/java/org/apache/wicket/application/ReloadingClassLoader.java | Java | apache-2.0 | 9,526 |
package jadx.tests.integration.conditions;
import org.junit.jupiter.api.Test;
import jadx.tests.api.SmaliTest;
import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat;
@SuppressWarnings("CommentedOutCode")
public class TestTernary4 extends SmaliTest {
// @formatter:off
/*
private Set test(HashMap<String, Object> hashMap) {
boolean z;
HashSet hashSet = new HashSet();
synchronized (this.defaultValuesByPath) {
for (String next : this.defaultValuesByPath.keySet()) {
Object obj = hashMap.get(next);
if (obj != null) {
z = !getValueObject(next).equals(obj);
} else {
z = this.valuesByPath.get(next) != null;;
}
if (z) {
hashSet.add(next);
}
}
}
return hashSet;
}
*/
// @formatter:on
@Test
public void test() {
assertThat(getClassNodeFromSmali())
.code()
.removeBlockComments()
.doesNotContain("5")
.doesNotContain("try");
}
}
| skylot/jadx | jadx-core/src/test/java/jadx/tests/integration/conditions/TestTernary4.java | Java | apache-2.0 | 944 |
package jadx.tests.integration.debuginfo;
import org.junit.jupiter.api.Test;
import jadx.core.dex.nodes.ClassNode;
import jadx.tests.api.SmaliTest;
import static jadx.tests.api.utils.JadxMatchers.containsOne;
import static org.hamcrest.MatcherAssert.assertThat;
public class TestVariablesNames extends SmaliTest {
// @formatter:off
/*
public static class TestCls {
public void test(String s, int k) {
f1(s);
int i = k + 3;
String s2 = "i" + i;
f2(i, s2);
double d = i * 5;
String s3 = "d" + d;
f3(d, s3);
}
private void f1(String s) {
}
private void f2(int i, String i2) {
}
private void f3(double d, String d2) {
}
}
*/
// @formatter:on
/**
* Parameter register reused in variables assign with different types and names
* No variables names in debug info
*/
@Test
public void test() {
ClassNode cls = getClassNodeFromSmaliWithPath("debuginfo", "TestVariablesNames");
String code = cls.getCode().toString();
// TODO: don't use current variables naming in tests
assertThat(code, containsOne("f1(str);"));
assertThat(code, containsOne("f2(i2, \"i\" + i2);"));
assertThat(code, containsOne("f3(d, \"d\" + d);"));
}
}
| skylot/jadx | jadx-core/src/test/java/jadx/tests/integration/debuginfo/TestVariablesNames.java | Java | apache-2.0 | 1,206 |
package com.cardshifter.gdx.screens;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.ui.*;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.cardshifter.api.incoming.UseAbilityMessage;
import com.cardshifter.api.messages.Message;
import com.cardshifter.api.outgoing.*;
import com.cardshifter.gdx.*;
import com.cardshifter.gdx.ui.CardshifterClientContext;
import com.cardshifter.gdx.ui.EntityView;
import com.cardshifter.gdx.ui.PlayerView;
import com.cardshifter.gdx.ui.cards.CardView;
import com.cardshifter.gdx.ui.cards.CardViewSmall;
import com.cardshifter.gdx.ui.zones.CompactHiddenZoneView;
import com.cardshifter.gdx.ui.zones.DefaultZoneView;
import com.cardshifter.gdx.ui.zones.ZoneView;
import java.util.*;
import java.util.List;
/**
* Created by Simon on 1/31/2015.
*/
public class GameScreen implements Screen, TargetableCallback {
private final CardshifterGame game;
private final CardshifterClient client;
private final int playerIndex;
private final int gameId;
private final Table table;
private final Map<Integer, ZoneView> zoneViews = new HashMap<Integer, ZoneView>();
private final Map<Integer, EntityView> entityViews = new HashMap<Integer, EntityView>();
private final Map<String, Container<Actor>> holders = new HashMap<String, Container<Actor>>();
private final List<EntityView> targetsSelected = new ArrayList<EntityView>();
private final Screen parentScreen;
private AvailableTargetsMessage targetsAvailable;
private final TargetableCallback onTarget = new TargetableCallback() {
@Override
public boolean addEntity(EntityView view) {
if (targetsSelected.contains(view)) {
targetsSelected.remove(view);
Gdx.app.log("GameScreen", "Removing selection " + view.getId());
view.setTargetable(TargetStatus.TARGETABLE, this);
return false;
}
if (targetsAvailable != null && targetsAvailable.getMax() == 1 && targetsAvailable.getMin() == 1) {
Gdx.app.log("GameScreen", "Sending selection " + view.getId());
client.send(new UseAbilityMessage(gameId, targetsAvailable.getEntity(), targetsAvailable.getAction(), new int[]{ view.getId() }));
return false;
}
Gdx.app.log("GameScreen", "Adding selection " + view.getId());
view.setTargetable(TargetStatus.TARGETED, this);
return targetsSelected.add(view);
}
};
private final CardshifterClientContext context;
//private final float screenWidth;
private final float screenHeight;
public GameScreen(final CardshifterGame game, final CardshifterClient client, NewGameMessage message, final Screen parentScreen) {
this.parentScreen = parentScreen;
this.game = game;
this.client = client;
this.playerIndex = message.getPlayerIndex();
this.gameId = message.getGameId();
this.context = new CardshifterClientContext(game.skin, message.getGameId(), client, game.stage);
//this.screenWidth = CardshifterGame.STAGE_WIDTH;
this.screenHeight = CardshifterGame.STAGE_HEIGHT;
this.table = new Table(game.skin);
Table leftTable = new Table(game.skin);
Table topTable = new Table(game.skin);
//Table rightTable = new Table(game.skin);
Table centerTable = new Table(game.skin);
TextButton backToMenu = new TextButton("Back to menu", game.skin);
backToMenu.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
game.setScreen(parentScreen);
}
});
leftTable.add(backToMenu).expandX().fill().row();
addZoneHolder(leftTable, 1 - this.playerIndex, "").expandY().fillY();
addZoneHolder(leftTable, this.playerIndex, "").expandY().fillY();
leftTable.add("controls").row();
TextButton actionDone = new TextButton("Done", game.skin);
actionDone.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
if (targetsAvailable != null) {
int selected = targetsSelected.size();
if (selected >= targetsAvailable.getMin() && selected <= targetsAvailable.getMax()) {
int[] targets = new int[targetsSelected.size()];
for (int i = 0; i < targets.length; i++) {
targets[i] = targetsSelected.get(i).getId();
}
UseAbilityMessage message = new UseAbilityMessage(gameId, targetsAvailable.getEntity(), targetsAvailable.getAction(), targets);
client.send(message);
}
}
}
});
leftTable.add(actionDone);
topTable.add(leftTable).left().expandY().fillY();
topTable.add(centerTable).center().expandX().expandY().fill();
//topTable.add(rightTable).right().width(150).expandY().fillY();
addZoneHolder(centerTable, 1 - this.playerIndex, "Hand").top().height(this.screenHeight/4);
addZoneHolder(centerTable, 1 - this.playerIndex, "Battlefield").height(this.screenHeight/4);
addZoneHolder(centerTable, this.playerIndex, "Battlefield").height(this.screenHeight/4);
this.table.add(topTable).expand().fill().row();
addZoneHolder(this.table, this.playerIndex, "Hand").height(140).expandX().fill();
this.table.setFillParent(true);
}
private Cell<Container<Actor>> addZoneHolder(Table table, int i, String name) {
Container<Actor> container = new Container<Actor>();
container.setName(name);
// container.fill();
Cell<Container<Actor>> cell = table.add(container).expandX().fillX();
table.row();
holders.put(i + name, container);
return cell;
}
@Override
public void render(float delta) {
}
@Override
public void resize(int width, int height) {
}
@Override
public void show() {
game.stage.addActor(table);
}
@Override
public void hide() {
table.remove();
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void dispose() {
}
public Map<Class<? extends Message>, SpecificHandler<?>> getHandlers() {
Map<Class<? extends Message>, SpecificHandler<?>> handlers =
new HashMap<Class<? extends Message>, SpecificHandler<?>>();
handlers.put(AvailableTargetsMessage.class, new SpecificHandler<AvailableTargetsMessage>() {
@Override
public void handle(AvailableTargetsMessage message) {
targetsAvailable = message;
targetsSelected.clear();
for (EntityView view : entityViews.values()) {
view.setTargetable(TargetStatus.NOT_TARGETABLE, onTarget);
}
for (int id : message.getTargets()) {
EntityView view = entityViews.get(id);
if (view != null) {
view.setTargetable(TargetStatus.TARGETABLE, onTarget);
}
}
}
});
handlers.put(UsableActionMessage.class, new SpecificHandler<UsableActionMessage>() {
@Override
public void handle(UsableActionMessage message) {
int id = message.getId();
EntityView view = entityViews.get(id);
if (view != null) {
view.usableAction(message);
if (view instanceof CardViewSmall) {
((CardViewSmall)view).setUsable(GameScreen.this);
}
}
}
});
handlers.put(CardInfoMessage.class, new SpecificHandler<CardInfoMessage>() {
@Override
public void handle(CardInfoMessage message) {
ZoneView zone = getZoneView(message.getZone());
if (zone != null) {
zone.removeCard(message.getId());
}
EntityView entityView = entityViews.remove(message.getId());
if (entityView != null) {
entityView.remove();
}
if (zone != null) {
entityViews.put(message.getId(), zone.addCard(message));
}
}
});
handlers.put(EntityRemoveMessage.class, new SpecificHandler<EntityRemoveMessage>() {
@Override
public void handle(EntityRemoveMessage message) {
EntityView view = entityViews.get(message.getEntity());
for (ZoneView zone : zoneViews.values()) {
if (zone.hasCard(message.getEntity())) {
zone.removeCard(message.getEntity());
}
}
if (view != null) {
view.entityRemoved();
entityViews.remove(message.getEntity());
}
}
});
handlers.put(GameOverMessage.class, new SpecificHandler<GameOverMessage>() {
@Override
public void handle(GameOverMessage message) {
Dialog dialog = new Dialog("Game Over!", context.getSkin()) {
@Override
protected void result(Object object) {
game.setScreen(parentScreen);
}
};
dialog.button("OK");
dialog.show(context.getStage());
}
});
handlers.put(PlayerMessage.class, new SpecificHandler<PlayerMessage>() {
@Override
public void handle(PlayerMessage message) {
PlayerView playerView = new PlayerView(context, message);
entityViews.put(message.getId(), playerView);
Container<Actor> holder = holders.get(String.valueOf(message.getIndex()));
if (holder != null) {
holder.setActor(playerView.getActor());
}
}
});
handlers.put(ResetAvailableActionsMessage.class, new SpecificHandler<ResetAvailableActionsMessage>() {
@Override
public void handle(ResetAvailableActionsMessage message) {
for (EntityView view : entityViews.values()) {
view.setTargetable(TargetStatus.NOT_TARGETABLE, null);
view.clearUsableActions();
}
}
});
handlers.put(UpdateMessage.class, new SpecificHandler<UpdateMessage>() {
@Override
public void handle(UpdateMessage message) {
EntityView entityView = entityViews.get(message.getId());
if (entityView != null) {
entityView.set(message.getKey(), message.getValue());
}
}
});
handlers.put(ZoneChangeMessage.class, new SpecificHandler<ZoneChangeMessage>() {
@Override
public void handle(ZoneChangeMessage message) {
ZoneView oldZone = getZoneView(message.getSourceZone()); // can be null
ZoneView destinationZone = getZoneView(message.getDestinationZone());
int id = message.getEntity();
CardView entityView = (CardView) entityViews.remove(id); // can be null
if (oldZone != null) {
oldZone.removeCard(id);
}
if (destinationZone != null) {
CardView newCardView = destinationZone.addCard(new CardInfoMessage(message.getDestinationZone(), id,
entityView == null ? null : entityView.getInfo()));
if (entityView != null) {
entityView.zoneMove(message, destinationZone, newCardView);
}
entityViews.put(id, newCardView);
}
else {
if (entityView != null) {
entityView.zoneMove(message, destinationZone, null);
}
}
/*
Send to AI Medium: ZoneChangeMessage [entity=95, sourceZone=72, destinationZone=73]
Send to AI Medium: CardInfo: 95 in zone 73 - {SCRAP=1, TAUNT=1, MAX_HEALTH=1, SICKNESS=1, MANA_COST=2, name=The Chopper, ATTACK=2, creatureType=Mech, HEALTH=1, ATTACK_AVAILABLE=1}
Send to Zomis: ZoneChangeMessage [entity=95, sourceZone=72, destinationZone=73]
if card is already known, send ZoneChange only
if card is not known, send ZoneChange first and then CardInfo
when cards are created from nowhere, ZoneChange with source -1 is sent and then CardInfo
*/
}
});
handlers.put(ZoneMessage.class, new SpecificHandler<ZoneMessage>() {
@Override
public void handle(ZoneMessage message) {
Gdx.app.log("GameScreen", "Zone " + message);
ZoneView zoneView = createZoneView(message);
if (zoneView != null) {
PlayerView view = (PlayerView) entityViews.get(message.getOwner());
if (view == null) {
Gdx.app.log("GameScreen", "no playerView for " + message.getOwner());
return;
}
String key = view.getIndex() + message.getName();
Container<Actor> container = holders.get(key);
if (container == null) {
Gdx.app.log("GameScreen", "no container for " + key);
return;
}
Gdx.app.log("GameScreen", "putting zoneview for " + key);
container.setActor(zoneView.getActor());
zoneViews.put(message.getId(), zoneView);
}
}
});
return handlers;
}
private ZoneView createZoneView(ZoneMessage message) {
String type = message.getName();
if (type.equals("Battlefield")) {
return new DefaultZoneView(context, message, this.entityViews);
}
if (type.equals("Hand")) {
return new DefaultZoneView(context, message, this.entityViews);
}
if (type.equals("Deck")) {
return new CompactHiddenZoneView(game, message);
}
if (type.equals("Cards")) {
return null; // Card models only
}
throw new RuntimeException("Unknown ZoneView type: " + message.getName());
}
private ZoneView getZoneView(int id) {
return this.zoneViews.get(id);
}
public boolean checkCardDrop(CardViewSmall cardView) {
Table table = (Table)cardView.getActor();
Vector2 stageLoc = table.localToStageCoordinates(new Vector2());
Rectangle tableRect = new Rectangle(stageLoc.x, stageLoc.y, table.getWidth(), table.getHeight());
for (Container<Actor> actor : this.holders.values()) {
if (actor.getName() == "Battlefield") {
Vector2 stageBattlefieldLoc = actor.localToStageCoordinates(new Vector2(actor.getActor().getX(), actor.getActor().getY()));
Vector2 modifiedSBL = new Vector2(stageBattlefieldLoc.x - actor.getWidth()/2, stageBattlefieldLoc.y - actor.getHeight()/2);
Rectangle deckRect = new Rectangle(modifiedSBL.x, modifiedSBL.y, actor.getWidth() * 0.8f, actor.getHeight());
//uncomment this to see the bug where battlefields pop up in strange places
/*
Image squareImage = new Image(new Texture(Gdx.files.internal("cardbg.png")));
squareImage.setPosition(modifiedSBL.x, modifiedSBL.y);
squareImage.setSize(deckRect.width, deckRect.height);
this.game.stage.addActor(squareImage);
*/
if (tableRect.overlaps(deckRect)) {
//this.addEntity(cardView);
System.out.println("target found!");
return true;
}
}
}
return false;
//these can be used to double check the location of the rectangles
/*
Image squareImage = new Image(new Texture(Gdx.files.internal("cardbg.png")));
squareImage.setPosition(modifiedSBL.x, modifiedSBL.y);
squareImage.setSize(deckRect.width, deckRect.height);
this.game.stage.addActor(squareImage);
*/
/*
Image squareImage = new Image(new Texture(Gdx.files.internal("cardbg.png")));
squareImage.setPosition(stageLoc.x, stageLoc.y);
squareImage.setSize(tableRect.width, tableRect.height);
this.game.stage.addActor(squareImage);
*/
}
@Override
public boolean addEntity(EntityView view) {
//called by the CardViewSmall when not in mulligan mode, nothing will happen
return false;
}
}
| Cardshifter/Cardshifter | gdx/core/src/com/cardshifter/gdx/screens/GameScreen.java | Java | apache-2.0 | 17,117 |
/*
* Copyright 2000-2014 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.jetbrains.python.inspections.quickfix;
import com.intellij.codeInsight.CodeInsightUtilCore;
import com.intellij.codeInsight.FileModificationService;
import com.intellij.codeInsight.template.TemplateBuilder;
import com.intellij.codeInsight.template.TemplateBuilderFactory;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.Function;
import com.jetbrains.python.PyBundle;
import com.jetbrains.python.PyNames;
import com.jetbrains.python.psi.*;
import com.jetbrains.python.psi.impl.PyPsiUtils;
import com.jetbrains.python.psi.types.PyClassType;
import com.jetbrains.python.psi.types.PyClassTypeImpl;
import com.jetbrains.python.psi.types.PyType;
import com.jetbrains.python.psi.types.TypeEvalContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Available on self.my_something when my_something is unresolved.
* User: dcheryasov
*/
public class AddFieldQuickFix implements LocalQuickFix {
private final String myInitializer;
private final String myClassName;
private final String myIdentifier;
private boolean replaceInitializer = false;
public AddFieldQuickFix(@NotNull final String identifier, @NotNull final String initializer, final String className, boolean replace) {
myIdentifier = identifier;
myInitializer = initializer;
myClassName = className;
replaceInitializer = replace;
}
@NotNull
public String getName() {
return PyBundle.message("QFIX.NAME.add.field.$0.to.class.$1", myIdentifier, myClassName);
}
@NotNull
public String getFamilyName() {
return "Add field to class";
}
@NotNull
public static PsiElement appendToMethod(PyFunction init, Function<String, PyStatement> callback) {
// add this field as the last stmt of the constructor
final PyStatementList statementList = init.getStatementList();
// name of 'self' may be different for fancier styles
String selfName = PyNames.CANONICAL_SELF;
final PyParameter[] params = init.getParameterList().getParameters();
if (params.length > 0) {
selfName = params[0].getName();
}
final PyStatement newStmt = callback.fun(selfName);
final PsiElement result = PyUtil.addElementToStatementList(newStmt, statementList, true);
PyPsiUtils.removeRedundantPass(statementList);
return result;
}
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
// expect the descriptor to point to the unresolved identifier.
final PsiElement element = descriptor.getPsiElement();
final PyClassType type = getClassType(element);
if (type == null) return;
final PyClass cls = type.getPyClass();
if (!FileModificationService.getInstance().preparePsiElementForWrite(cls)) return;
WriteAction.run(() -> {
PsiElement initStatement;
if (!type.isDefinition()) {
initStatement = addFieldToInit(project, cls, myIdentifier, new CreateFieldCallback(project, myIdentifier, myInitializer));
}
else {
PyStatement field = PyElementGenerator.getInstance(project)
.createFromText(LanguageLevel.getDefault(), PyStatement.class, myIdentifier + " = " + myInitializer);
initStatement = PyUtil.addElementToStatementList(field, cls.getStatementList(), true);
}
if (initStatement != null) {
showTemplateBuilder(initStatement, cls.getContainingFile());
return;
}
// somehow we failed. tell about this
PyUtil.showBalloon(project, PyBundle.message("QFIX.failed.to.add.field"), MessageType.ERROR);
});
}
@Override
public boolean startInWriteAction() {
return false;
}
private static PyClassType getClassType(@NotNull final PsiElement element) {
if (element instanceof PyQualifiedExpression) {
final PyExpression qualifier = ((PyQualifiedExpression)element).getQualifier();
if (qualifier == null) return null;
final PyType type = TypeEvalContext.userInitiated(element.getProject(), element.getContainingFile()).getType(qualifier);
return type instanceof PyClassType ? (PyClassType)type : null;
}
final PyClass aClass = PsiTreeUtil.getParentOfType(element, PyClass.class);
return aClass != null ? new PyClassTypeImpl(aClass, false) : null;
}
private void showTemplateBuilder(PsiElement initStatement, @NotNull final PsiFile file) {
initStatement = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(initStatement);
if (initStatement instanceof PyAssignmentStatement) {
final TemplateBuilder builder = TemplateBuilderFactory.getInstance().createTemplateBuilder(initStatement);
final PyExpression assignedValue = ((PyAssignmentStatement)initStatement).getAssignedValue();
final PyExpression leftExpression = ((PyAssignmentStatement)initStatement).getLeftHandSideExpression();
if (assignedValue != null && leftExpression != null) {
if (replaceInitializer)
builder.replaceElement(assignedValue, myInitializer);
else
builder.replaceElement(leftExpression.getLastChild(), myIdentifier);
final VirtualFile virtualFile = file.getVirtualFile();
if (virtualFile == null) return;
final Editor editor = FileEditorManager.getInstance(file.getProject()).openTextEditor(
new OpenFileDescriptor(file.getProject(), virtualFile), true);
if (editor == null) return;
builder.run(editor, false);
}
}
}
@Nullable
public static PsiElement addFieldToInit(Project project, PyClass cls, String itemName, Function<String, PyStatement> callback) {
if (cls != null && itemName != null) {
PyFunction init = cls.findMethodByName(PyNames.INIT, false, null);
if (init != null) {
return appendToMethod(init, callback);
}
else { // no init! boldly copy ancestor's.
for (PyClass ancestor : cls.getAncestorClasses(null)) {
init = ancestor.findMethodByName(PyNames.INIT, false, null);
if (init != null) break;
}
PyFunction newInit = createInitMethod(project, cls, init);
appendToMethod(newInit, callback);
PsiElement addAnchor = null;
PyFunction[] meths = cls.getMethods();
if (meths.length > 0) addAnchor = meths[0].getPrevSibling();
PyStatementList clsContent = cls.getStatementList();
newInit = (PyFunction) clsContent.addAfter(newInit, addAnchor);
PyUtil.showBalloon(project, PyBundle.message("QFIX.added.constructor.$0.for.field.$1", cls.getName(), itemName), MessageType.INFO);
final PyStatementList statementList = newInit.getStatementList();
final PyStatement[] statements = statementList.getStatements();
return statements.length != 0 ? statements[0] : null;
}
}
return null;
}
@NotNull
private static PyFunction createInitMethod(Project project, PyClass cls, @Nullable PyFunction ancestorInit) {
// found it; copy its param list and make a call to it.
String paramList = ancestorInit != null ? ancestorInit.getParameterList().getText() : "(self)";
String functionText = "def " + PyNames.INIT + paramList + ":\n";
if (ancestorInit == null) functionText += " pass";
else {
final PyClass ancestorClass = ancestorInit.getContainingClass();
if (ancestorClass != null && !PyUtil.isObjectClass(ancestorClass)) {
StringBuilder sb = new StringBuilder();
PyParameter[] params = ancestorInit.getParameterList().getParameters();
boolean seen = false;
if (cls.isNewStyleClass(null)) {
// form the super() call
sb.append("super(");
if (!LanguageLevel.forElement(cls).isPy3K()) {
sb.append(cls.getName());
// NOTE: assume that we have at least the first param
String self_name = params[0].getName();
sb.append(", ").append(self_name);
}
sb.append(").").append(PyNames.INIT).append("(");
}
else {
sb.append(ancestorClass.getName());
sb.append(".__init__(self");
seen = true;
}
for (int i = 1; i < params.length; i += 1) {
if (seen) sb.append(", ");
else seen = true;
sb.append(params[i].getText());
}
sb.append(")");
functionText += " " + sb.toString();
}
else {
functionText += " pass";
}
}
return PyElementGenerator.getInstance(project).createFromText(
LanguageLevel.getDefault(), PyFunction.class, functionText,
new int[]{0}
);
}
private static class CreateFieldCallback implements Function<String, PyStatement> {
private final Project myProject;
private final String myItemName;
private final String myInitializer;
private CreateFieldCallback(Project project, String itemName, String initializer) {
myProject = project;
myItemName = itemName;
myInitializer = initializer;
}
public PyStatement fun(String selfName) {
return PyElementGenerator.getInstance(myProject).createFromText(LanguageLevel.getDefault(), PyStatement.class, selfName + "." + myItemName + " = " + myInitializer);
}
}
}
| jk1/intellij-community | python/src/com/jetbrains/python/inspections/quickfix/AddFieldQuickFix.java | Java | apache-2.0 | 10,326 |
/*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.emoji.text;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.SdkSuppress;
import androidx.test.filters.SmallTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@SmallTest
@RunWith(AndroidJUnit4.class)
@SdkSuppress(minSdkVersion = 19)
public class MetadataRepoTest {
MetadataRepo mMetadataRepo;
@Before
public void clearResourceIndex() {
mMetadataRepo = new MetadataRepo();
}
@Test(expected = NullPointerException.class)
public void testPut_withNullMetadata() {
mMetadataRepo.put(null);
}
@Test(expected = IllegalArgumentException.class)
public void testPut_withEmptyKeys() {
mMetadataRepo.put(new TestEmojiMetadata(new int[0]));
}
@Test
public void testPut_withSingleCodePointMapping() {
final int[] codePoint = new int[]{1};
final TestEmojiMetadata metadata = new TestEmojiMetadata(codePoint);
mMetadataRepo.put(metadata);
assertSame(metadata, getNode(codePoint));
}
@Test
public void testPut_withMultiCodePointsMapping() {
final int[] codePoint = new int[]{1, 2, 3, 4};
final TestEmojiMetadata metadata = new TestEmojiMetadata(codePoint);
mMetadataRepo.put(metadata);
assertSame(metadata, getNode(codePoint));
assertEquals(null, getNode(new int[]{1}));
assertEquals(null, getNode(new int[]{1, 2}));
assertEquals(null, getNode(new int[]{1, 2, 3}));
assertEquals(null, getNode(new int[]{1, 2, 3, 5}));
}
@Test
public void testPut_sequentialCodePoints() {
final int[] codePoint1 = new int[]{1, 2, 3, 4};
final EmojiMetadata metadata1 = new TestEmojiMetadata(codePoint1);
final int[] codePoint2 = new int[]{1, 2, 3};
final EmojiMetadata metadata2 = new TestEmojiMetadata(codePoint2);
final int[] codePoint3 = new int[]{1, 2};
final EmojiMetadata metadata3 = new TestEmojiMetadata(codePoint3);
mMetadataRepo.put(metadata1);
mMetadataRepo.put(metadata2);
mMetadataRepo.put(metadata3);
assertSame(metadata1, getNode(codePoint1));
assertSame(metadata2, getNode(codePoint2));
assertSame(metadata3, getNode(codePoint3));
assertEquals(null, getNode(new int[]{1}));
assertEquals(null, getNode(new int[]{1, 2, 3, 4, 5}));
}
final EmojiMetadata getNode(final int[] codepoints) {
return getNode(mMetadataRepo.getRootNode(), codepoints, 0);
}
final EmojiMetadata getNode(MetadataRepo.Node node, final int[] codepoints, int start) {
if (codepoints.length < start) return null;
if (codepoints.length == start) return node.getData();
final MetadataRepo.Node childNode = node.get(codepoints[start]);
if (childNode == null) return null;
return getNode(childNode, codepoints, start + 1);
}
}
| AndroidX/androidx | emoji/emoji/src/androidTest/java/androidx/emoji/text/MetadataRepoTest.java | Java | apache-2.0 | 3,654 |
/*
* Copyright 2009 Martin Grotzke
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package de.javakaffee.web.msm;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.*;
import static org.testng.Assert.assertEquals;
import java.io.IOException;
import java.util.Collection;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.Nonnull;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import org.apache.catalina.Context;
import org.apache.catalina.Host;
import org.apache.catalina.Valve;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.tomcat.util.http.ServerCookie;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import de.javakaffee.web.msm.MemcachedSessionService.SessionManager;
/**
* Test the {@link RequestTrackingHostValve}.
*
* @author <a href="mailto:martin.grotzke@javakaffee.de">Martin Grotzke</a>
* @version $Id$
*/
public abstract class RequestTrackingHostValveTest {
protected MemcachedSessionService _service;
private RequestTrackingHostValve _sessionTrackerValve;
private Valve _nextValve;
private Request _request;
private Response _response;
@BeforeMethod
public void setUp() throws Exception {
_service = mock( MemcachedSessionService.class );
_request = mock( Request.class );
_response = mock( Response.class );
final Context _contextContainer = mock(Context.class);
final Host _hostContainer = mock(Host.class);
final SessionManager _manager = mock(SessionManager.class);
when(_service.getManager()).thenReturn(_manager);
when(_manager.getContext()).thenReturn(_contextContainer);
when(_contextContainer.getParent()).thenReturn(_hostContainer);
when(_contextContainer.getPath()).thenReturn("/");
_sessionTrackerValve = createSessionTrackerValve();
_nextValve = mock( Valve.class );
_sessionTrackerValve.setNext( _nextValve );
_sessionTrackerValve.setContainer(_hostContainer);
when(_request.getRequestURI()).thenReturn( "/someRequest");
when(_request.getMethod()).thenReturn("GET");
when(_request.getQueryString()).thenReturn(null);
when(_request.getContext()).thenReturn(_contextContainer);
when(_request.getNote(eq(RequestTrackingHostValve.REQUEST_PROCESSED))).thenReturn(Boolean.TRUE);
when(_request.getNote(eq(RequestTrackingHostValve.SESSION_ID_CHANGED))).thenReturn(Boolean.FALSE);
}
@Nonnull
protected RequestTrackingHostValve createSessionTrackerValve() {
return new RequestTrackingHostValve(".*\\.(png|gif|jpg|css|js|ico)$", "somesessionid", _service, Statistics.create(),
new AtomicBoolean( true ), new CurrentRequest()) {
@Override
protected String[] getSetCookieHeaders(final Response response) {
return RequestTrackingHostValveTest.this.getSetCookieHeaders(response);
}
};
}
protected abstract String[] getSetCookieHeaders(final Response response);
@AfterMethod
public void tearDown() throws Exception {
reset( _service,
_nextValve,
_request,
_response );
}
@Test
public final void testGetSessionCookieName() throws IOException, ServletException {
final RequestTrackingHostValve cut = new RequestTrackingHostValve(null, "foo", _service, Statistics.create(),
new AtomicBoolean( true ), new CurrentRequest()) {
@Override
protected String[] getSetCookieHeaders(final Response response) {
final Collection<String> result = response.getHeaders("Set-Cookie");
return result.toArray(new String[result.size()]);
}
};
assertEquals(cut.getSessionCookieName(), "foo");
}
@Test
public final void testProcessRequestNotePresent() throws IOException, ServletException {
_sessionTrackerValve.invoke( _request, _response );
verify( _service, never() ).backupSession( anyString(), anyBoolean(), anyString() );
verify(_request).setNote(eq(RequestTrackingHostValve.REQUEST_PROCESS), eq(Boolean.TRUE));
}
@Test
public final void testBackupSessionNotInvokedWhenNoSessionIdPresent() throws IOException, ServletException {
when( _request.getRequestedSessionId() ).thenReturn( null );
when( _response.getHeader( eq( "Set-Cookie" ) ) ).thenReturn( null );
_sessionTrackerValve.invoke( _request, _response );
verify( _service, never() ).backupSession( anyString(), anyBoolean(), anyString() );
}
@Test
public final void testBackupSessionInvokedWhenResponseCookiePresent() throws IOException, ServletException {
when( _request.getRequestedSessionId() ).thenReturn( null );
final Cookie cookie = new Cookie( _sessionTrackerValve.getSessionCookieName(), "foo" );
setupGetResponseSetCookieHeadersExpectations(_response, new String[]{generateCookieString( cookie )});
_sessionTrackerValve.invoke( _request, _response );
verify( _service ).backupSession( eq( "foo" ), eq( false), anyString() );
}
@Test
public final void testChangeSessionIdForRelocatedSession() throws IOException, ServletException {
final String sessionId = "bar";
final String newSessionId = "newId";
when(_request.getNote(eq(RequestTrackingHostValve.SESSION_ID_CHANGED))).thenReturn(Boolean.TRUE);
when( _request.getRequestedSessionId() ).thenReturn( sessionId );
final Cookie cookie = new Cookie( _sessionTrackerValve.getSessionCookieName(), newSessionId );
setupGetResponseSetCookieHeadersExpectations(_response, new String[]{generateCookieString( cookie )});
_sessionTrackerValve.invoke( _request, _response );
verify( _service ).backupSession( eq( newSessionId ), eq( true ), anyString() );
}
@Test
public final void testRequestFinishedShouldBeInvokedForIgnoredResources() throws IOException, ServletException {
when( _request.getRequestedSessionId() ).thenReturn( "foo" );
when(_request.getRequestURI()).thenReturn("/pixel.gif");
_sessionTrackerValve.invoke( _request, _response );
verify( _service ).requestFinished( eq( "foo" ), anyString() );
}
protected abstract void setupGetResponseSetCookieHeadersExpectations(Response response, String[] result);
@Nonnull
protected String generateCookieString(final Cookie cookie) {
final StringBuffer sb = new StringBuffer();
ServerCookie.appendCookieValue
(sb, cookie.getVersion(), cookie.getName(), cookie.getValue(),
cookie.getPath(), cookie.getDomain(), cookie.getComment(),
cookie.getMaxAge(), cookie.getSecure(), true);
final String setSessionCookieHeader = sb.toString();
return setSessionCookieHeader;
}
}
| zhangwei5095/memcached-session-manager | core/src/test/java/de/javakaffee/web/msm/RequestTrackingHostValveTest.java | Java | apache-2.0 | 7,744 |
/*
* 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.hyracks.algebricks.rewriter.rules.subplan;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.mutable.Mutable;
import org.apache.commons.lang3.mutable.MutableObject;
import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException;
import org.apache.hyracks.algebricks.common.utils.ListSet;
import org.apache.hyracks.algebricks.common.utils.Pair;
import org.apache.hyracks.algebricks.core.algebra.base.ILogicalExpression;
import org.apache.hyracks.algebricks.core.algebra.base.ILogicalOperator;
import org.apache.hyracks.algebricks.core.algebra.base.ILogicalPlan;
import org.apache.hyracks.algebricks.core.algebra.base.IOptimizationContext;
import org.apache.hyracks.algebricks.core.algebra.base.LogicalOperatorTag;
import org.apache.hyracks.algebricks.core.algebra.base.LogicalVariable;
import org.apache.hyracks.algebricks.core.algebra.expressions.ConstantExpression;
import org.apache.hyracks.algebricks.core.algebra.expressions.ScalarFunctionCallExpression;
import org.apache.hyracks.algebricks.core.algebra.expressions.VariableReferenceExpression;
import org.apache.hyracks.algebricks.core.algebra.functions.AlgebricksBuiltinFunctions;
import org.apache.hyracks.algebricks.core.algebra.functions.IFunctionInfo;
import org.apache.hyracks.algebricks.core.algebra.operators.logical.AbstractBinaryJoinOperator;
import org.apache.hyracks.algebricks.core.algebra.operators.logical.AbstractLogicalOperator;
import org.apache.hyracks.algebricks.core.algebra.operators.logical.AggregateOperator;
import org.apache.hyracks.algebricks.core.algebra.operators.logical.AssignOperator;
import org.apache.hyracks.algebricks.core.algebra.operators.logical.DataSourceScanOperator;
import org.apache.hyracks.algebricks.core.algebra.operators.logical.GroupByOperator;
import org.apache.hyracks.algebricks.core.algebra.operators.logical.NestedTupleSourceOperator;
import org.apache.hyracks.algebricks.core.algebra.operators.logical.ProjectOperator;
import org.apache.hyracks.algebricks.core.algebra.operators.logical.SelectOperator;
import org.apache.hyracks.algebricks.core.algebra.operators.logical.SubplanOperator;
import org.apache.hyracks.algebricks.core.algebra.operators.logical.UnnestOperator;
import org.apache.hyracks.algebricks.core.algebra.operators.logical.visitors.VariableUtilities;
import org.apache.hyracks.algebricks.core.algebra.plan.ALogicalPlanImpl;
import org.apache.hyracks.algebricks.core.algebra.properties.FunctionalDependency;
import org.apache.hyracks.algebricks.core.algebra.util.OperatorManipulationUtil;
import org.apache.hyracks.algebricks.core.algebra.util.OperatorPropertiesUtil;
import org.apache.hyracks.algebricks.core.config.AlgebricksConfig;
import org.apache.hyracks.algebricks.core.rewriter.base.IAlgebraicRewriteRule;
import org.apache.hyracks.algebricks.rewriter.util.PhysicalOptimizationsUtil;
/**
* The rule searches for SUBPLAN operator with a optional PROJECT operator and
* an AGGREGATE followed by a join operator.
*
* <pre>
* Before
*
* plan__parent
* SUBPLAN {
* PROJECT?
* AGGREGATE
* plan__nested_A
* INNER_JOIN | LEFT_OUTER_JOIN ($condition, $left, $right)
* plan__nested_B
* }
* plan__child
*
* where $condition does not equal a constant true.
*
* After (This is a general application of the rule, specifics may vary based on the query plan.)
*
* plan__parent
* GROUP_BY {
* PROJECT?
* AGGREGATE
* plan__nested_A
* SELECT( algebricks:not( is_null( $right ) ) )
* NESTED_TUPLE_SOURCE
* }
* SUBPLAN {
* INNER_JOIN | LEFT_OUTER_JOIN ($condition, $left, $right)
* plan__nested_B
* }
* plan__child
* </pre>
*
* @author prestonc
*/
public class IntroduceGroupByForSubplanRule implements IAlgebraicRewriteRule {
@Override
public boolean rewritePre(Mutable<ILogicalOperator> opRef, IOptimizationContext context)
throws AlgebricksException {
return false;
}
@Override
public boolean rewritePost(Mutable<ILogicalOperator> opRef, IOptimizationContext context)
throws AlgebricksException {
AbstractLogicalOperator op0 = (AbstractLogicalOperator) opRef.getValue();
if (op0.getOperatorTag() != LogicalOperatorTag.SUBPLAN) {
return false;
}
SubplanOperator subplan = (SubplanOperator) op0;
Iterator<ILogicalPlan> plansIter = subplan.getNestedPlans().iterator();
ILogicalPlan p = null;
while (plansIter.hasNext()) {
p = plansIter.next();
}
if (p == null) {
return false;
}
if (p.getRoots().size() != 1) {
return false;
}
Mutable<ILogicalOperator> subplanRoot = p.getRoots().get(0);
AbstractLogicalOperator op1 = (AbstractLogicalOperator) subplanRoot.getValue();
Mutable<ILogicalOperator> botRef = subplanRoot;
AbstractLogicalOperator op2;
// Project is optional
if (op1.getOperatorTag() != LogicalOperatorTag.PROJECT) {
op2 = op1;
} else {
ProjectOperator project = (ProjectOperator) op1;
botRef = project.getInputs().get(0);
op2 = (AbstractLogicalOperator) botRef.getValue();
}
if (op2.getOperatorTag() != LogicalOperatorTag.AGGREGATE) {
return false;
}
AggregateOperator aggregate = (AggregateOperator) op2;
Set<LogicalVariable> free = new HashSet<LogicalVariable>();
VariableUtilities.getUsedVariables(aggregate, free);
Mutable<ILogicalOperator> op3Ref = aggregate.getInputs().get(0);
AbstractLogicalOperator op3 = (AbstractLogicalOperator) op3Ref.getValue();
while (op3.getInputs().size() == 1) {
Set<LogicalVariable> prod = new HashSet<LogicalVariable>();
VariableUtilities.getProducedVariables(op3, prod);
free.removeAll(prod);
VariableUtilities.getUsedVariables(op3, free);
botRef = op3Ref;
op3Ref = op3.getInputs().get(0);
op3 = (AbstractLogicalOperator) op3Ref.getValue();
}
if (op3.getOperatorTag() != LogicalOperatorTag.INNERJOIN
&& op3.getOperatorTag() != LogicalOperatorTag.LEFTOUTERJOIN) {
return false;
}
AbstractBinaryJoinOperator join = (AbstractBinaryJoinOperator) op3;
if (join.getCondition().getValue() == ConstantExpression.TRUE) {
return false;
}
VariableUtilities.getUsedVariables(join, free);
AbstractLogicalOperator b0 = (AbstractLogicalOperator) join.getInputs().get(0).getValue();
// see if there's an NTS at the end of the pipeline
NestedTupleSourceOperator outerNts = getNts(b0);
if (outerNts == null) {
AbstractLogicalOperator b1 = (AbstractLogicalOperator) join.getInputs().get(1).getValue();
outerNts = getNts(b1);
if (outerNts == null) {
return false;
}
}
Set<LogicalVariable> pkVars = computeGbyVars(outerNts, free, context);
if (pkVars == null || pkVars.size() < 1) {
// there is no non-trivial primary key, group-by keys are all live variables
// that were produced by descendant or self
ILogicalOperator subplanInput = subplan.getInputs().get(0).getValue();
pkVars = new HashSet<LogicalVariable>();
//get live variables
VariableUtilities.getLiveVariables(subplanInput, pkVars);
//get produced variables
Set<LogicalVariable> producedVars = new HashSet<LogicalVariable>();
VariableUtilities.getProducedVariablesInDescendantsAndSelf(subplanInput, producedVars);
//retain the intersection
pkVars.retainAll(producedVars);
}
AlgebricksConfig.ALGEBRICKS_LOGGER.fine("Found FD for introducing group-by: " + pkVars);
Mutable<ILogicalOperator> rightRef = join.getInputs().get(1);
LogicalVariable testForNull = null;
AbstractLogicalOperator right = (AbstractLogicalOperator) rightRef.getValue();
switch (right.getOperatorTag()) {
case UNNEST: {
UnnestOperator innerUnnest = (UnnestOperator) right;
// Select [ $y != null ]
testForNull = innerUnnest.getVariable();
break;
}
case RUNNINGAGGREGATE: {
ILogicalOperator inputToRunningAggregate = right.getInputs().get(0).getValue();
Set<LogicalVariable> producedVars = new ListSet<LogicalVariable>();
VariableUtilities.getProducedVariables(inputToRunningAggregate, producedVars);
if (!producedVars.isEmpty()) {
// Select [ $y != null ]
testForNull = producedVars.iterator().next();
}
break;
}
case DATASOURCESCAN: {
DataSourceScanOperator innerScan = (DataSourceScanOperator) right;
// Select [ $y != null ]
if (innerScan.getVariables().size() == 1) {
testForNull = innerScan.getVariables().get(0);
}
break;
}
default:
break;
}
if (testForNull == null) {
testForNull = context.newVar();
AssignOperator tmpAsgn = new AssignOperator(testForNull,
new MutableObject<ILogicalExpression>(ConstantExpression.TRUE));
tmpAsgn.getInputs().add(new MutableObject<ILogicalOperator>(rightRef.getValue()));
rightRef.setValue(tmpAsgn);
context.computeAndSetTypeEnvironmentForOperator(tmpAsgn);
}
IFunctionInfo finfoEq = context.getMetadataProvider().lookupFunction(AlgebricksBuiltinFunctions.IS_MISSING);
ILogicalExpression isNullTest = new ScalarFunctionCallExpression(finfoEq,
new MutableObject<ILogicalExpression>(new VariableReferenceExpression(testForNull)));
IFunctionInfo finfoNot = context.getMetadataProvider().lookupFunction(AlgebricksBuiltinFunctions.NOT);
ScalarFunctionCallExpression nonNullTest = new ScalarFunctionCallExpression(finfoNot,
new MutableObject<ILogicalExpression>(isNullTest));
SelectOperator selectNonNull = new SelectOperator(new MutableObject<ILogicalExpression>(nonNullTest), false,
null);
GroupByOperator g = new GroupByOperator();
Mutable<ILogicalOperator> newSubplanRef = new MutableObject<ILogicalOperator>(subplan);
NestedTupleSourceOperator nts = new NestedTupleSourceOperator(new MutableObject<ILogicalOperator>(g));
opRef.setValue(g);
selectNonNull.getInputs().add(new MutableObject<ILogicalOperator>(nts));
List<Mutable<ILogicalOperator>> prodInpList = botRef.getValue().getInputs();
prodInpList.clear();
prodInpList.add(new MutableObject<ILogicalOperator>(selectNonNull));
ILogicalPlan gPlan = new ALogicalPlanImpl(new MutableObject<ILogicalOperator>(subplanRoot.getValue()));
g.getNestedPlans().add(gPlan);
subplanRoot.setValue(op3Ref.getValue());
g.getInputs().add(newSubplanRef);
HashSet<LogicalVariable> underVars = new HashSet<LogicalVariable>();
VariableUtilities.getLiveVariables(subplan.getInputs().get(0).getValue(), underVars);
underVars.removeAll(pkVars);
Map<LogicalVariable, LogicalVariable> mappedVars = buildVarExprList(pkVars, context, g, g.getGroupByList());
context.updatePrimaryKeys(mappedVars);
for (LogicalVariable uv : underVars) {
g.getDecorList().add(new Pair<LogicalVariable, Mutable<ILogicalExpression>>(null,
new MutableObject<ILogicalExpression>(new VariableReferenceExpression(uv))));
}
OperatorPropertiesUtil.typeOpRec(subplanRoot, context);
OperatorPropertiesUtil.typeOpRec(gPlan.getRoots().get(0), context);
context.computeAndSetTypeEnvironmentForOperator(g);
return true;
}
private NestedTupleSourceOperator getNts(AbstractLogicalOperator op) {
AbstractLogicalOperator alo = op;
do {
if (alo.getOperatorTag() == LogicalOperatorTag.NESTEDTUPLESOURCE) {
return (NestedTupleSourceOperator) alo;
}
if (alo.getInputs().size() != 1) {
return null;
}
alo = (AbstractLogicalOperator) alo.getInputs().get(0).getValue();
} while (true);
}
protected Set<LogicalVariable> computeGbyVars(AbstractLogicalOperator op, Set<LogicalVariable> freeVars,
IOptimizationContext context) throws AlgebricksException {
PhysicalOptimizationsUtil.computeFDsAndEquivalenceClasses(op, context);
List<FunctionalDependency> fdList = context.getFDList(op);
if (fdList == null) {
return null;
}
// check if any of the FDs is a key
List<LogicalVariable> all = new ArrayList<LogicalVariable>();
VariableUtilities.getLiveVariables(op, all);
all.retainAll(freeVars);
for (FunctionalDependency fd : fdList) {
if (fd.getTail().containsAll(all)) {
return new HashSet<LogicalVariable>(fd.getHead());
}
}
return null;
}
private Map<LogicalVariable, LogicalVariable> buildVarExprList(Collection<LogicalVariable> vars,
IOptimizationContext context, GroupByOperator g,
List<Pair<LogicalVariable, Mutable<ILogicalExpression>>> outVeList) throws AlgebricksException {
Map<LogicalVariable, LogicalVariable> m = new HashMap<LogicalVariable, LogicalVariable>();
for (LogicalVariable ov : vars) {
LogicalVariable newVar = context.newVar();
ILogicalExpression varExpr = new VariableReferenceExpression(newVar);
outVeList.add(new Pair<LogicalVariable, Mutable<ILogicalExpression>>(ov,
new MutableObject<ILogicalExpression>(varExpr)));
for (ILogicalPlan p : g.getNestedPlans()) {
for (Mutable<ILogicalOperator> r : p.getRoots()) {
OperatorManipulationUtil.substituteVarRec((AbstractLogicalOperator) r.getValue(), ov, newVar, true,
context);
}
}
AbstractLogicalOperator opUnder = (AbstractLogicalOperator) g.getInputs().get(0).getValue();
OperatorManipulationUtil.substituteVarRec(opUnder, ov, newVar, true, context);
m.put(ov, newVar);
}
return m;
}
}
| ty1er/incubator-asterixdb | hyracks-fullstack/algebricks/algebricks-rewriter/src/main/java/org/apache/hyracks/algebricks/rewriter/rules/subplan/IntroduceGroupByForSubplanRule.java | Java | apache-2.0 | 15,726 |
/**
* Copyright 2009 - 2011 Sergio Bossa (sergio.bossa@gmail.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 terrastore.store.features;
import java.io.IOException;
import java.io.Serializable;
import java.util.Map;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.msgpack.MessagePackable;
import org.msgpack.MessageTypeException;
import org.msgpack.MessageUnpackable;
import org.msgpack.Packer;
import org.msgpack.Unpacker;
import terrastore.util.io.MsgPackUtils;
/**
* Update object carrying data about the update function, timeout and parameters.
*
* @author Sergio Bossa
*/
public class Update implements MessagePackable, MessageUnpackable, Serializable {
private static final long serialVersionUID = 12345678901L;
//
private String functionName;
private long timeoutInMillis;
private Map<String, Object> parameters;
public Update(String functionName, long timeoutInMillis, Map<String, Object> parameters) {
this.functionName = functionName;
this.timeoutInMillis = timeoutInMillis;
this.parameters = parameters;
}
public Update() {
}
public long getTimeoutInMillis() {
return timeoutInMillis;
}
public String getFunctionName() {
return functionName;
}
public Map<String, Object> getParameters() {
return parameters;
}
@Override
public void messagePack(Packer packer) throws IOException {
MsgPackUtils.packString(packer, functionName);
MsgPackUtils.packLong(packer, timeoutInMillis);
MsgPackUtils.packGenericMap(packer, parameters);
}
@Override
public void messageUnpack(Unpacker unpacker) throws IOException, MessageTypeException {
functionName = MsgPackUtils.unpackString(unpacker);
timeoutInMillis = MsgPackUtils.unpackLong(unpacker);
parameters = MsgPackUtils.unpackGenericMap(unpacker);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Update) {
Update other = (Update) obj;
return new EqualsBuilder().append(this.functionName, other.functionName).append(this.timeoutInMillis, other.timeoutInMillis).append(this.parameters, other.parameters).
isEquals();
} else {
return false;
}
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(functionName).append(timeoutInMillis).append(parameters).toHashCode();
}
}
| byzhang/terrastore | src/main/java/terrastore/store/features/Update.java | Java | apache-2.0 | 3,088 |
/*
* Copyright 2012, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * 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 Google Inc. 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.jf.dexlib2.writer.pool;
import org.jf.dexlib2.iface.reference.StringReference;
import org.jf.dexlib2.writer.StringSection;
import org.jf.util.ExceptionWithContext;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public class StringPool extends StringTypeBasePool implements StringSection<CharSequence, StringReference> {
public StringPool(@Nonnull DexPool dexPool) {
super(dexPool);
}
public void intern(@Nonnull CharSequence string) {
internedItems.put(string.toString(), 0);
}
public void internNullable(@Nullable CharSequence string) {
if (string != null) {
intern(string);
}
}
@Override public int getItemIndex(@Nonnull StringReference key) {
Integer index = internedItems.get(key.toString());
if (index == null) {
throw new ExceptionWithContext("Item not found.: %s", key.toString());
}
return index;
}
@Override public boolean hasJumboIndexes() {
return internedItems.size() > 65536;
}
}
| 4455jkjh/apktool | dexlib2/src/main/java/org/jf/dexlib2/writer/pool/StringPool.java | Java | apache-2.0 | 2,633 |
/*
* 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; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.ml.inference.allocation;
import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.ResourceAlreadyExistsException;
import org.elasticsearch.ResourceNotFoundException;
import org.elasticsearch.Version;
import org.elasticsearch.cluster.ClusterChangedEvent;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.cluster.metadata.NodesShutdownMetadata;
import org.elasticsearch.cluster.metadata.SingleNodeShutdownMetadata;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodeRole;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.collect.MapBuilder;
import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.util.set.Sets;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.xpack.core.ml.MlMetadata;
import org.elasticsearch.xpack.core.ml.action.StartTrainedModelDeploymentAction;
import org.elasticsearch.xpack.core.ml.action.UpdateTrainedModelAllocationStateAction;
import org.elasticsearch.xpack.core.ml.inference.allocation.AllocationState;
import org.elasticsearch.xpack.core.ml.inference.allocation.RoutingState;
import org.elasticsearch.xpack.core.ml.inference.allocation.RoutingStateAndReason;
import org.elasticsearch.xpack.core.ml.inference.allocation.TrainedModelAllocation;
import org.elasticsearch.xpack.ml.MachineLearning;
import org.elasticsearch.xpack.ml.job.NodeLoadDetector;
import org.elasticsearch.xpack.ml.process.MlMemoryTracker;
import org.junit.Before;
import java.util.Collections;
import java.util.Set;
import java.util.function.Function;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.anEmptyMap;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class TrainedModelAllocationClusterServiceTests extends ESTestCase {
private ClusterService clusterService;
private NodeLoadDetector nodeLoadDetector;
@Before
public void setupObjects() {
clusterService = mock(ClusterService.class);
ClusterSettings clusterSettings = new ClusterSettings(
Settings.EMPTY,
Sets.newHashSet(MachineLearning.MAX_MACHINE_MEMORY_PERCENT, MachineLearning.USE_AUTO_MACHINE_MEMORY_PERCENT)
);
when(clusterService.getClusterSettings()).thenReturn(clusterSettings);
MlMemoryTracker memoryTracker = mock(MlMemoryTracker.class);
when(memoryTracker.isRecentlyRefreshed()).thenReturn(true);
nodeLoadDetector = new NodeLoadDetector(memoryTracker);
}
public void testUpdateModelRoutingTable() {
String modelId = "existing-model";
String nodeId = "ml-node-with-room";
ClusterState currentState = ClusterState.builder(new ClusterName("testUpdateModelRoutingTable"))
.nodes(DiscoveryNodes.builder().add(buildNode("ml-node-with-room", true, ByteSizeValue.ofGb(4).getBytes())).build())
.metadata(
Metadata.builder()
.putCustom(
TrainedModelAllocationMetadata.NAME,
TrainedModelAllocationMetadata.Builder.empty()
.addNewAllocation(
modelId,
TrainedModelAllocation.Builder.empty(newParams(modelId, 10_000L)).addNewRoutingEntry(nodeId)
)
.build()
)
.build()
)
.build();
assertThatStoppingAllocationPreventsMutation(
state -> TrainedModelAllocationClusterService.updateModelRoutingTable(
state,
new UpdateTrainedModelAllocationStateAction.Request(nodeId, modelId, new RoutingStateAndReason(RoutingState.STARTED, ""))
),
currentState
);
ClusterState newState = TrainedModelAllocationClusterService.updateModelRoutingTable(
currentState,
new UpdateTrainedModelAllocationStateAction.Request(nodeId, modelId, new RoutingStateAndReason(RoutingState.STARTED, ""))
);
assertThat(
TrainedModelAllocationMetadata.fromState(newState).getModelAllocation(modelId).getNodeRoutingTable().get(nodeId).getState(),
equalTo(RoutingState.STARTED)
);
expectThrows(
ResourceNotFoundException.class,
() -> TrainedModelAllocationClusterService.updateModelRoutingTable(
currentState,
new UpdateTrainedModelAllocationStateAction.Request(
"missingNode",
modelId,
new RoutingStateAndReason(RoutingState.STARTED, "")
)
)
);
expectThrows(
ResourceNotFoundException.class,
() -> TrainedModelAllocationClusterService.updateModelRoutingTable(
currentState,
new UpdateTrainedModelAllocationStateAction.Request(
nodeId,
"missingModel",
new RoutingStateAndReason(RoutingState.STARTED, "")
)
)
);
// TEST Stopped
// We should allow a "stopped" update on missing models and nodes as entries may have already been deleted
TrainedModelAllocationClusterService.updateModelRoutingTable(
currentState,
new UpdateTrainedModelAllocationStateAction.Request("missingNode", modelId, new RoutingStateAndReason(RoutingState.STOPPED, ""))
);
TrainedModelAllocationClusterService.updateModelRoutingTable(
currentState,
new UpdateTrainedModelAllocationStateAction.Request(nodeId, "missingModel", new RoutingStateAndReason(RoutingState.STOPPED, ""))
);
ClusterState updateState = TrainedModelAllocationClusterService.updateModelRoutingTable(
currentState,
new UpdateTrainedModelAllocationStateAction.Request(nodeId, modelId, new RoutingStateAndReason(RoutingState.STOPPED, ""))
);
assertThat(
TrainedModelAllocationMetadata.fromState(updateState).getModelAllocation(modelId).getNodeRoutingTable(),
not(hasKey(nodeId))
);
}
public void testRemoveAllocation() {
ClusterState clusterStateWithoutAllocation = ClusterState.builder(new ClusterName("testRemoveAllocation"))
.metadata(Metadata.builder().build())
.build();
String modelId = "remove-allocation";
expectThrows(
ResourceNotFoundException.class,
() -> TrainedModelAllocationClusterService.removeAllocation(clusterStateWithoutAllocation, modelId)
);
ClusterState clusterStateWithAllocation = ClusterState.builder(new ClusterName("testRemoveAllocation"))
.metadata(
Metadata.builder()
.putCustom(
TrainedModelAllocationMetadata.NAME,
TrainedModelAllocationMetadata.Builder.empty()
.addNewAllocation(modelId, TrainedModelAllocation.Builder.empty(newParams(modelId, randomNonNegativeLong())))
.build()
)
.build()
)
.build();
assertThat(TrainedModelAllocationMetadata.fromState(clusterStateWithAllocation).getModelAllocation(modelId), is(not(nullValue())));
ClusterState modified = TrainedModelAllocationClusterService.removeAllocation(clusterStateWithAllocation, modelId);
assertThat(TrainedModelAllocationMetadata.fromState(modified).getModelAllocation(modelId), is(nullValue()));
}
public void testRemoveAllAllocations() {
ClusterState clusterStateWithoutAllocation = ClusterState.builder(new ClusterName("testRemoveAllAllocations"))
.metadata(Metadata.builder().build())
.build();
assertThat(
TrainedModelAllocationClusterService.removeAllAllocations(clusterStateWithoutAllocation),
equalTo(clusterStateWithoutAllocation)
);
ClusterState clusterStateWithAllocations = ClusterState.builder(new ClusterName("testRemoveAllAllocations"))
.metadata(
Metadata.builder()
.putCustom(
TrainedModelAllocationMetadata.NAME,
TrainedModelAllocationMetadataTests.randomInstance()
)
.build()
)
.build();
ClusterState modified = TrainedModelAllocationClusterService.removeAllAllocations(clusterStateWithAllocations);
assertThat(TrainedModelAllocationMetadata.fromState(modified).modelAllocations(), is(anEmptyMap()));
}
public void testCreateAllocation() {
ClusterState currentState = ClusterState.builder(new ClusterName("testCreateAllocation"))
.nodes(
DiscoveryNodes.builder()
.add(buildNode("ml-node-with-room", true, ByteSizeValue.ofGb(4).getBytes()))
.add(buildNode("ml-node-without-room", true, 1000L))
.add(buildNode("not-ml-node", false, ByteSizeValue.ofGb(4).getBytes()))
.add(buildNode("ml-node-shutting-down", true, ByteSizeValue.ofGb(4).getBytes()))
.add(buildOldNode("old-ml-node-with-room", true, ByteSizeValue.ofGb(4).getBytes()))
.build()
)
.metadata(Metadata.builder().putCustom(NodesShutdownMetadata.TYPE, shutdownMetadata("ml-node-shutting-down")))
.build();
TrainedModelAllocationClusterService trainedModelAllocationClusterService = createClusterService();
ClusterState newState = trainedModelAllocationClusterService.createModelAllocation(currentState, newParams("new-model", 150));
TrainedModelAllocation createdAllocation = TrainedModelAllocationMetadata.fromState(newState).getModelAllocation("new-model");
assertThat(createdAllocation, is(not(nullValue())));
assertThat(createdAllocation.getNodeRoutingTable().keySet(), hasSize(2));
assertThat(createdAllocation.getNodeRoutingTable(), hasKey("ml-node-with-room"));
assertThat(createdAllocation.getNodeRoutingTable().get("ml-node-with-room").getState(), equalTo(RoutingState.STARTING));
assertThat(createdAllocation.getNodeRoutingTable(), hasKey("ml-node-without-room"));
assertThat(createdAllocation.getNodeRoutingTable().get("ml-node-without-room").getState(), equalTo(RoutingState.FAILED));
assertThat(
createdAllocation.getNodeRoutingTable().get("ml-node-without-room").getReason(),
containsString("This node has insufficient available memory.")
);
expectThrows(
ResourceAlreadyExistsException.class,
() -> trainedModelAllocationClusterService.createModelAllocation(newState, newParams("new-model", 150))
);
}
public void testCreateAllocationWhileResetModeIsTrue() {
ClusterState currentState = ClusterState.builder(new ClusterName("testCreateAllocation"))
.nodes(
DiscoveryNodes.builder()
.add(buildNode("ml-node-with-room", true, ByteSizeValue.ofGb(4).getBytes()))
.build()
)
.metadata(Metadata.builder().putCustom(MlMetadata.TYPE, new MlMetadata.Builder().isResetMode(true).build()))
.build();
TrainedModelAllocationClusterService trainedModelAllocationClusterService = createClusterService();
expectThrows(
ElasticsearchStatusException.class,
() -> trainedModelAllocationClusterService.createModelAllocation(currentState, newParams("new-model", 150))
);
ClusterState stateWithoutReset = ClusterState.builder(new ClusterName("testCreateAllocation"))
.nodes(
DiscoveryNodes.builder()
.add(buildNode("ml-node-with-room", true, ByteSizeValue.ofGb(4).getBytes()))
.build()
)
.metadata(Metadata.builder().putCustom(MlMetadata.TYPE, new MlMetadata.Builder().isResetMode(false).build()))
.build();
// Shouldn't throw
trainedModelAllocationClusterService.createModelAllocation(stateWithoutReset, newParams("new-model", 150));
}
public void testAddRemoveAllocationNodes() {
ClusterState currentState = ClusterState.builder(new ClusterName("testAddRemoveAllocationNodes"))
.nodes(
DiscoveryNodes.builder()
.add(buildNode("ml-node-with-room", true, ByteSizeValue.ofGb(4).getBytes()))
.add(buildNode("new-ml-node-with-room", true, ByteSizeValue.ofGb(4).getBytes()))
.add(buildNode("ml-node-without-room", true, 1000L))
.add(buildNode("not-ml-node", false, ByteSizeValue.ofGb(4).getBytes()))
.add(buildNode("ml-node-shutting-down", true, ByteSizeValue.ofGb(4).getBytes()))
.add(buildOldNode("old-versioned-ml-node-with-room", true, ByteSizeValue.ofGb(4).getBytes()))
.build()
)
.metadata(
Metadata.builder()
.putCustom(NodesShutdownMetadata.TYPE, shutdownMetadata("ml-node-shutting-down"))
.putCustom(
TrainedModelAllocationMetadata.NAME,
TrainedModelAllocationMetadata.Builder.empty()
.addNewAllocation(
"model-1",
TrainedModelAllocation.Builder.empty(newParams("model-1", 10_000))
.addNewRoutingEntry("ml-node-with-room")
.updateExistingRoutingEntry("ml-node-with-room", started())
.addNewRoutingEntry("old-ml-node-with-room")
.updateExistingRoutingEntry("old-ml-node-with-room", started())
.addNewRoutingEntry("ml-node-shutting-down")
)
.addNewAllocation(
"model-2",
TrainedModelAllocation.Builder.empty(newParams("model-2", 10_000))
.addNewRoutingEntry("old-ml-node-with-room")
.updateExistingRoutingEntry("old-ml-node-with-room", started())
)
.build()
)
)
.build();
TrainedModelAllocationClusterService trainedModelAllocationClusterService = createClusterService();
// Stopping shouldn't cause any updates
assertThatStoppingAllocationPreventsMutation(
trainedModelAllocationClusterService::addRemoveAllocationNodes,
currentState
);
ClusterState modified = trainedModelAllocationClusterService.addRemoveAllocationNodes(currentState);
TrainedModelAllocationMetadata trainedModelAllocationMetadata = TrainedModelAllocationMetadata.fromState(modified);
assertThat(trainedModelAllocationMetadata.modelAllocations().keySet(), hasSize(2));
assertThat(trainedModelAllocationMetadata.modelAllocations(), allOf(hasKey("model-1"), hasKey("model-2")));
assertThat(trainedModelAllocationMetadata.getModelAllocation("model-1").getNodeRoutingTable().keySet(), hasSize(3));
assertThat(
trainedModelAllocationMetadata.getModelAllocation("model-1").getNodeRoutingTable(),
allOf(hasKey("ml-node-with-room"), hasKey("new-ml-node-with-room"), hasKey("ml-node-without-room"))
);
assertNodeState(trainedModelAllocationMetadata, "model-1", "ml-node-with-room", RoutingState.STARTED);
assertNodeState(trainedModelAllocationMetadata, "model-1", "new-ml-node-with-room", RoutingState.STARTING);
assertNodeState(trainedModelAllocationMetadata, "model-1", "ml-node-without-room", RoutingState.FAILED);
assertThat(trainedModelAllocationMetadata.getModelAllocation("model-2").getNodeRoutingTable().keySet(), hasSize(3));
assertThat(
trainedModelAllocationMetadata.getModelAllocation("model-2").getNodeRoutingTable(),
allOf(hasKey("ml-node-with-room"), hasKey("new-ml-node-with-room"), hasKey("ml-node-without-room"))
);
assertNodeState(trainedModelAllocationMetadata, "model-2", "ml-node-with-room", RoutingState.STARTING);
assertNodeState(trainedModelAllocationMetadata, "model-2", "new-ml-node-with-room", RoutingState.STARTING);
assertNodeState(trainedModelAllocationMetadata, "model-2", "ml-node-without-room", RoutingState.FAILED);
}
public void testShouldAllocateModels() {
String model1 = "model-1";
String model2 = "model-2";
String mlNode1 = "ml-node-with-room";
String mlNode2 = "new-ml-node-with-room";
DiscoveryNode mlNode1Node = buildNode(mlNode1, true, ByteSizeValue.ofGb(4).getBytes());
DiscoveryNode mlNode2Node = buildNode(mlNode2, true, ByteSizeValue.ofGb(4).getBytes());
ClusterState stateWithTwoNodes = ClusterState.builder(new ClusterName("testShouldAllocateModels"))
.nodes(DiscoveryNodes.builder().add(mlNode1Node).add(mlNode2Node))
.build();
ClusterState stateWithOneNode = ClusterState.builder(new ClusterName("testShouldAllocateModels"))
.nodes(DiscoveryNodes.builder().add(mlNode1Node))
.build();
ClusterState stateWithOneNodeNotMl = ClusterState.builder(new ClusterName("testShouldAllocateModels"))
.nodes(DiscoveryNodes.builder().add(mlNode1Node).add(buildNode("not-ml-node", false, ByteSizeValue.ofGb(4).getBytes())))
.build();
// No metadata in the new state means no allocations, so no updates
assertThat(
TrainedModelAllocationClusterService.shouldAllocateModels(
new ClusterChangedEvent(
"test",
ClusterState.builder(randomFrom(stateWithOneNodeNotMl, stateWithOneNode, stateWithTwoNodes)).build(),
ClusterState.builder(randomFrom(stateWithOneNodeNotMl, stateWithOneNode, stateWithTwoNodes))
.metadata(
Metadata.builder()
.putCustom(
TrainedModelAllocationMetadata.NAME,
TrainedModelAllocationMetadata.Builder.empty()
.addNewAllocation(model1, TrainedModelAllocation.Builder.empty(newParams(model1, 100)))
.build()
)
.build()
)
.build()
)
),
is(false)
);
// Even with metadata changes, unless there are node changes, do nothing
ClusterState randomState = randomFrom(stateWithOneNodeNotMl, stateWithOneNode, stateWithTwoNodes);
assertThat(
TrainedModelAllocationClusterService.shouldAllocateModels(
new ClusterChangedEvent(
"test",
ClusterState.builder(randomState)
.metadata(
Metadata.builder()
.putCustom(TrainedModelAllocationMetadata.NAME, TrainedModelAllocationMetadataTests.randomInstance())
.build()
)
.build(),
ClusterState.builder(randomState)
.metadata(
Metadata.builder()
.putCustom(TrainedModelAllocationMetadata.NAME, TrainedModelAllocationMetadataTests.randomInstance())
.build()
)
.build()
)
),
is(false)
);
// If the node removed is not even an ML node, we should not attempt to re-allocate
assertThat(
TrainedModelAllocationClusterService.shouldAllocateModels(
new ClusterChangedEvent(
"test",
ClusterState.builder(stateWithOneNode)
.metadata(
Metadata.builder()
.putCustom(
TrainedModelAllocationMetadata.NAME,
TrainedModelAllocationMetadata.Builder.empty()
.addNewAllocation(model1, TrainedModelAllocation.Builder.empty(newParams(model1, 100)))
.build()
)
.build()
)
.build(),
ClusterState.builder(stateWithOneNodeNotMl)
.metadata(
Metadata.builder()
.putCustom(
TrainedModelAllocationMetadata.NAME,
TrainedModelAllocationMetadata.Builder.empty()
.addNewAllocation(model1, TrainedModelAllocation.Builder.empty(newParams(model1, 100)))
.build()
)
.build()
)
.build()
)
),
is(false)
);
// If the node removed is an ML node, but no models are allocated to it, we should not attempt to re-allocate
assertThat(
TrainedModelAllocationClusterService.shouldAllocateModels(
new ClusterChangedEvent(
"test",
ClusterState.builder(stateWithOneNode)
.metadata(
Metadata.builder()
.putCustom(
TrainedModelAllocationMetadata.NAME,
TrainedModelAllocationMetadata.Builder.empty()
.addNewAllocation(model1, TrainedModelAllocation.Builder.empty(newParams(model1, 100)))
.build()
)
.build()
)
.build(),
ClusterState.builder(stateWithTwoNodes)
.metadata(
Metadata.builder()
.putCustom(
TrainedModelAllocationMetadata.NAME,
TrainedModelAllocationMetadata.Builder.empty()
.addNewAllocation(model1, TrainedModelAllocation.Builder.empty(newParams(model1, 100)))
.build()
)
.build()
)
.build()
)
),
is(false)
);
// If a new ML node is added, we should attempt to re-allocate
assertThat(
TrainedModelAllocationClusterService.shouldAllocateModels(
new ClusterChangedEvent(
"test",
ClusterState.builder(stateWithTwoNodes)
.metadata(
Metadata.builder()
.putCustom(
TrainedModelAllocationMetadata.NAME,
TrainedModelAllocationMetadata.Builder.empty()
.addNewAllocation(model1, TrainedModelAllocation.Builder.empty(newParams(model1, 100)))
.build()
)
.build()
)
.build(),
ClusterState.builder(stateWithOneNode)
.metadata(
Metadata.builder()
.putCustom(
TrainedModelAllocationMetadata.NAME,
TrainedModelAllocationMetadata.Builder.empty()
.addNewAllocation(model1, TrainedModelAllocation.Builder.empty(newParams(model1, 100)))
.build()
)
.build()
)
.build()
)
),
is(true)
);
// If a new ML node is added, but allocation is stopping, we should not re-allocate
assertThat(
TrainedModelAllocationClusterService.shouldAllocateModels(
new ClusterChangedEvent(
"test",
ClusterState.builder(stateWithTwoNodes)
.metadata(
Metadata.builder()
.putCustom(
TrainedModelAllocationMetadata.NAME,
TrainedModelAllocationMetadata.Builder.empty()
.addNewAllocation(
model1,
TrainedModelAllocation.Builder.empty(newParams(model1, 100)).stopAllocation()
)
.build()
)
.build()
)
.build(),
ClusterState.builder(stateWithOneNode)
.metadata(
Metadata.builder()
.putCustom(
TrainedModelAllocationMetadata.NAME,
TrainedModelAllocationMetadata.Builder.empty()
.addNewAllocation(model1, TrainedModelAllocation.Builder.empty(newParams(model1, 100)))
.build()
)
.build()
)
.build()
)
),
is(false)
);
// If a new ML node is added, but its shutting down, don't re-allocate
assertThat(
TrainedModelAllocationClusterService.shouldAllocateModels(
new ClusterChangedEvent(
"test",
ClusterState.builder(stateWithTwoNodes)
.metadata(
Metadata.builder()
.putCustom(
TrainedModelAllocationMetadata.NAME,
TrainedModelAllocationMetadata.Builder.empty()
.addNewAllocation(model1, TrainedModelAllocation.Builder.empty(newParams(model1, 100)))
.build()
)
.putCustom(NodesShutdownMetadata.TYPE, shutdownMetadata(mlNode2))
.build()
)
.build(),
ClusterState.builder(stateWithOneNode)
.metadata(
Metadata.builder()
.putCustom(
TrainedModelAllocationMetadata.NAME,
TrainedModelAllocationMetadata.Builder.empty()
.addNewAllocation(model1, TrainedModelAllocation.Builder.empty(newParams(model1, 100)))
.build()
)
.build()
)
.build()
)
),
is(false)
);
// If a ML node is removed and its routed to, re-allocate
assertThat(
TrainedModelAllocationClusterService.shouldAllocateModels(
new ClusterChangedEvent(
"test",
ClusterState.builder(stateWithOneNode)
.metadata(
Metadata.builder()
.putCustom(
TrainedModelAllocationMetadata.NAME,
TrainedModelAllocationMetadata.Builder.empty()
.addNewAllocation(
model1,
TrainedModelAllocation.Builder.empty(newParams(model1, 100)).addNewRoutingEntry(mlNode1)
)
.addNewAllocation(
model2,
TrainedModelAllocation.Builder.empty(newParams("model-2", 100))
.addNewRoutingEntry(mlNode1)
.addNewRoutingEntry(mlNode2)
)
.build()
)
.build()
)
.build(),
ClusterState.builder(stateWithTwoNodes)
.metadata(
Metadata.builder()
.putCustom(
TrainedModelAllocationMetadata.NAME,
TrainedModelAllocationMetadata.Builder.empty()
.addNewAllocation(
model1,
TrainedModelAllocation.Builder.empty(newParams(model1, 100)).addNewRoutingEntry(mlNode1)
)
.addNewAllocation(
model2,
TrainedModelAllocation.Builder.empty(newParams("model-2", 100))
.addNewRoutingEntry(mlNode1)
.addNewRoutingEntry(mlNode2)
)
.build()
)
.build()
)
.build()
)
),
is(true)
);
// If a ML node is removed and its routed to, but the allocation is stopping, don't re-allocate
assertThat(
TrainedModelAllocationClusterService.shouldAllocateModels(
new ClusterChangedEvent(
"test",
ClusterState.builder(stateWithOneNode)
.metadata(
Metadata.builder()
.putCustom(
TrainedModelAllocationMetadata.NAME,
TrainedModelAllocationMetadata.Builder.empty()
.addNewAllocation(
model1,
TrainedModelAllocation.Builder.empty(newParams(model1, 100)).addNewRoutingEntry(mlNode1)
)
.addNewAllocation(
model2,
TrainedModelAllocation.Builder.empty(newParams("model-2", 100))
.addNewRoutingEntry(mlNode1)
.addNewRoutingEntry(mlNode2)
.stopAllocation()
)
.build()
)
.build()
)
.build(),
ClusterState.builder(stateWithTwoNodes)
.metadata(
Metadata.builder()
.putCustom(
TrainedModelAllocationMetadata.NAME,
TrainedModelAllocationMetadata.Builder.empty()
.addNewAllocation(
model1,
TrainedModelAllocation.Builder.empty(newParams(model1, 100)).addNewRoutingEntry(mlNode1)
)
.addNewAllocation(
model2,
TrainedModelAllocation.Builder.empty(newParams("model-2", 100))
.addNewRoutingEntry(mlNode1)
.addNewRoutingEntry(mlNode2)
)
.build()
)
.build()
)
.build()
)
),
is(false)
);
}
public void testSetAllocationToStopping() {
ClusterState clusterStateWithoutAllocation = ClusterState.builder(new ClusterName("testSetAllocationToStopping"))
.metadata(Metadata.builder().build())
.build();
String modelId = "stopping-allocation";
expectThrows(
ResourceNotFoundException.class,
() -> TrainedModelAllocationClusterService.setToStopping(clusterStateWithoutAllocation, modelId)
);
ClusterState clusterStateWithAllocation = ClusterState.builder(new ClusterName("testSetAllocationToStopping"))
.metadata(
Metadata.builder()
.putCustom(
TrainedModelAllocationMetadata.NAME,
TrainedModelAllocationMetadata.Builder.empty()
.addNewAllocation(modelId, TrainedModelAllocation.Builder.empty(newParams(modelId, randomNonNegativeLong())))
.build()
)
.build()
)
.build();
TrainedModelAllocationMetadata before = TrainedModelAllocationMetadata.fromState(clusterStateWithAllocation);
assertThat(before.getModelAllocation(modelId), is(not(nullValue())));
assertThat(before.getModelAllocation(modelId).getAllocationState(), equalTo(AllocationState.STARTED));
ClusterState modified = TrainedModelAllocationClusterService.setToStopping(clusterStateWithAllocation, modelId);
assertThat(
TrainedModelAllocationMetadata.fromState(modified).getModelAllocation(modelId).getAllocationState(),
equalTo(AllocationState.STOPPING)
);
}
private void assertThatStoppingAllocationPreventsMutation(
Function<ClusterState, ClusterState> mutationFunction,
ClusterState original
) {
TrainedModelAllocationMetadata tempMetadata = TrainedModelAllocationMetadata.fromState(original);
if (tempMetadata.modelAllocations().isEmpty()) {
return;
}
TrainedModelAllocationMetadata.Builder builder = TrainedModelAllocationMetadata.builder(original);
for (String modelId : tempMetadata.modelAllocations().keySet()) {
builder.getAllocation(modelId).stopAllocation();
}
TrainedModelAllocationMetadata metadataWithStopping = builder.build();
ClusterState originalWithStoppingAllocations = ClusterState.builder(original)
.metadata(Metadata.builder(original.metadata()).putCustom(TrainedModelAllocationMetadata.NAME, metadataWithStopping).build())
.build();
assertThat(
"setting all allocations to stopping did not prevent mutation",
TrainedModelAllocationMetadata.fromState(mutationFunction.apply(originalWithStoppingAllocations)),
equalTo(metadataWithStopping)
);
}
private TrainedModelAllocationClusterService createClusterService() {
return new TrainedModelAllocationClusterService(Settings.EMPTY, clusterService, nodeLoadDetector);
}
private static DiscoveryNode buildNode(String name, boolean isML, long nativeMemory) {
return buildNode(name, isML, nativeMemory, Version.CURRENT);
}
private static DiscoveryNode buildNode(String name, boolean isML, long nativeMemory, Version version) {
return new DiscoveryNode(
name,
name,
buildNewFakeTransportAddress(),
MapBuilder.<String, String>newMapBuilder()
.put(MachineLearning.MACHINE_MEMORY_NODE_ATTR, String.valueOf(nativeMemory))
.put(MachineLearning.MAX_JVM_SIZE_NODE_ATTR, String.valueOf(10))
.put(MachineLearning.MAX_OPEN_JOBS_NODE_ATTR, String.valueOf(10))
.map(),
isML ? DiscoveryNodeRole.roles() : Set.of(DiscoveryNodeRole.DATA_ROLE, DiscoveryNodeRole.MASTER_ROLE),
version
);
}
private static RoutingStateAndReason started() {
return new RoutingStateAndReason(RoutingState.STARTED, "");
}
private static DiscoveryNode buildOldNode(String name, boolean isML, long nativeMemory) {
return buildNode(name, isML, nativeMemory, Version.V_7_15_0);
}
private static StartTrainedModelDeploymentAction.TaskParams newParams(String modelId, long modelSize) {
return new StartTrainedModelDeploymentAction.TaskParams(modelId, modelSize);
}
private static void assertNodeState(TrainedModelAllocationMetadata metadata, String modelId, String nodeId, RoutingState routingState) {
assertThat(metadata.getModelAllocation(modelId).getNodeRoutingTable().get(nodeId).getState(), equalTo(routingState));
}
private static NodesShutdownMetadata shutdownMetadata(String nodeId) {
return new NodesShutdownMetadata(
Collections.singletonMap(
nodeId,
SingleNodeShutdownMetadata.builder()
.setType(SingleNodeShutdownMetadata.Type.REMOVE)
.setStartedAtMillis(randomNonNegativeLong())
.setReason("tests")
.setNodeId(nodeId)
.build()
)
);
}
}
| ern/elasticsearch | x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/inference/allocation/TrainedModelAllocationClusterServiceTests.java | Java | apache-2.0 | 40,420 |
/**
* JBoss, Home of Professional Open Source.
* Copyright 2014-2022 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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.pnc.indyrepositorymanager;
import org.apache.commons.io.IOUtils;
import org.commonjava.indy.client.core.Indy;
import org.commonjava.indy.client.core.util.UrlUtils;
import org.commonjava.indy.model.core.Group;
import org.commonjava.indy.model.core.RemoteRepository;
import org.commonjava.indy.model.core.StoreKey;
import org.commonjava.indy.model.core.StoreType;
import org.jboss.pnc.enums.RepositoryType;
import org.jboss.pnc.indyrepositorymanager.fixture.TestBuildExecution;
import org.jboss.pnc.model.Artifact;
import org.jboss.pnc.spi.repositorymanager.BuildExecution;
import org.jboss.pnc.spi.repositorymanager.RepositoryManagerResult;
import org.jboss.pnc.spi.repositorymanager.model.RepositorySession;
import org.jboss.pnc.test.category.ContainerTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.commonjava.indy.pkg.maven.model.MavenPackageTypeDescriptor.MAVEN_PKG_KEY;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.jboss.pnc.indyrepositorymanager.IndyRepositoryConstants.PUBLIC_GROUP_ID;
import static org.jboss.pnc.indyrepositorymanager.IndyRepositoryConstants.SHARED_IMPORTS_ID;
@Category(ContainerTest.class)
public class ExcludeInternalRepoByRegexTest extends AbstractImportTest {
private static final String INTERNAL = "internal";
private static final String EXTERNAL = "external";
@Override
protected List<String> getIgnoredRepoPatterns() {
List<String> result = new ArrayList<>();
result.add("maven:.+:in.+");
return result;
}
@Test
public void extractBuildArtifacts_ContainsTwoDownloads() throws Exception {
// create a remote repo pointing at our server fixture's 'repo/test' directory.
indy.stores()
.create(
new RemoteRepository(MAVEN_PKG_KEY, INTERNAL, server.formatUrl(INTERNAL)),
"Creating internal test remote repo",
RemoteRepository.class);
indy.stores()
.create(
new RemoteRepository(MAVEN_PKG_KEY, EXTERNAL, server.formatUrl(EXTERNAL)),
"Creating external test remote repo",
RemoteRepository.class);
StoreKey publicKey = new StoreKey(MAVEN_PKG_KEY, StoreType.group, PUBLIC_GROUP_ID);
StoreKey internalKey = new StoreKey(MAVEN_PKG_KEY, StoreType.remote, INTERNAL);
StoreKey externalKey = new StoreKey(MAVEN_PKG_KEY, StoreType.remote, EXTERNAL);
Group publicGroup = indy.stores().load(publicKey, Group.class);
if (publicGroup == null) {
publicGroup = new Group(MAVEN_PKG_KEY, PUBLIC_GROUP_ID, internalKey, externalKey);
indy.stores().create(publicGroup, "creating public group", Group.class);
} else {
publicGroup.setConstituents(Arrays.asList(internalKey, externalKey));
indy.stores().update(publicGroup, "adding test remotes to public group");
}
String internalPath = "org/foo/internal/1.0/internal-1.0.pom";
String externalPath = "org/foo/external/1.1/external-1.1.pom";
String content = "This is a test " + System.currentTimeMillis();
// setup the expectation that the remote repo pointing at this server will request this file...and define its
// content.
server.expect(server.formatUrl(INTERNAL, internalPath), 200, content);
server.expect(server.formatUrl(EXTERNAL, externalPath), 200, content);
// create a dummy non-chained build execution and repo session based on it
BuildExecution execution = new TestBuildExecution();
RepositorySession rc = driver.createBuildRepository(
execution,
accessToken,
accessToken,
RepositoryType.MAVEN,
Collections.emptyMap(),
false);
assertThat(rc, notNullValue());
String baseUrl = rc.getConnectionInfo().getDependencyUrl();
// download the two files via the repo session's dependency URL, which will proxy the test http server
// using the expectations above
assertThat(download(UrlUtils.buildUrl(baseUrl, internalPath)), equalTo(content));
assertThat(download(UrlUtils.buildUrl(baseUrl, externalPath)), equalTo(content));
// extract the build artifacts, which should contain the two imported deps.
// This will also trigger promoting imported artifacts into the shared-imports hosted repo
RepositoryManagerResult repositoryManagerResult = rc.extractBuildArtifacts(true);
List<Artifact> deps = repositoryManagerResult.getDependencies();
System.out.println(deps);
assertThat(deps, notNullValue());
assertThat(deps.size(), equalTo(2));
Indy indy = driver.getIndy(accessToken);
StoreKey sharedImportsKey = new StoreKey(MAVEN_PKG_KEY, StoreType.hosted, SHARED_IMPORTS_ID);
// check that the imports from external locations are available from shared-imports
InputStream stream = indy.content().get(sharedImportsKey, externalPath);
String downloaded = IOUtils.toString(stream, (String) null);
assertThat(downloaded, equalTo(content));
stream.close();
// check that the imports from internal/trusted locations are NOT available from shared-imports
stream = indy.content().get(sharedImportsKey, internalPath);
assertThat(stream, nullValue());
}
}
| project-ncl/pnc | indy-repository-manager/src/test/java/org/jboss/pnc/indyrepositorymanager/ExcludeInternalRepoByRegexTest.java | Java | apache-2.0 | 6,538 |
/*
* Copyright (c) 2010-2014 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.testing.longtest;
import com.evolveum.midpoint.common.LoggingConfigurationManager;
import com.evolveum.midpoint.common.ProfilingConfigurationManager;
import com.evolveum.midpoint.model.impl.sync.ReconciliationTaskHandler;
import com.evolveum.midpoint.model.test.AbstractModelIntegrationTest;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.query.ObjectQuery;
import com.evolveum.midpoint.prism.util.PrismAsserts;
import com.evolveum.midpoint.prism.util.PrismTestUtil;
import com.evolveum.midpoint.schema.ResultHandler;
import com.evolveum.midpoint.schema.constants.MidPointConstants;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.util.ObjectQueryUtil;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.test.util.MidPointTestConstants;
import com.evolveum.midpoint.test.util.TestUtil;
import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException;
import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentPolicyEnforcementType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectTemplateType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemObjectsType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.mutable.MutableInt;
import org.opends.server.types.Entry;
import org.opends.server.types.LDIFImportConfig;
import org.opends.server.util.LDIFException;
import org.opends.server.util.LDIFReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.ContextConfiguration;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
import javax.xml.namespace.QName;
import java.io.File;
import java.io.IOException;
import static com.evolveum.midpoint.test.IntegrationTestTools.display;
import static org.testng.AssertJUnit.assertEquals;
/**
* Mix of various tests for issues that are difficult to replicate using dummy resources.
*
* @author Radovan Semancik
*
*/
@ContextConfiguration(locations = {"classpath:ctx-longtest-test-main.xml"})
@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
public class TestLdapComplex extends AbstractModelIntegrationTest {
public static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "ldap-complex");
public static final File SYSTEM_CONFIGURATION_FILE = new File(COMMON_DIR, "system-configuration.xml");
public static final String SYSTEM_CONFIGURATION_OID = SystemObjectsType.SYSTEM_CONFIGURATION.value();
public static final File USER_TEMPLATE_FILE = new File(TEST_DIR, "user-template.xml");
protected static final File USER_ADMINISTRATOR_FILE = new File(COMMON_DIR, "user-administrator.xml");
protected static final String USER_ADMINISTRATOR_OID = "00000000-0000-0000-0000-000000000002";
protected static final String USER_ADMINISTRATOR_USERNAME = "administrator";
protected static final File ROLE_SUPERUSER_FILE = new File(COMMON_DIR, "role-superuser.xml");
protected static final String ROLE_SUPERUSER_OID = "00000000-0000-0000-0000-000000000004";
protected static final File ROLE_CAPTAIN_FILE = new File(TEST_DIR, "role-captain.xml");
protected static final File ROLE_JUDGE_FILE = new File(TEST_DIR, "role-judge.xml");
protected static final File ROLE_PIRATE_FILE = new File(TEST_DIR, "role-pirate.xml");
protected static final File ROLE_SAILOR_FILE = new File(TEST_DIR, "role-sailor.xml");
protected static final String ROLE_PIRATE_OID = "12345678-d34d-b33f-f00d-555555556603";
protected static final File ROLES_LDIF_FILE = new File(TEST_DIR, "roles.ldif");
protected static final File RESOURCE_OPENDJ_FILE = new File(COMMON_DIR, "resource-opendj-complex.xml");
protected static final String RESOURCE_OPENDJ_NAME = "Localhost OpenDJ";
protected static final String RESOURCE_OPENDJ_OID = "10000000-0000-0000-0000-000000000003";
protected static final String RESOURCE_OPENDJ_NAMESPACE = MidPointConstants.NS_RI;
// Make it at least 1501 so it will go over the 3000 entries size limit
private static final int NUM_LDAP_ENTRIES = 1000;
private static final String LDAP_GROUP_PIRATES_DN = "cn=Pirates,ou=groups,dc=example,dc=com";
protected ResourceType resourceOpenDjType;
protected PrismObject<ResourceType> resourceOpenDj;
@Autowired
private ReconciliationTaskHandler reconciliationTaskHandler;
@Override
protected void startResources() throws Exception {
openDJController.startCleanServer();
}
@AfterClass
public static void stopResources() throws Exception {
openDJController.stop();
}
@Override
public void initSystem(Task initTask, OperationResult initResult) throws Exception {
super.initSystem(initTask, initResult);
modelService.postInit(initResult);
// System Configuration
PrismObject<SystemConfigurationType> config;
try {
config = repoAddObjectFromFile(SYSTEM_CONFIGURATION_FILE, SystemConfigurationType.class, initResult);
} catch (ObjectAlreadyExistsException e) {
throw new ObjectAlreadyExistsException("System configuration already exists in repository;" +
"looks like the previous test haven't cleaned it up", e);
}
LoggingConfigurationManager.configure(
ProfilingConfigurationManager.checkSystemProfilingConfiguration(config),
config.asObjectable().getVersion(), initResult);
// administrator
PrismObject<UserType> userAdministrator = repoAddObjectFromFile(USER_ADMINISTRATOR_FILE, UserType.class, initResult);
repoAddObjectFromFile(ROLE_SUPERUSER_FILE, RoleType.class, initResult);
login(userAdministrator);
// Roles
repoAddObjectFromFile(ROLE_CAPTAIN_FILE, RoleType.class, initResult);
repoAddObjectFromFile(ROLE_JUDGE_FILE, RoleType.class, initResult);
repoAddObjectFromFile(ROLE_PIRATE_FILE, RoleType.class, initResult);
repoAddObjectFromFile(ROLE_SAILOR_FILE, RoleType.class, initResult);
// templates
repoAddObjectFromFile(USER_TEMPLATE_FILE, ObjectTemplateType.class, initResult);
// Resources
resourceOpenDj = importAndGetObjectFromFile(ResourceType.class, RESOURCE_OPENDJ_FILE, RESOURCE_OPENDJ_OID, initTask, initResult);
resourceOpenDjType = resourceOpenDj.asObjectable();
openDJController.setResource(resourceOpenDj);
assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE);
openDJController.addEntriesFromLdifFile(ROLES_LDIF_FILE.getPath());
display("initial LDAP content", openDJController.dumpEntries());
}
@Test
public void test100BigImport() throws Exception {
final String TEST_NAME = "test100BigImport";
TestUtil.displayTestTile(this, TEST_NAME);
// GIVEN
loadEntries("u");
Task task = taskManager.createTaskInstance(TestLdapComplex.class.getName() + "." + TEST_NAME);
task.setOwner(getUser(USER_ADMINISTRATOR_OID));
OperationResult result = task.getResult();
// WHEN
TestUtil.displayWhen(TEST_NAME);
//task.setExtensionPropertyValue(SchemaConstants.MODEL_EXTENSION_WORKER_THREADS, 2);
modelService.importFromResource(RESOURCE_OPENDJ_OID,
new QName(RESOURCE_OPENDJ_NAMESPACE, "AccountObjectClass"), task, result);
// THEN
TestUtil.displayThen(TEST_NAME);
OperationResult subresult = result.getLastSubresult();
TestUtil.assertInProgress("importAccountsFromResource result", subresult);
waitForTaskFinish(task, true, 20000 + NUM_LDAP_ENTRIES*2000);
// THEN
TestUtil.displayThen(TEST_NAME);
int userCount = modelService.countObjects(UserType.class, null, null, task, result);
display("Users", userCount);
assertEquals("Unexpected number of users", NUM_LDAP_ENTRIES+4, userCount);
assertUser("u1", task, result);
}
private void assertUser(String name, Task task, OperationResult result) throws com.evolveum.midpoint.util.exception.ObjectNotFoundException, com.evolveum.midpoint.util.exception.SchemaException, com.evolveum.midpoint.util.exception.SecurityViolationException, com.evolveum.midpoint.util.exception.CommunicationException, com.evolveum.midpoint.util.exception.ConfigurationException {
UserType user = findUserByUsername("u1").asObjectable();
display("user " + name, user.asPrismObject());
assertEquals("Wrong number of assignments", 4, user.getAssignment().size());
}
@Test(enabled = false)
public void test120BigReconciliation() throws Exception {
final String TEST_NAME = "test120BigReconciliation";
TestUtil.displayTestTile(this, TEST_NAME);
// GIVEN
Task task = taskManager.createTaskInstance(TestLdapComplex.class.getName() + "." + TEST_NAME);
task.setOwner(getUser(USER_ADMINISTRATOR_OID));
OperationResult result = task.getResult();
// WHEN
TestUtil.displayWhen(TEST_NAME);
//task.setExtensionPropertyValue(SchemaConstants.MODEL_EXTENSION_WORKER_THREADS, 2);
ResourceType resource = modelService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, task, result).asObjectable();
reconciliationTaskHandler.launch(resource,
new QName(RESOURCE_OPENDJ_NAMESPACE, "AccountObjectClass"), task, result);
// THEN
TestUtil.displayThen(TEST_NAME);
// TODO
// OperationResult subresult = result.getLastSubresult();
// TestUtil.assertInProgress("reconciliation launch result", subresult);
waitForTaskFinish(task, true, 20000 + NUM_LDAP_ENTRIES*2000);
// THEN
TestUtil.displayThen(TEST_NAME);
int userCount = modelService.countObjects(UserType.class, null, null, task, result);
display("Users", userCount);
assertEquals("Unexpected number of users", NUM_LDAP_ENTRIES+4, userCount);
assertUser("u1", task, result);
}
private void loadEntries(String prefix) throws LDIFException, IOException {
long ldapPopStart = System.currentTimeMillis();
for(int i=0; i < NUM_LDAP_ENTRIES; i++) {
String name = "user"+i;
Entry entry = createEntry(prefix+i, name);
openDJController.addEntry(entry);
}
long ldapPopEnd = System.currentTimeMillis();
display("Loaded "+NUM_LDAP_ENTRIES+" LDAP entries in "+((ldapPopEnd-ldapPopStart)/1000)+" seconds");
}
private Entry createEntry(String uid, String name) throws IOException, LDIFException {
StringBuilder sb = new StringBuilder();
String dn = "uid="+uid+","+openDJController.getSuffixPeople();
sb.append("dn: ").append(dn).append("\n");
sb.append("objectClass: inetOrgPerson\n");
sb.append("uid: ").append(uid).append("\n");
sb.append("cn: ").append(name).append("\n");
sb.append("sn: ").append(name).append("\n");
LDIFImportConfig importConfig = new LDIFImportConfig(IOUtils.toInputStream(sb.toString(), "utf-8"));
LDIFReader ldifReader = new LDIFReader(importConfig);
Entry ldifEntry = ldifReader.readEntry();
return ldifEntry;
}
private String toDn(String username) {
return "uid="+username+","+OPENDJ_PEOPLE_SUFFIX;
}
}
| gureronder/midpoint | testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestLdapComplex.java | Java | apache-2.0 | 12,396 |
/*
* Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License. See accompanying
* LICENSE file.
*/
package com.pivotal.gemfirexd.internal.impl.services.cache;
import com.pivotal.gemfirexd.internal.iapi.error.StandardException;
import com.pivotal.gemfirexd.internal.iapi.reference.SQLState;
import com.pivotal.gemfirexd.internal.iapi.services.cache.Cacheable;
import com.pivotal.gemfirexd.internal.iapi.services.cache.CacheableFactory;
/**
* An extension to {@link ConcurrentCache} for GemFireXD that sets the identity
* on a {@link CacheEntry} before inserting into the cache. This is to avoid
* deadlock scenario with DDL read-write locks:
*
* distributed write lock (other VM) -> local write lock -> cache hit with
* existing entry -> {@link CacheEntry#waitUntilIdentityIsSet()}
*
* cache miss -> cache put -> {@link Cacheable#setIdentity(Object)} -> read from
* SYSTABLES -> local read lock
*
* See bug #40683 for more details.
*
* Currently this is only used for <code>TDCacheble</code>s while for other
* {@link Cacheable}s the normal {@link ConcurrentCache} is used.
*
* @see ConcurrentCache
*
* @author swale
*/
final class GfxdConcurrentCache extends ConcurrentCache {
/**
* Creates a new cache manager.
*
* @param holderFactory
* factory which creates <code>Cacheable</code>s
* @param name
* the name of the cache
* @param initialSize
* the initial capacity of the cache
* @param maxSize
* maximum number of elements in the cache
*/
GfxdConcurrentCache(CacheableFactory holderFactory, String name,
int initialSize, int maxSize) {
super(holderFactory, name, initialSize, maxSize);
}
// Overrides of ConcurrentCache
/**
* Find an object in the cache. If it is not present, add it to the cache. The
* returned object is kept until <code>release()</code> is called.
*
* @param key
* identity of the object to find
* @return the cached object, or <code>null</code> if it cannot be found
*/
@Override
public Cacheable find(Object key) throws StandardException {
if (stopped) {
return null;
}
Cacheable item;
CacheEntry entry = cache.get(key);
while (true) {
if (entry != null) {
// Found an entry in the cache, lock it.
entry.lock();
if (entry.isValid()) {
try {
// Entry is still valid. Return it.
item = entry.getCacheable();
// The object is already cached. Increase the use count and
// return it.
entry.keep(true);
return item;
} finally {
entry.unlock();
}
}
else {
// This entry has been removed from the cache while we were
// waiting for the lock. Unlock it and try again.
entry.unlock();
entry = cache.get(key);
}
}
else {
entry = new CacheEntry(true);
// Lock the entry before it's inserted in free slot.
entry.lock();
try {
// The object is not cached. Insert the entry into a free
// slot and retrieve a reusable Cacheable.
item = insertIntoFreeSlot(key, entry);
} finally {
entry.unlock();
}
// Set the identity without holding the lock on the entry. If we
// hold the lock, we may run into a deadlock if the user code in
// setIdentity() re-enters the buffer manager.
Cacheable itemWithIdentity = item.setIdentity(key);
if (itemWithIdentity != null) {
entry.setCacheable(itemWithIdentity);
// add the entry to cache
CacheEntry oldEntry = cache.putIfAbsent(key, entry);
if (oldEntry != null) {
// Someone inserted the entry while we created a new
// one. Retry with the entry currently in the cache.
entry = oldEntry;
}
else {
// We successfully inserted a new entry.
return itemWithIdentity;
}
}
else {
return null;
}
}
}
}
/**
* Create an object in the cache. The object is kept until
* <code>release()</code> is called.
*
* @param key
* identity of the object to create
* @param createParameter
* parameters passed to <code>Cacheable.createIdentity()</code>
* @return a reference to the cached object, or <code>null</code> if the
* object cannot be created
* @exception StandardException
* if the object is already in the cache, or if some other error
* occurs
* @see Cacheable#createIdentity(Object,Object)
*/
@Override
public Cacheable create(Object key, Object createParameter)
throws StandardException {
if (stopped) {
return null;
}
Cacheable item;
CacheEntry entry = new CacheEntry(true);
// Lock the entry before it's inserted in free slot.
entry.lock();
try {
// The object is not cached. Insert the entry into a free
// slot and retrieve a reusable Cacheable.
item = insertIntoFreeSlot(key, entry);
} finally {
entry.unlock();
}
// Create the identity without holding the lock on the entry.
// Otherwise, we may run into a deadlock if the user code in
// createIdentity() re-enters the buffer manager.
Cacheable itemWithIdentity = item.createIdentity(key, createParameter);
if (itemWithIdentity != null) {
entry.setCacheable(itemWithIdentity);
if (cache.putIfAbsent(key, entry) != null) {
// We can't create the object if it's already in the cache.
throw StandardException.newException(SQLState.OBJECT_EXISTS_IN_CACHE,
name, key);
}
}
return itemWithIdentity;
}
}
| papicella/snappy-store | gemfirexd/core/src/main/java/com/pivotal/gemfirexd/internal/impl/services/cache/GfxdConcurrentCache.java | Java | apache-2.0 | 6,422 |
/*
* 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.test;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.jar.JarOutputStream;
import java.util.zip.ZipEntry;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.io.ByteStreams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.Path;
import org.apache.pig.ExecType;
import org.apache.pig.PigServer;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* Ensure classes from a registered jar are available in the UDFContext.
* Please see PIG-2532 for additional details.
*/
public class TestRegisteredJarVisibility {
private static final Log LOG = LogFactory.getLog(TestRegisteredJarVisibility.class);
private static final String JAR_FILE_NAME = "test-foo-loader.jar";
private static final String PACKAGE_NAME = "org.apache.pig.test";
// Actual data is not important. Reusing an existing input file.
private static final File INPUT_FILE = new File("test/data/pigunit/top_queries_input_data.txt");
private static MiniCluster cluster;
private static File jarFile;
@BeforeClass()
public static void setUp() throws IOException {
String testResourcesDir = "test/resources/" + PACKAGE_NAME.replace(".", "/");
String testBuildDataDir = "build/test/data";
// Create the test data directory if needed
File testDataDir = new File(testBuildDataDir,
TestRegisteredJarVisibility.class.getCanonicalName());
testDataDir.mkdirs();
jarFile = new File(testDataDir, JAR_FILE_NAME);
File[] javaFiles = new File[]{
new File(testResourcesDir, "RegisteredJarVisibilityLoader.java"),
new File(testResourcesDir, "RegisteredJarVisibilitySchema.java")};
List<File> classFiles = compile(javaFiles);
// Canonical class name to class file
Map<String, File> filesToJar = Maps.newHashMap();
for (File classFile : classFiles) {
filesToJar.put(
PACKAGE_NAME + "." + classFile.getName().replace(".class", ""),
classFile);
}
jar(filesToJar);
cluster = MiniCluster.buildCluster();
}
@AfterClass()
public static void tearDown() {
cluster.shutDown();
}
@Test()
public void testRegisteredJarVisibilitySchemaNotOnClasspath() {
boolean exceptionThrown = false;
try {
Class.forName("org.apache.pig.test.FooSchema");
} catch (ClassNotFoundException e) {
exceptionThrown = true;
}
Assert.assertTrue(exceptionThrown);
}
@Test()
public void testRegisteredJarVisibility() throws IOException {
cluster.getFileSystem().copyFromLocalFile(
new Path("file://" + INPUT_FILE.getAbsolutePath()), new Path(INPUT_FILE.getName()));
PigServer pigServer = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
String query = "register " + jarFile.getAbsolutePath() + ";\n"
+ "a = load '" + INPUT_FILE.getName()
+ "' using org.apache.pig.test.RegisteredJarVisibilityLoader();";
LOG.info("Running pig script:\n" + query);
pigServer.registerScript(new ByteArrayInputStream(query.getBytes()));
pigServer.openIterator("a");
pigServer.shutdown();
}
private static List<File> compile(File[] javaFiles) {
LOG.info("Compiling: " + Arrays.asList(javaFiles));
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> compilationUnits1 =
fileManager.getJavaFileObjects(javaFiles);
JavaCompiler.CompilationTask task =
compiler.getTask(null, fileManager, null, null, null, compilationUnits1);
task.call();
List<File> classFiles = Lists.newArrayList();
for (File javaFile : javaFiles) {
File classFile = new File(javaFile.getAbsolutePath().replace(".java", ".class"));
classFile.deleteOnExit();
Assert.assertTrue(classFile.exists());
classFiles.add(classFile);
LOG.info("Created " + classFile.getAbsolutePath());
}
return classFiles;
}
/**
* Create a jar file containing the generated classes.
*
* @param filesToJar map of canonical class name to class file
* @throws IOException on error
*/
private static void jar(Map<String, File> filesToJar) throws IOException {
LOG.info("Creating jar file containing: " + filesToJar);
JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarFile.getAbsolutePath()));
try {
for (Map.Entry<String, File> entry : filesToJar.entrySet()) {
String zipEntryName = entry.getKey().replace(".", "/") + ".class";
LOG.info("Adding " + zipEntryName + " to " + jarFile.getAbsolutePath());
jos.putNextEntry(new ZipEntry(zipEntryName));
InputStream classInputStream = new FileInputStream(entry.getValue().getAbsolutePath());
try {
ByteStreams.copy(classInputStream, jos);
} finally {
classInputStream.close();
}
}
} finally {
jos.close();
}
Assert.assertTrue(jarFile.exists());
LOG.info("Created " + jarFile.getAbsolutePath());
}
}
| internetarchive/pig | test/org/apache/pig/test/TestRegisteredJarVisibility.java | Java | apache-2.0 | 6,888 |
package com.kodcu.service.extension.chart;
import com.kodcu.controller.ApplicationController;
import com.kodcu.other.Current;
import com.kodcu.service.ThreadService;
import javafx.scene.chart.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* Created by usta on 31.03.2015.
*/
@Component("area-bean")
public class AreaChartBuilderService extends XYChartBuilderService {
private final ThreadService threadService;
private final Current current;
private final ApplicationController controller;
@Autowired
public AreaChartBuilderService(ThreadService threadService, Current current, ApplicationController controller) {
super(threadService, current, controller);
this.threadService = threadService;
this.current = current;
this.controller = controller;
}
@Override
protected XYChart<Number, Number> createXYChart() {
final NumberAxis xAxis = new NumberAxis();
final NumberAxis yAxis = new NumberAxis();
final XYChart<Number, Number> lineChart = new AreaChart<Number, Number>(xAxis, yAxis);
return lineChart;
}
}
| gastaldi/AsciidocFX | src/main/java/com/kodcu/service/extension/chart/AreaChartBuilderService.java | Java | apache-2.0 | 1,187 |
package com.taobao.zeus.broadcast.alarm;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.taobao.zeus.model.LogDescriptor;
import com.taobao.zeus.store.UserManager;
import com.taobao.zeus.store.mysql.MysqlLogManager;
import com.taobao.zeus.store.mysql.persistence.ZeusUser;
import com.taobao.zeus.util.Environment;
public class MailAlarm extends AbstractZeusAlarm {
private static Logger log = LoggerFactory.getLogger(MailAlarm.class);
@Autowired
private UserManager userManager;
@Autowired
private MysqlLogManager zeusLogManager;
private static String host = Environment.getHost();// 邮件服务器
private static String port = Environment.getPort();// 端口
private static String from = Environment.getSendFrom();// 发送者
private static String user = Environment.getUsername();// 用户名
private static String password = Environment.getPassword();// 密码
@Override
public void alarm(String jobId, List<String> users, String title, String content)
throws Exception {
List<ZeusUser> userList = userManager.findListByUidByOrder(users);
List<String> emails = new ArrayList<String>();
if (userList != null && userList.size() > 0) {
for (ZeusUser user : userList) {
String userEmail = user.getEmail();
if (userEmail != null && !userEmail.isEmpty()
&& userEmail.contains("@")) {
if (userEmail.contains(";")) {
String[] userEmails = userEmail.split(";");
for (String ems : userEmails) {
if (ems.contains("@")) {
emails.add(ems);
}
}
} else {
emails.add(userEmail);
}
}
}
if (emails.size() > 0) {
content = content.replace("<br/>", "\r\n");
sendEmail(jobId, emails, title, content);
/*try{
LogDescriptor logDescriptor = new LogDescriptor();
logDescriptor.setLogType("email");
logDescriptor.setIp(InetAddress.getLocalHost().getHostAddress());
logDescriptor.setUserName("zeus");
logDescriptor.setUrl(jobId);
logDescriptor.setRpc(emails.toString());
logDescriptor.setDelegate(title);
logDescriptor.setMethod("");
// logDescriptor.setDescription((content.length()>4000 ? content.substring(4000) : content));
logDescriptor.setDescription("");
zeusLogManager.addLog(logDescriptor);
}catch(Exception ex){
log.error(ex.toString());
}*/
}
}
}
public void sendEmail(String jobId, List<String> emails, String subject,
String body) {
try {
log.info( "jobId: " + jobId +" begin to send the email!");
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.auth", "true");
Transport transport = null;
Session session = Session.getDefaultInstance(props, null);
transport = session.getTransport("smtp");
transport.connect(host, user, password);
MimeMessage msg = new MimeMessage(session);
msg.setSentDate(new Date());
InternetAddress fromAddress = new InternetAddress(from);
msg.setFrom(fromAddress);
InternetAddress[] toAddress = new InternetAddress[emails.size()];
for (int i = 0; i < emails.size(); i++) {
toAddress[i] = new InternetAddress(emails.get(i));
}
msg.setRecipients(Message.RecipientType.TO, toAddress);
msg.setSubject(subject, "UTF-8");
msg.setText(body, "UTF-8");
msg.saveChanges();
transport.sendMessage(msg, msg.getAllRecipients());
log.info("jobId: " + jobId + " send email: " + emails + "; from: " + from + " subject: "
+ subject + ", send success!");
} catch (NoSuchProviderException e) {
log.error("jobId: " + jobId + " fail to send the mail. ", e);
} catch (MessagingException e) {
log.error("jobId: " + jobId + " fail to send the mail. ", e);
} catch (Exception e) {
log.error("jobId: " + jobId + " fail to send the mail. ", e);
}
}
}
| wwzhe/dataworks-zeus | schedule/src/main/java/com/taobao/zeus/broadcast/alarm/MailAlarm.java | Java | apache-2.0 | 4,315 |
/**
* 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.felix.karaf.tooling.features;
import org.apache.maven.artifact.Artifact;
import org.easymock.EasyMock;
import static org.easymock.EasyMock.*;
import junit.framework.TestCase;
/**
* Test cases for {@link GenerateFeaturesXmlMojo}
*/
public class GenerateFeaturesXmlMojoTest extends TestCase {
public void testToString() throws Exception {
Artifact artifact = EasyMock.createMock(Artifact.class);
expect(artifact.getGroupId()).andReturn("org.apache.felix.karaf.test");
expect(artifact.getArtifactId()).andReturn("test-artifact");
expect(artifact.getVersion()).andReturn("1.2.3");
replay(artifact);
assertEquals("org.apache.felix.karaf.test/test-artifact/1.2.3", GenerateFeaturesXmlMojo.toString(artifact));
}
}
| igor-sfdc/felix | tooling/features-maven-plugin/src/test/java/org/apache/felix/karaf/tooling/features/GenerateFeaturesXmlMojoTest.java | Java | apache-2.0 | 1,613 |
/**
* Copyright 2015 IBM Corp.
*
* 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.ibmcloud.contest.phonebook;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
/**
* Throw a 400 status code
*/
public class BadRequestException extends WebApplicationException {
private static final long serialVersionUID = 1L;
public BadRequestException() {
super(Response.status(Status.BAD_REQUEST).build());
}
}
| ibmkendrick/phonebookdemo-v2 | src/main/java/com/ibmcloud/contest/phonebook/BadRequestException.java | Java | apache-2.0 | 1,011 |
package org.zstack.sdk.zwatch.monitorgroup.api;
import org.zstack.sdk.zwatch.monitorgroup.entity.MonitorTemplateInventory;
public class CreateMonitorTemplateResult {
public MonitorTemplateInventory inventory;
public void setInventory(MonitorTemplateInventory inventory) {
this.inventory = inventory;
}
public MonitorTemplateInventory getInventory() {
return this.inventory;
}
}
| zstackorg/zstack | sdk/src/main/java/org/zstack/sdk/zwatch/monitorgroup/api/CreateMonitorTemplateResult.java | Java | apache-2.0 | 417 |
/*-
* Copyright (C) 2007 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.
*
* Modifications:
* -Changed package name
* -Removed Android dependencies
* -Removed/replaced Java SE dependencies
* -Removed/replaced annotations
*/
package com.google.authenticator.blackberry;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.ByteArrayOutputStream;
import java.util.Vector;
/**
* Immutable URI reference. A URI reference includes a URI and a fragment, the
* component of the URI following a '#'. Builds and parses URI references
* which conform to
* <a href="http://www.faqs.org/rfcs/rfc2396.html">RFC 2396</a>.
*
* <p>In the interest of performance, this class performs little to no
* validation. Behavior is undefined for invalid input. This class is very
* forgiving--in the face of invalid input, it will return garbage
* rather than throw an exception unless otherwise specified.
*/
public abstract class Uri {
/*
This class aims to do as little up front work as possible. To accomplish
that, we vary the implementation dependending on what the user passes in.
For example, we have one implementation if the user passes in a
URI string (StringUri) and another if the user passes in the
individual components (OpaqueUri).
*Concurrency notes*: Like any truly immutable object, this class is safe
for concurrent use. This class uses a caching pattern in some places where
it doesn't use volatile or synchronized. This is safe to do with ints
because getting or setting an int is atomic. It's safe to do with a String
because the internal fields are final and the memory model guarantees other
threads won't see a partially initialized instance. We are not guaranteed
that some threads will immediately see changes from other threads on
certain platforms, but we don't mind if those threads reconstruct the
cached result. As a result, we get thread safe caching with no concurrency
overhead, which means the most common case, access from a single thread,
is as fast as possible.
From the Java Language spec.:
"17.5 Final Field Semantics
... when the object is seen by another thread, that thread will always
see the correctly constructed version of that object's final fields.
It will also see versions of any object or array referenced by
those final fields that are at least as up-to-date as the final fields
are."
In that same vein, all non-transient fields within Uri
implementations should be final and immutable so as to ensure true
immutability for clients even when they don't use proper concurrency
control.
For reference, from RFC 2396:
"4.3. Parsing a URI Reference
A URI reference is typically parsed according to the four main
components and fragment identifier in order to determine what
components are present and whether the reference is relative or
absolute. The individual components are then parsed for their
subparts and, if not opaque, to verify their validity.
Although the BNF defines what is allowed in each component, it is
ambiguous in terms of differentiating between an authority component
and a path component that begins with two slash characters. The
greedy algorithm is used for disambiguation: the left-most matching
rule soaks up as much of the URI reference string as it is capable of
matching. In other words, the authority component wins."
The "four main components" of a hierarchical URI consist of
<scheme>://<authority><path>?<query>
*/
/**
* NOTE: EMPTY accesses this field during its own initialization, so this
* field *must* be initialized first, or else EMPTY will see a null value!
*
* Placeholder for strings which haven't been cached. This enables us
* to cache null. We intentionally create a new String instance so we can
* compare its identity and there is no chance we will confuse it with
* user data.
*/
private static final String NOT_CACHED = new String("NOT CACHED");
/**
* The empty URI, equivalent to "".
*/
public static final Uri EMPTY = new HierarchicalUri(null, Part.NULL,
PathPart.EMPTY, Part.NULL, Part.NULL);
/**
* Prevents external subclassing.
*/
private Uri() {}
/**
* Returns true if this URI is hierarchical like "http://google.com".
* Absolute URIs are hierarchical if the scheme-specific part starts with
* a '/'. Relative URIs are always hierarchical.
*/
public abstract boolean isHierarchical();
/**
* Returns true if this URI is opaque like "mailto:nobody@google.com". The
* scheme-specific part of an opaque URI cannot start with a '/'.
*/
public boolean isOpaque() {
return !isHierarchical();
}
/**
* Returns true if this URI is relative, i.e. if it doesn't contain an
* explicit scheme.
*
* @return true if this URI is relative, false if it's absolute
*/
public abstract boolean isRelative();
/**
* Returns true if this URI is absolute, i.e. if it contains an
* explicit scheme.
*
* @return true if this URI is absolute, false if it's relative
*/
public boolean isAbsolute() {
return !isRelative();
}
/**
* Gets the scheme of this URI. Example: "http"
*
* @return the scheme or null if this is a relative URI
*/
public abstract String getScheme();
/**
* Gets the scheme-specific part of this URI, i.e. everything between the
* scheme separator ':' and the fragment separator '#'. If this is a
* relative URI, this method returns the entire URI. Decodes escaped octets.
*
* <p>Example: "//www.google.com/search?q=android"
*
* @return the decoded scheme-specific-part
*/
public abstract String getSchemeSpecificPart();
/**
* Gets the scheme-specific part of this URI, i.e. everything between the
* scheme separator ':' and the fragment separator '#'. If this is a
* relative URI, this method returns the entire URI. Leaves escaped octets
* intact.
*
* <p>Example: "//www.google.com/search?q=android"
*
* @return the decoded scheme-specific-part
*/
public abstract String getEncodedSchemeSpecificPart();
/**
* Gets the decoded authority part of this URI. For
* server addresses, the authority is structured as follows:
* {@code [ userinfo '@' ] host [ ':' port ]}
*
* <p>Examples: "google.com", "bob@google.com:80"
*
* @return the authority for this URI or null if not present
*/
public abstract String getAuthority();
/**
* Gets the encoded authority part of this URI. For
* server addresses, the authority is structured as follows:
* {@code [ userinfo '@' ] host [ ':' port ]}
*
* <p>Examples: "google.com", "bob@google.com:80"
*
* @return the authority for this URI or null if not present
*/
public abstract String getEncodedAuthority();
/**
* Gets the decoded user information from the authority.
* For example, if the authority is "nobody@google.com", this method will
* return "nobody".
*
* @return the user info for this URI or null if not present
*/
public abstract String getUserInfo();
/**
* Gets the encoded user information from the authority.
* For example, if the authority is "nobody@google.com", this method will
* return "nobody".
*
* @return the user info for this URI or null if not present
*/
public abstract String getEncodedUserInfo();
/**
* Gets the encoded host from the authority for this URI. For example,
* if the authority is "bob@google.com", this method will return
* "google.com".
*
* @return the host for this URI or null if not present
*/
public abstract String getHost();
/**
* Gets the port from the authority for this URI. For example,
* if the authority is "google.com:80", this method will return 80.
*
* @return the port for this URI or -1 if invalid or not present
*/
public abstract int getPort();
/**
* Gets the decoded path.
*
* @return the decoded path, or null if this is not a hierarchical URI
* (like "mailto:nobody@google.com") or the URI is invalid
*/
public abstract String getPath();
/**
* Gets the encoded path.
*
* @return the encoded path, or null if this is not a hierarchical URI
* (like "mailto:nobody@google.com") or the URI is invalid
*/
public abstract String getEncodedPath();
/**
* Gets the decoded query component from this URI. The query comes after
* the query separator ('?') and before the fragment separator ('#'). This
* method would return "q=android" for
* "http://www.google.com/search?q=android".
*
* @return the decoded query or null if there isn't one
*/
public abstract String getQuery();
/**
* Gets the encoded query component from this URI. The query comes after
* the query separator ('?') and before the fragment separator ('#'). This
* method would return "q=android" for
* "http://www.google.com/search?q=android".
*
* @return the encoded query or null if there isn't one
*/
public abstract String getEncodedQuery();
/**
* Gets the decoded fragment part of this URI, everything after the '#'.
*
* @return the decoded fragment or null if there isn't one
*/
public abstract String getFragment();
/**
* Gets the encoded fragment part of this URI, everything after the '#'.
*
* @return the encoded fragment or null if there isn't one
*/
public abstract String getEncodedFragment();
/**
* Gets the decoded path segments.
*
* @return decoded path segments, each without a leading or trailing '/'
*/
public abstract String[] getPathSegments();
/**
* Gets the decoded last segment in the path.
*
* @return the decoded last segment or null if the path is empty
*/
public abstract String getLastPathSegment();
/**
* Compares this Uri to another object for equality. Returns true if the
* encoded string representations of this Uri and the given Uri are
* equal. Case counts. Paths are not normalized. If one Uri specifies a
* default port explicitly and the other leaves it implicit, they will not
* be considered equal.
*/
public boolean equals(Object o) {
if (!(o instanceof Uri)) {
return false;
}
Uri other = (Uri) o;
return toString().equals(other.toString());
}
/**
* Hashes the encoded string represention of this Uri consistently with
* {@link #equals(Object)}.
*/
public int hashCode() {
return toString().hashCode();
}
/**
* Compares the string representation of this Uri with that of
* another.
*/
public int compareTo(Uri other) {
return toString().compareTo(other.toString());
}
/**
* Returns the encoded string representation of this URI.
* Example: "http://google.com/"
*/
public abstract String toString();
/**
* Constructs a new builder, copying the attributes from this Uri.
*/
public abstract Builder buildUpon();
/** Index of a component which was not found. */
private final static int NOT_FOUND = -1;
/** Placeholder value for an index which hasn't been calculated yet. */
private final static int NOT_CALCULATED = -2;
/**
* Error message presented when a user tries to treat an opaque URI as
* hierarchical.
*/
private static final String NOT_HIERARCHICAL
= "This isn't a hierarchical URI.";
/** Default encoding. */
private static final String DEFAULT_ENCODING = "UTF-8";
/**
* Creates a Uri which parses the given encoded URI string.
*
* @param uriString an RFC 2396-compliant, encoded URI
* @throws NullPointerException if uriString is null
* @return Uri for this given uri string
*/
public static Uri parse(String uriString) {
return new StringUri(uriString);
}
/**
* An implementation which wraps a String URI. This URI can be opaque or
* hierarchical, but we extend AbstractHierarchicalUri in case we need
* the hierarchical functionality.
*/
private static class StringUri extends AbstractHierarchicalUri {
/** Used in parcelling. */
static final int TYPE_ID = 1;
/** URI string representation. */
private final String uriString;
private StringUri(String uriString) {
if (uriString == null) {
throw new NullPointerException("uriString");
}
this.uriString = uriString;
}
/** Cached scheme separator index. */
private volatile int cachedSsi = NOT_CALCULATED;
/** Finds the first ':'. Returns -1 if none found. */
private int findSchemeSeparator() {
return cachedSsi == NOT_CALCULATED
? cachedSsi = uriString.indexOf(':')
: cachedSsi;
}
/** Cached fragment separator index. */
private volatile int cachedFsi = NOT_CALCULATED;
/** Finds the first '#'. Returns -1 if none found. */
private int findFragmentSeparator() {
return cachedFsi == NOT_CALCULATED
? cachedFsi = uriString.indexOf('#', findSchemeSeparator())
: cachedFsi;
}
public boolean isHierarchical() {
int ssi = findSchemeSeparator();
if (ssi == NOT_FOUND) {
// All relative URIs are hierarchical.
return true;
}
if (uriString.length() == ssi + 1) {
// No ssp.
return false;
}
// If the ssp starts with a '/', this is hierarchical.
return uriString.charAt(ssi + 1) == '/';
}
public boolean isRelative() {
// Note: We return true if the index is 0
return findSchemeSeparator() == NOT_FOUND;
}
private volatile String scheme = NOT_CACHED;
public String getScheme() {
boolean cached = (scheme != NOT_CACHED);
return cached ? scheme : (scheme = parseScheme());
}
private String parseScheme() {
int ssi = findSchemeSeparator();
return ssi == NOT_FOUND ? null : uriString.substring(0, ssi);
}
private Part ssp;
private Part getSsp() {
return ssp == null ? ssp = Part.fromEncoded(parseSsp()) : ssp;
}
public String getEncodedSchemeSpecificPart() {
return getSsp().getEncoded();
}
public String getSchemeSpecificPart() {
return getSsp().getDecoded();
}
private String parseSsp() {
int ssi = findSchemeSeparator();
int fsi = findFragmentSeparator();
// Return everything between ssi and fsi.
return fsi == NOT_FOUND
? uriString.substring(ssi + 1)
: uriString.substring(ssi + 1, fsi);
}
private Part authority;
private Part getAuthorityPart() {
if (authority == null) {
String encodedAuthority
= parseAuthority(this.uriString, findSchemeSeparator());
return authority = Part.fromEncoded(encodedAuthority);
}
return authority;
}
public String getEncodedAuthority() {
return getAuthorityPart().getEncoded();
}
public String getAuthority() {
return getAuthorityPart().getDecoded();
}
private PathPart path;
private PathPart getPathPart() {
return path == null
? path = PathPart.fromEncoded(parsePath())
: path;
}
public String getPath() {
return getPathPart().getDecoded();
}
public String getEncodedPath() {
return getPathPart().getEncoded();
}
public String[] getPathSegments() {
return getPathPart().getPathSegments().segments;
}
private String parsePath() {
String uriString = this.uriString;
int ssi = findSchemeSeparator();
// If the URI is absolute.
if (ssi > -1) {
// Is there anything after the ':'?
boolean schemeOnly = ssi + 1 == uriString.length();
if (schemeOnly) {
// Opaque URI.
return null;
}
// A '/' after the ':' means this is hierarchical.
if (uriString.charAt(ssi + 1) != '/') {
// Opaque URI.
return null;
}
} else {
// All relative URIs are hierarchical.
}
return parsePath(uriString, ssi);
}
private Part query;
private Part getQueryPart() {
return query == null
? query = Part.fromEncoded(parseQuery()) : query;
}
public String getEncodedQuery() {
return getQueryPart().getEncoded();
}
private String parseQuery() {
// It doesn't make sense to cache this index. We only ever
// calculate it once.
int qsi = uriString.indexOf('?', findSchemeSeparator());
if (qsi == NOT_FOUND) {
return null;
}
int fsi = findFragmentSeparator();
if (fsi == NOT_FOUND) {
return uriString.substring(qsi + 1);
}
if (fsi < qsi) {
// Invalid.
return null;
}
return uriString.substring(qsi + 1, fsi);
}
public String getQuery() {
return getQueryPart().getDecoded();
}
private Part fragment;
private Part getFragmentPart() {
return fragment == null
? fragment = Part.fromEncoded(parseFragment()) : fragment;
}
public String getEncodedFragment() {
return getFragmentPart().getEncoded();
}
private String parseFragment() {
int fsi = findFragmentSeparator();
return fsi == NOT_FOUND ? null : uriString.substring(fsi + 1);
}
public String getFragment() {
return getFragmentPart().getDecoded();
}
public String toString() {
return uriString;
}
/**
* Parses an authority out of the given URI string.
*
* @param uriString URI string
* @param ssi scheme separator index, -1 for a relative URI
*
* @return the authority or null if none is found
*/
static String parseAuthority(String uriString, int ssi) {
int length = uriString.length();
// If "//" follows the scheme separator, we have an authority.
if (length > ssi + 2
&& uriString.charAt(ssi + 1) == '/'
&& uriString.charAt(ssi + 2) == '/') {
// We have an authority.
// Look for the start of the path, query, or fragment, or the
// end of the string.
int end = ssi + 3;
LOOP: while (end < length) {
switch (uriString.charAt(end)) {
case '/': // Start of path
case '?': // Start of query
case '#': // Start of fragment
break LOOP;
}
end++;
}
return uriString.substring(ssi + 3, end);
} else {
return null;
}
}
/**
* Parses a path out of this given URI string.
*
* @param uriString URI string
* @param ssi scheme separator index, -1 for a relative URI
*
* @return the path
*/
static String parsePath(String uriString, int ssi) {
int length = uriString.length();
// Find start of path.
int pathStart;
if (length > ssi + 2
&& uriString.charAt(ssi + 1) == '/'
&& uriString.charAt(ssi + 2) == '/') {
// Skip over authority to path.
pathStart = ssi + 3;
LOOP: while (pathStart < length) {
switch (uriString.charAt(pathStart)) {
case '?': // Start of query
case '#': // Start of fragment
return ""; // Empty path.
case '/': // Start of path!
break LOOP;
}
pathStart++;
}
} else {
// Path starts immediately after scheme separator.
pathStart = ssi + 1;
}
// Find end of path.
int pathEnd = pathStart;
LOOP: while (pathEnd < length) {
switch (uriString.charAt(pathEnd)) {
case '?': // Start of query
case '#': // Start of fragment
break LOOP;
}
pathEnd++;
}
return uriString.substring(pathStart, pathEnd);
}
public Builder buildUpon() {
if (isHierarchical()) {
return new Builder()
.scheme(getScheme())
.authority(getAuthorityPart())
.path(getPathPart())
.query(getQueryPart())
.fragment(getFragmentPart());
} else {
return new Builder()
.scheme(getScheme())
.opaquePart(getSsp())
.fragment(getFragmentPart());
}
}
}
/**
* Creates an opaque Uri from the given components. Encodes the ssp
* which means this method cannot be used to create hierarchical URIs.
*
* @param scheme of the URI
* @param ssp scheme-specific-part, everything between the
* scheme separator (':') and the fragment separator ('#'), which will
* get encoded
* @param fragment fragment, everything after the '#', null if undefined,
* will get encoded
*
* @throws NullPointerException if scheme or ssp is null
* @return Uri composed of the given scheme, ssp, and fragment
*
* @see Builder if you don't want the ssp and fragment to be encoded
*/
public static Uri fromParts(String scheme, String ssp,
String fragment) {
if (scheme == null) {
throw new NullPointerException("scheme");
}
if (ssp == null) {
throw new NullPointerException("ssp");
}
return new OpaqueUri(scheme, Part.fromDecoded(ssp),
Part.fromDecoded(fragment));
}
/**
* Opaque URI.
*/
private static class OpaqueUri extends Uri {
/** Used in parcelling. */
static final int TYPE_ID = 2;
private final String scheme;
private final Part ssp;
private final Part fragment;
private OpaqueUri(String scheme, Part ssp, Part fragment) {
this.scheme = scheme;
this.ssp = ssp;
this.fragment = fragment == null ? Part.NULL : fragment;
}
public boolean isHierarchical() {
return false;
}
public boolean isRelative() {
return scheme == null;
}
public String getScheme() {
return this.scheme;
}
public String getEncodedSchemeSpecificPart() {
return ssp.getEncoded();
}
public String getSchemeSpecificPart() {
return ssp.getDecoded();
}
public String getAuthority() {
return null;
}
public String getEncodedAuthority() {
return null;
}
public String getPath() {
return null;
}
public String getEncodedPath() {
return null;
}
public String getQuery() {
return null;
}
public String getEncodedQuery() {
return null;
}
public String getFragment() {
return fragment.getDecoded();
}
public String getEncodedFragment() {
return fragment.getEncoded();
}
public String[] getPathSegments() {
return new String[0];
}
public String getLastPathSegment() {
return null;
}
public String getUserInfo() {
return null;
}
public String getEncodedUserInfo() {
return null;
}
public String getHost() {
return null;
}
public int getPort() {
return -1;
}
private volatile String cachedString = NOT_CACHED;
public String toString() {
boolean cached = cachedString != NOT_CACHED;
if (cached) {
return cachedString;
}
StringBuffer sb = new StringBuffer();
sb.append(scheme).append(':');
sb.append(getEncodedSchemeSpecificPart());
if (!fragment.isEmpty()) {
sb.append('#').append(fragment.getEncoded());
}
return cachedString = sb.toString();
}
public Builder buildUpon() {
return new Builder()
.scheme(this.scheme)
.opaquePart(this.ssp)
.fragment(this.fragment);
}
}
/**
* Wrapper for path segment array.
*/
static class PathSegments {
static final PathSegments EMPTY = new PathSegments(null, 0);
final String[] segments;
final int size;
PathSegments(String[] segments, int size) {
this.segments = segments;
this.size = size;
}
public String get(int index) {
if (index >= size) {
throw new IndexOutOfBoundsException();
}
return segments[index];
}
public int size() {
return this.size;
}
}
/**
* Builds PathSegments.
*/
static class PathSegmentsBuilder {
String[] segments;
int size = 0;
void add(String segment) {
if (segments == null) {
segments = new String[4];
} else if (size + 1 == segments.length) {
String[] expanded = new String[segments.length * 2];
System.arraycopy(segments, 0, expanded, 0, segments.length);
segments = expanded;
}
segments[size++] = segment;
}
PathSegments build() {
if (segments == null) {
return PathSegments.EMPTY;
}
try {
return new PathSegments(segments, size);
} finally {
// Makes sure this doesn't get reused.
segments = null;
}
}
}
/**
* Support for hierarchical URIs.
*/
private abstract static class AbstractHierarchicalUri extends Uri {
public String getLastPathSegment() {
// TODO: If we haven't parsed all of the segments already, just
// grab the last one directly so we only allocate one string.
String[] segments = getPathSegments();
int size = segments.length;
if (size == 0) {
return null;
}
return segments[size - 1];
}
private Part userInfo;
private Part getUserInfoPart() {
return userInfo == null
? userInfo = Part.fromEncoded(parseUserInfo()) : userInfo;
}
public final String getEncodedUserInfo() {
return getUserInfoPart().getEncoded();
}
private String parseUserInfo() {
String authority = getEncodedAuthority();
if (authority == null) {
return null;
}
int end = authority.indexOf('@');
return end == NOT_FOUND ? null : authority.substring(0, end);
}
public String getUserInfo() {
return getUserInfoPart().getDecoded();
}
private volatile String host = NOT_CACHED;
public String getHost() {
boolean cached = (host != NOT_CACHED);
return cached ? host
: (host = parseHost());
}
private String parseHost() {
String authority = getEncodedAuthority();
if (authority == null) {
return null;
}
// Parse out user info and then port.
int userInfoSeparator = authority.indexOf('@');
int portSeparator = authority.indexOf(':', userInfoSeparator);
String encodedHost = portSeparator == NOT_FOUND
? authority.substring(userInfoSeparator + 1)
: authority.substring(userInfoSeparator + 1, portSeparator);
return decode(encodedHost);
}
private volatile int port = NOT_CALCULATED;
public int getPort() {
return port == NOT_CALCULATED
? port = parsePort()
: port;
}
private int parsePort() {
String authority = getEncodedAuthority();
if (authority == null) {
return -1;
}
// Make sure we look for the port separtor *after* the user info
// separator. We have URLs with a ':' in the user info.
int userInfoSeparator = authority.indexOf('@');
int portSeparator = authority.indexOf(':', userInfoSeparator);
if (portSeparator == NOT_FOUND) {
return -1;
}
String portString = decode(authority.substring(portSeparator + 1));
try {
return Integer.parseInt(portString);
} catch (NumberFormatException e) {
return -1;
}
}
}
/**
* Hierarchical Uri.
*/
private static class HierarchicalUri extends AbstractHierarchicalUri {
/** Used in parcelling. */
static final int TYPE_ID = 3;
private final String scheme; // can be null
private final Part authority;
private final PathPart path;
private final Part query;
private final Part fragment;
private HierarchicalUri(String scheme, Part authority, PathPart path,
Part query, Part fragment) {
this.scheme = scheme;
this.authority = Part.nonNull(authority);
this.path = path == null ? PathPart.NULL : path;
this.query = Part.nonNull(query);
this.fragment = Part.nonNull(fragment);
}
public boolean isHierarchical() {
return true;
}
public boolean isRelative() {
return scheme == null;
}
public String getScheme() {
return scheme;
}
private Part ssp;
private Part getSsp() {
return ssp == null
? ssp = Part.fromEncoded(makeSchemeSpecificPart()) : ssp;
}
public String getEncodedSchemeSpecificPart() {
return getSsp().getEncoded();
}
public String getSchemeSpecificPart() {
return getSsp().getDecoded();
}
/**
* Creates the encoded scheme-specific part from its sub parts.
*/
private String makeSchemeSpecificPart() {
StringBuffer builder = new StringBuffer();
appendSspTo(builder);
return builder.toString();
}
private void appendSspTo(StringBuffer builder) {
String encodedAuthority = authority.getEncoded();
if (encodedAuthority != null) {
// Even if the authority is "", we still want to append "//".
builder.append("//").append(encodedAuthority);
}
String encodedPath = path.getEncoded();
if (encodedPath != null) {
builder.append(encodedPath);
}
if (!query.isEmpty()) {
builder.append('?').append(query.getEncoded());
}
}
public String getAuthority() {
return this.authority.getDecoded();
}
public String getEncodedAuthority() {
return this.authority.getEncoded();
}
public String getEncodedPath() {
return this.path.getEncoded();
}
public String getPath() {
return this.path.getDecoded();
}
public String getQuery() {
return this.query.getDecoded();
}
public String getEncodedQuery() {
return this.query.getEncoded();
}
public String getFragment() {
return this.fragment.getDecoded();
}
public String getEncodedFragment() {
return this.fragment.getEncoded();
}
public String[] getPathSegments() {
return this.path.getPathSegments().segments;
}
private volatile String uriString = NOT_CACHED;
/**
* {@inheritDoc}
*/
public String toString() {
boolean cached = (uriString != NOT_CACHED);
return cached ? uriString
: (uriString = makeUriString());
}
private String makeUriString() {
StringBuffer builder = new StringBuffer();
if (scheme != null) {
builder.append(scheme).append(':');
}
appendSspTo(builder);
if (!fragment.isEmpty()) {
builder.append('#').append(fragment.getEncoded());
}
return builder.toString();
}
public Builder buildUpon() {
return new Builder()
.scheme(scheme)
.authority(authority)
.path(path)
.query(query)
.fragment(fragment);
}
}
/**
* Helper class for building or manipulating URI references. Not safe for
* concurrent use.
*
* <p>An absolute hierarchical URI reference follows the pattern:
* {@code <scheme>://<authority><absolute path>?<query>#<fragment>}
*
* <p>Relative URI references (which are always hierarchical) follow one
* of two patterns: {@code <relative or absolute path>?<query>#<fragment>}
* or {@code //<authority><absolute path>?<query>#<fragment>}
*
* <p>An opaque URI follows this pattern:
* {@code <scheme>:<opaque part>#<fragment>}
*/
public static final class Builder {
private String scheme;
private Part opaquePart;
private Part authority;
private PathPart path;
private Part query;
private Part fragment;
/**
* Constructs a new Builder.
*/
public Builder() {}
/**
* Sets the scheme.
*
* @param scheme name or {@code null} if this is a relative Uri
*/
public Builder scheme(String scheme) {
this.scheme = scheme;
return this;
}
Builder opaquePart(Part opaquePart) {
this.opaquePart = opaquePart;
return this;
}
/**
* Encodes and sets the given opaque scheme-specific-part.
*
* @param opaquePart decoded opaque part
*/
public Builder opaquePart(String opaquePart) {
return opaquePart(Part.fromDecoded(opaquePart));
}
/**
* Sets the previously encoded opaque scheme-specific-part.
*
* @param opaquePart encoded opaque part
*/
public Builder encodedOpaquePart(String opaquePart) {
return opaquePart(Part.fromEncoded(opaquePart));
}
Builder authority(Part authority) {
// This URI will be hierarchical.
this.opaquePart = null;
this.authority = authority;
return this;
}
/**
* Encodes and sets the authority.
*/
public Builder authority(String authority) {
return authority(Part.fromDecoded(authority));
}
/**
* Sets the previously encoded authority.
*/
public Builder encodedAuthority(String authority) {
return authority(Part.fromEncoded(authority));
}
Builder path(PathPart path) {
// This URI will be hierarchical.
this.opaquePart = null;
this.path = path;
return this;
}
/**
* Sets the path. Leaves '/' characters intact but encodes others as
* necessary.
*
* <p>If the path is not null and doesn't start with a '/', and if
* you specify a scheme and/or authority, the builder will prepend the
* given path with a '/'.
*/
public Builder path(String path) {
return path(PathPart.fromDecoded(path));
}
/**
* Sets the previously encoded path.
*
* <p>If the path is not null and doesn't start with a '/', and if
* you specify a scheme and/or authority, the builder will prepend the
* given path with a '/'.
*/
public Builder encodedPath(String path) {
return path(PathPart.fromEncoded(path));
}
/**
* Encodes the given segment and appends it to the path.
*/
public Builder appendPath(String newSegment) {
return path(PathPart.appendDecodedSegment(path, newSegment));
}
/**
* Appends the given segment to the path.
*/
public Builder appendEncodedPath(String newSegment) {
return path(PathPart.appendEncodedSegment(path, newSegment));
}
Builder query(Part query) {
// This URI will be hierarchical.
this.opaquePart = null;
this.query = query;
return this;
}
/**
* Encodes and sets the query.
*/
public Builder query(String query) {
return query(Part.fromDecoded(query));
}
/**
* Sets the previously encoded query.
*/
public Builder encodedQuery(String query) {
return query(Part.fromEncoded(query));
}
Builder fragment(Part fragment) {
this.fragment = fragment;
return this;
}
/**
* Encodes and sets the fragment.
*/
public Builder fragment(String fragment) {
return fragment(Part.fromDecoded(fragment));
}
/**
* Sets the previously encoded fragment.
*/
public Builder encodedFragment(String fragment) {
return fragment(Part.fromEncoded(fragment));
}
/**
* Encodes the key and value and then appends the parameter to the
* query string.
*
* @param key which will be encoded
* @param value which will be encoded
*/
public Builder appendQueryParameter(String key, String value) {
// This URI will be hierarchical.
this.opaquePart = null;
String encodedParameter = encode(key, null) + "="
+ encode(value, null);
if (query == null) {
query = Part.fromEncoded(encodedParameter);
return this;
}
String oldQuery = query.getEncoded();
if (oldQuery == null || oldQuery.length() == 0) {
query = Part.fromEncoded(encodedParameter);
} else {
query = Part.fromEncoded(oldQuery + "&" + encodedParameter);
}
return this;
}
/**
* Constructs a Uri with the current attributes.
*
* @throws UnsupportedOperationException if the URI is opaque and the
* scheme is null
*/
public Uri build() {
if (opaquePart != null) {
if (this.scheme == null) {
throw new UnsupportedOperationException(
"An opaque URI must have a scheme.");
}
return new OpaqueUri(scheme, opaquePart, fragment);
} else {
// Hierarchical URIs should not return null for getPath().
PathPart path = this.path;
if (path == null || path == PathPart.NULL) {
path = PathPart.EMPTY;
} else {
// If we have a scheme and/or authority, the path must
// be absolute. Prepend it with a '/' if necessary.
if (hasSchemeOrAuthority()) {
path = PathPart.makeAbsolute(path);
}
}
return new HierarchicalUri(
scheme, authority, path, query, fragment);
}
}
private boolean hasSchemeOrAuthority() {
return scheme != null
|| (authority != null && authority != Part.NULL);
}
/**
* {@inheritDoc}
*/
public String toString() {
return build().toString();
}
}
/**
* Searches the query string for parameter values with the given key.
*
* @param key which will be encoded
*
* @throws UnsupportedOperationException if this isn't a hierarchical URI
* @throws NullPointerException if key is null
*
* @return a list of decoded values
*/
public String[] getQueryParameters(String key) {
if (isOpaque()) {
throw new UnsupportedOperationException(NOT_HIERARCHICAL);
}
String query = getEncodedQuery();
if (query == null) {
return new String[0];
}
String encodedKey;
try {
encodedKey = URLEncoder.encode(key, DEFAULT_ENCODING);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("AssertionError: " + e);
}
// Prepend query with "&" making the first parameter the same as the
// rest.
query = "&" + query;
// Parameter prefix.
String prefix = "&" + encodedKey + "=";
Vector values = new Vector();
int start = 0;
int length = query.length();
while (start < length) {
start = query.indexOf(prefix, start);
if (start == -1) {
// No more values.
break;
}
// Move start to start of value.
start += prefix.length();
// Find end of value.
int end = query.indexOf('&', start);
if (end == -1) {
end = query.length();
}
String value = query.substring(start, end);
values.addElement(decode(value));
start = end;
}
int size = values.size();
String[] result = new String[size];
values.copyInto(result);
return result;
}
/**
* Searches the query string for the first value with the given key.
*
* @param key which will be encoded
* @throws UnsupportedOperationException if this isn't a hierarchical URI
* @throws NullPointerException if key is null
*
* @return the decoded value or null if no parameter is found
*/
public String getQueryParameter(String key) {
if (isOpaque()) {
throw new UnsupportedOperationException(NOT_HIERARCHICAL);
}
String query = getEncodedQuery();
if (query == null) {
return null;
}
String encodedKey;
try {
encodedKey = URLEncoder.encode(key, DEFAULT_ENCODING);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("AssertionError: " + e);
}
String prefix = encodedKey + "=";
if (query.length() < prefix.length()) {
return null;
}
int start;
if (query.startsWith(prefix)) {
// It's the first parameter.
start = prefix.length();
} else {
// It must be later in the query string.
prefix = "&" + prefix;
start = query.indexOf(prefix);
if (start == -1) {
// Not found.
return null;
}
start += prefix.length();
}
// Find end of value.
int end = query.indexOf('&', start);
if (end == -1) {
end = query.length();
}
String value = query.substring(start, end);
return decode(value);
}
private static final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
/**
* Encodes characters in the given string as '%'-escaped octets
* using the UTF-8 scheme. Leaves letters ("A-Z", "a-z"), numbers
* ("0-9"), and unreserved characters ("_-!.~'()*") intact. Encodes
* all other characters.
*
* @param s string to encode
* @return an encoded version of s suitable for use as a URI component,
* or null if s is null
*/
public static String encode(String s) {
return encode(s, null);
}
/**
* Encodes characters in the given string as '%'-escaped octets
* using the UTF-8 scheme. Leaves letters ("A-Z", "a-z"), numbers
* ("0-9"), and unreserved characters ("_-!.~'()*") intact. Encodes
* all other characters with the exception of those specified in the
* allow argument.
*
* @param s string to encode
* @param allow set of additional characters to allow in the encoded form,
* null if no characters should be skipped
* @return an encoded version of s suitable for use as a URI component,
* or null if s is null
*/
public static String encode(String s, String allow) {
if (s == null) {
return null;
}
// Lazily-initialized buffers.
StringBuffer encoded = null;
int oldLength = s.length();
// This loop alternates between copying over allowed characters and
// encoding in chunks. This results in fewer method calls and
// allocations than encoding one character at a time.
int current = 0;
while (current < oldLength) {
// Start in "copying" mode where we copy over allowed chars.
// Find the next character which needs to be encoded.
int nextToEncode = current;
while (nextToEncode < oldLength
&& isAllowed(s.charAt(nextToEncode), allow)) {
nextToEncode++;
}
// If there's nothing more to encode...
if (nextToEncode == oldLength) {
if (current == 0) {
// We didn't need to encode anything!
return s;
} else {
// Presumably, we've already done some encoding.
encoded.append(s.substring(current, oldLength));
return encoded.toString();
}
}
if (encoded == null) {
encoded = new StringBuffer();
}
if (nextToEncode > current) {
// Append allowed characters leading up to this point.
encoded.append(s.substring(current, nextToEncode));
} else {
// assert nextToEncode == current
}
// Switch to "encoding" mode.
// Find the next allowed character.
current = nextToEncode;
int nextAllowed = current + 1;
while (nextAllowed < oldLength
&& !isAllowed(s.charAt(nextAllowed), allow)) {
nextAllowed++;
}
// Convert the substring to bytes and encode the bytes as
// '%'-escaped octets.
String toEncode = s.substring(current, nextAllowed);
try {
byte[] bytes = toEncode.getBytes(DEFAULT_ENCODING);
int bytesLength = bytes.length;
for (int i = 0; i < bytesLength; i++) {
encoded.append('%');
encoded.append(HEX_DIGITS[(bytes[i] & 0xf0) >> 4]);
encoded.append(HEX_DIGITS[bytes[i] & 0xf]);
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("AssertionError: " + e);
}
current = nextAllowed;
}
// Encoded could still be null at this point if s is empty.
return encoded == null ? s : encoded.toString();
}
/**
* Returns true if the given character is allowed.
*
* @param c character to check
* @param allow characters to allow
* @return true if the character is allowed or false if it should be
* encoded
*/
private static boolean isAllowed(char c, String allow) {
return (c >= 'A' && c <= 'Z')
|| (c >= 'a' && c <= 'z')
|| (c >= '0' && c <= '9')
|| "_-!.~'()*".indexOf(c) != NOT_FOUND
|| (allow != null && allow.indexOf(c) != NOT_FOUND);
}
/** Unicode replacement character: \\uFFFD. */
private static final byte[] REPLACEMENT = { (byte) 0xFF, (byte) 0xFD };
/**
* Decodes '%'-escaped octets in the given string using the UTF-8 scheme.
* Replaces invalid octets with the unicode replacement character
* ("\\uFFFD").
*
* @param s encoded string to decode
* @return the given string with escaped octets decoded, or null if
* s is null
*/
public static String decode(String s) {
/*
Compared to java.net.URLEncoderDecoder.decode(), this method decodes a
chunk at a time instead of one character at a time, and it doesn't
throw exceptions. It also only allocates memory when necessary--if
there's nothing to decode, this method won't do much.
*/
if (s == null) {
return null;
}
// Lazily-initialized buffers.
StringBuffer decoded = null;
ByteArrayOutputStream out = null;
int oldLength = s.length();
// This loop alternates between copying over normal characters and
// escaping in chunks. This results in fewer method calls and
// allocations than decoding one character at a time.
int current = 0;
while (current < oldLength) {
// Start in "copying" mode where we copy over normal characters.
// Find the next escape sequence.
int nextEscape = s.indexOf('%', current);
if (nextEscape == NOT_FOUND) {
if (decoded == null) {
// We didn't actually decode anything.
return s;
} else {
// Append the remainder and return the decoded string.
decoded.append(s.substring(current, oldLength));
return decoded.toString();
}
}
// Prepare buffers.
if (decoded == null) {
// Looks like we're going to need the buffers...
// We know the new string will be shorter. Using the old length
// may overshoot a bit, but it will save us from resizing the
// buffer.
decoded = new StringBuffer(oldLength);
out = new ByteArrayOutputStream(4);
} else {
// Clear decoding buffer.
out.reset();
}
// Append characters leading up to the escape.
if (nextEscape > current) {
decoded.append(s.substring(current, nextEscape));
current = nextEscape;
} else {
// assert current == nextEscape
}
// Switch to "decoding" mode where we decode a string of escape
// sequences.
// Decode and append escape sequences. Escape sequences look like
// "%ab" where % is literal and a and b are hex digits.
try {
do {
if (current + 2 >= oldLength) {
// Truncated escape sequence.
out.write(REPLACEMENT);
} else {
int a = Character.digit(s.charAt(current + 1), 16);
int b = Character.digit(s.charAt(current + 2), 16);
if (a == -1 || b == -1) {
// Non hex digits.
out.write(REPLACEMENT);
} else {
// Combine the hex digits into one byte and write.
out.write((a << 4) + b);
}
}
// Move passed the escape sequence.
current += 3;
} while (current < oldLength && s.charAt(current) == '%');
// Decode UTF-8 bytes into a string and append it.
decoded.append(new String(out.toByteArray(), DEFAULT_ENCODING));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("AssertionError: " + e);
} catch (IOException e) {
throw new RuntimeException("AssertionError: " + e);
}
}
// If we don't have a buffer, we didn't have to decode anything.
return decoded == null ? s : decoded.toString();
}
/**
* Support for part implementations.
*/
static abstract class AbstractPart {
/**
* Enum which indicates which representation of a given part we have.
*/
static class Representation {
static final int BOTH = 0;
static final int ENCODED = 1;
static final int DECODED = 2;
}
volatile String encoded;
volatile String decoded;
AbstractPart(String encoded, String decoded) {
this.encoded = encoded;
this.decoded = decoded;
}
abstract String getEncoded();
final String getDecoded() {
boolean hasDecoded = decoded != NOT_CACHED;
return hasDecoded ? decoded : (decoded = decode(encoded));
}
}
/**
* Immutable wrapper of encoded and decoded versions of a URI part. Lazily
* creates the encoded or decoded version from the other.
*/
static class Part extends AbstractPart {
/** A part with null values. */
static final Part NULL = new EmptyPart(null);
/** A part with empty strings for values. */
static final Part EMPTY = new EmptyPart("");
private Part(String encoded, String decoded) {
super(encoded, decoded);
}
boolean isEmpty() {
return false;
}
String getEncoded() {
boolean hasEncoded = encoded != NOT_CACHED;
return hasEncoded ? encoded : (encoded = encode(decoded));
}
/**
* Returns given part or {@link #NULL} if the given part is null.
*/
static Part nonNull(Part part) {
return part == null ? NULL : part;
}
/**
* Creates a part from the encoded string.
*
* @param encoded part string
*/
static Part fromEncoded(String encoded) {
return from(encoded, NOT_CACHED);
}
/**
* Creates a part from the decoded string.
*
* @param decoded part string
*/
static Part fromDecoded(String decoded) {
return from(NOT_CACHED, decoded);
}
/**
* Creates a part from the encoded and decoded strings.
*
* @param encoded part string
* @param decoded part string
*/
static Part from(String encoded, String decoded) {
// We have to check both encoded and decoded in case one is
// NOT_CACHED.
if (encoded == null) {
return NULL;
}
if (encoded.length() == 0) {
return EMPTY;
}
if (decoded == null) {
return NULL;
}
if (decoded .length() == 0) {
return EMPTY;
}
return new Part(encoded, decoded);
}
private static class EmptyPart extends Part {
public EmptyPart(String value) {
super(value, value);
}
/**
* {@inheritDoc}
*/
boolean isEmpty() {
return true;
}
}
}
/**
* Immutable wrapper of encoded and decoded versions of a path part. Lazily
* creates the encoded or decoded version from the other.
*/
static class PathPart extends AbstractPart {
/** A part with null values. */
static final PathPart NULL = new PathPart(null, null);
/** A part with empty strings for values. */
static final PathPart EMPTY = new PathPart("", "");
private PathPart(String encoded, String decoded) {
super(encoded, decoded);
}
String getEncoded() {
boolean hasEncoded = encoded != NOT_CACHED;
// Don't encode '/'.
return hasEncoded ? encoded : (encoded = encode(decoded, "/"));
}
/**
* Cached path segments. This doesn't need to be volatile--we don't
* care if other threads see the result.
*/
private PathSegments pathSegments;
/**
* Gets the individual path segments. Parses them if necessary.
*
* @return parsed path segments or null if this isn't a hierarchical
* URI
*/
PathSegments getPathSegments() {
if (pathSegments != null) {
return pathSegments;
}
String path = getEncoded();
if (path == null) {
return pathSegments = PathSegments.EMPTY;
}
PathSegmentsBuilder segmentBuilder = new PathSegmentsBuilder();
int previous = 0;
int current;
while ((current = path.indexOf('/', previous)) > -1) {
// This check keeps us from adding a segment if the path starts
// '/' and an empty segment for "//".
if (previous < current) {
String decodedSegment
= decode(path.substring(previous, current));
segmentBuilder.add(decodedSegment);
}
previous = current + 1;
}
// Add in the final path segment.
if (previous < path.length()) {
segmentBuilder.add(decode(path.substring(previous)));
}
return pathSegments = segmentBuilder.build();
}
static PathPart appendEncodedSegment(PathPart oldPart,
String newSegment) {
// If there is no old path, should we make the new path relative
// or absolute? I pick absolute.
if (oldPart == null) {
// No old path.
return fromEncoded("/" + newSegment);
}
String oldPath = oldPart.getEncoded();
if (oldPath == null) {
oldPath = "";
}
int oldPathLength = oldPath.length();
String newPath;
if (oldPathLength == 0) {
// No old path.
newPath = "/" + newSegment;
} else if (oldPath.charAt(oldPathLength - 1) == '/') {
newPath = oldPath + newSegment;
} else {
newPath = oldPath + "/" + newSegment;
}
return fromEncoded(newPath);
}
static PathPart appendDecodedSegment(PathPart oldPart, String decoded) {
String encoded = encode(decoded);
// TODO: Should we reuse old PathSegments? Probably not.
return appendEncodedSegment(oldPart, encoded);
}
/**
* Creates a path from the encoded string.
*
* @param encoded part string
*/
static PathPart fromEncoded(String encoded) {
return from(encoded, NOT_CACHED);
}
/**
* Creates a path from the decoded string.
*
* @param decoded part string
*/
static PathPart fromDecoded(String decoded) {
return from(NOT_CACHED, decoded);
}
/**
* Creates a path from the encoded and decoded strings.
*
* @param encoded part string
* @param decoded part string
*/
static PathPart from(String encoded, String decoded) {
if (encoded == null) {
return NULL;
}
if (encoded.length() == 0) {
return EMPTY;
}
return new PathPart(encoded, decoded);
}
/**
* Prepends path values with "/" if they're present, not empty, and
* they don't already start with "/".
*/
static PathPart makeAbsolute(PathPart oldPart) {
boolean encodedCached = oldPart.encoded != NOT_CACHED;
// We don't care which version we use, and we don't want to force
// unneccessary encoding/decoding.
String oldPath = encodedCached ? oldPart.encoded : oldPart.decoded;
if (oldPath == null || oldPath.length() == 0
|| oldPath.startsWith("/")) {
return oldPart;
}
// Prepend encoded string if present.
String newEncoded = encodedCached
? "/" + oldPart.encoded : NOT_CACHED;
// Prepend decoded string if present.
boolean decodedCached = oldPart.decoded != NOT_CACHED;
String newDecoded = decodedCached
? "/" + oldPart.decoded
: NOT_CACHED;
return new PathPart(newEncoded, newDecoded);
}
}
/**
* Creates a new Uri by appending an already-encoded path segment to a
* base Uri.
*
* @param baseUri Uri to append path segment to
* @param pathSegment encoded path segment to append
* @return a new Uri based on baseUri with the given segment appended to
* the path
* @throws NullPointerException if baseUri is null
*/
public static Uri withAppendedPath(Uri baseUri, String pathSegment) {
Builder builder = baseUri.buildUpon();
builder = builder.appendEncodedPath(pathSegment);
return builder.build();
}
}
| google/google-authenticator | mobile/blackberry/src/com/google/authenticator/blackberry/Uri.java | Java | apache-2.0 | 65,026 |
/*
* 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.distributed.internal.membership;
import org.apache.geode.distributed.internal.DMStats;
import org.apache.geode.distributed.internal.DistributionConfig;
import org.apache.geode.distributed.internal.LocatorStats;
import org.apache.geode.distributed.internal.membership.gms.NetLocator;
import org.apache.geode.internal.admin.remote.RemoteTransportConfig;
import org.apache.geode.internal.security.SecurityService;
import java.io.File;
import java.net.InetAddress;
/**
* This is the SPI for a provider of membership services.
*
* @see org.apache.geode.distributed.internal.membership.NetMember
*/
public interface MemberServices {
/**
* Return a new NetMember, possibly for a different host
*
* @param i the name of the host for the specified NetMember, the current host (hopefully) if
* there are any problems.
* @param port the membership port
* @param splitBrainEnabled whether the member has this feature enabled
* @param canBeCoordinator whether the member can be membership coordinator
* @param payload the payload to be associated with the resulting object
* @param version TODO
* @return the new NetMember
*/
public abstract NetMember newNetMember(InetAddress i, int port, boolean splitBrainEnabled,
boolean canBeCoordinator, MemberAttributes payload, short version);
/**
* Return a new NetMember representing current host
*
* @param i an InetAddress referring to the current host
* @param port the membership port being used
*
* @return the new NetMember
*/
public abstract NetMember newNetMember(InetAddress i, int port);
/**
* Return a new NetMember representing current host
*
* @param s a String referring to the current host
* @param p the membership port being used
* @return the new member
*/
public abstract NetMember newNetMember(String s, int p);
/**
* Create a new MembershipManager
*
* @param listener the listener to notify for callbacks
* @param transport holds configuration information that can be used by the manager to configure
* itself
* @param stats a gemfire statistics collection object for communications stats
*
* @return a MembershipManager
*/
public abstract MembershipManager newMembershipManager(DistributedMembershipListener listener,
DistributionConfig config, RemoteTransportConfig transport, DMStats stats,
SecurityService securityService);
/**
* currently this is a test method but it ought to be used by InternalLocator to create the peer
* location TcpHandler
*/
public abstract NetLocator newLocatorHandler(InetAddress bindAddress, File stateFile,
String locatorString, boolean usePreferredCoordinators,
boolean networkPartitionDetectionEnabled, LocatorStats stats, String securityUDPDHAlgo);
}
| pivotal-amurmann/geode | geode-core/src/main/java/org/apache/geode/distributed/internal/membership/MemberServices.java | Java | apache-2.0 | 3,644 |
/*
* Copyright (c) 2009 Kathryn Huxtable and Kenneth Orr.
*
* This file is part of the SeaGlass Pluggable Look and Feel.
*
* 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.
*
* $Id: org.eclipse.jdt.ui.prefs 172 2009-10-06 18:31:12Z kathryn@kathrynhuxtable.org $
*/
package com.seaglasslookandfeel.ui;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.beans.PropertyChangeEvent;
import javax.swing.JComponent;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.UIResource;
import javax.swing.plaf.synth.SynthContext;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;
import com.seaglasslookandfeel.SeaGlassContext;
/**
* SeaGlass TextPaneUI delegate.
*
* Based on SynthTextPaneUI by Georges Saab and David Karlton.
*
* The only reason this exists is that we had to modify SynthTextPaneUI.
*
* @see javax.swing.plaf.synth.SynthTextPaneUI
*/
public class SeaGlassTextPaneUI extends SeaGlassEditorPaneUI {
/**
* Creates a UI for the JTextPane.
*
* @param c the JTextPane object
* @return the UI object
*/
public static ComponentUI createUI(JComponent c) {
return new SeaGlassTextPaneUI();
}
/**
* Fetches the name used as a key to lookup properties through the
* UIManager. This is used as a prefix to all the standard
* text properties.
*
* @return the name ("TextPane")
*/
@Override
protected String getPropertyPrefix() {
return "TextPane";
}
/**
* Installs the UI for a component. This does the following
* things.
* <ol>
* <li>
* Sets opaqueness of the associated component according to its style,
* if the opaque property has not already been set by the client program.
* <li>
* Installs the default caret and highlighter into the
* associated component. These properties are only set if their
* current value is either {@code null} or an instance of
* {@link UIResource}.
* <li>
* Attaches to the editor and model. If there is no
* model, a default one is created.
* <li>
* Creates the view factory and the view hierarchy used
* to represent the model.
* </ol>
*
* @param c the editor component
* @see javax.swing.plaf.basic.BasicTextUI#installUI
* @see ComponentUI#installUI
*/
@Override
public void installUI(JComponent c) {
super.installUI(c);
updateForeground(c.getForeground());
updateFont(c.getFont());
}
/**
* This method gets called when a bound property is changed
* on the associated JTextComponent. This is a hook
* which UI implementations may change to reflect how the
* UI displays bound properties of JTextComponent subclasses.
* If the font, foreground or document has changed, the
* the appropriate property is set in the default style of
* the document.
*
* @param evt the property change event
*/
@Override
protected void propertyChange(PropertyChangeEvent evt) {
super.propertyChange(evt);
String name = evt.getPropertyName();
if (name.equals("foreground")) {
updateForeground((Color)evt.getNewValue());
} else if (name.equals("font")) {
updateFont((Font)evt.getNewValue());
} else if (name.equals("document")) {
JComponent comp = getComponent();
updateForeground(comp.getForeground());
updateFont(comp.getFont());
}
}
/**
* Update the color in the default style of the document.
*
* @param color the new color to use or null to remove the color attribute
* from the document's style
*/
private void updateForeground(Color color) {
StyledDocument doc = (StyledDocument)getComponent().getDocument();
Style style = doc.getStyle(StyleContext.DEFAULT_STYLE);
if (style == null) {
return;
}
if (color == null) {
style.removeAttribute(StyleConstants.Foreground);
} else {
StyleConstants.setForeground(style, color);
}
}
/**
* Update the font in the default style of the document.
*
* @param font the new font to use or null to remove the font attribute
* from the document's style
*/
private void updateFont(Font font) {
StyledDocument doc = (StyledDocument)getComponent().getDocument();
Style style = doc.getStyle(StyleContext.DEFAULT_STYLE);
if (style == null) {
return;
}
if (font == null) {
style.removeAttribute(StyleConstants.FontFamily);
style.removeAttribute(StyleConstants.FontSize);
style.removeAttribute(StyleConstants.Bold);
style.removeAttribute(StyleConstants.Italic);
} else {
StyleConstants.setFontFamily(style, font.getName());
StyleConstants.setFontSize(style, font.getSize());
StyleConstants.setBold(style, font.isBold());
StyleConstants.setItalic(style, font.isItalic());
}
}
@Override
void paintBackground(SynthContext context, Graphics g, JComponent c) {
((SeaGlassContext)context).getPainter().paintTextPaneBackground(context, g, 0, 0,
c.getWidth(), c.getHeight());
}
/**
* @inheritDoc
*/
@Override
public void paintBorder(SynthContext context, Graphics g, int x,
int y, int w, int h) {
((SeaGlassContext)context).getPainter().paintTextPaneBorder(context, g, x, y, w, h);
}
}
| khuxtable/seaglass | src/main/java/com/seaglasslookandfeel/ui/SeaGlassTextPaneUI.java | Java | apache-2.0 | 6,509 |
/**
* Most of the code in the Qalingo project is copyrighted Hoteia and licensed
* under the Apache License Version 2.0 (release version 0.8.0)
* http://www.apache.org/licenses/LICENSE-2.0
*
* Copyright (c) Hoteia, 2012-2014
* http://www.hoteia.com - http://twitter.com/hoteia - contact@hoteia.com
*
*/
package org.hoteia.qalingo.core.service.pojo;
import java.util.List;
import java.util.Set;
import org.dozer.Mapper;
import org.hoteia.qalingo.core.domain.Customer;
import org.hoteia.qalingo.core.domain.CustomerMarketArea;
import org.hoteia.qalingo.core.domain.CustomerWishlist;
import org.hoteia.qalingo.core.domain.MarketArea;
import org.hoteia.qalingo.core.pojo.customer.CustomerPojo;
import org.hoteia.qalingo.core.pojo.customer.CustomerWishlistPojo;
import org.hoteia.qalingo.core.pojo.util.mapper.PojoUtil;
import org.hoteia.qalingo.core.service.CustomerService;
import org.hoteia.qalingo.core.service.MarketService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service("customerPojoService")
@Transactional(readOnly = true)
public class CustomerPojoService {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private Mapper dozerBeanMapper;
@Autowired
protected MarketService marketService;
@Autowired
private CustomerService customerService;
public List<CustomerPojo> getAllCustomers() {
List<Customer> customers = customerService.findCustomers();
logger.debug("Found {} customers", customers.size());
return PojoUtil.mapAll(dozerBeanMapper, customers, CustomerPojo.class);
}
public CustomerPojo getCustomerById(final String id) {
Customer customer = customerService.getCustomerById(id);
logger.debug("Found customer {} for id {}", customer, id);
return customer == null ? null : dozerBeanMapper.map(customer, CustomerPojo.class);
}
public CustomerPojo getCustomerByLoginOrEmail(final String usernameOrEmail) {
Customer customer = customerService.getCustomerByLoginOrEmail(usernameOrEmail);
logger.debug("Found customer {} for usernameOrEmail {}", customer, usernameOrEmail);
return customer == null ? null : dozerBeanMapper.map(customer, CustomerPojo.class);
}
public CustomerPojo getCustomerByPermalink(final String permalink) {
Customer customer = customerService.getCustomerByPermalink(permalink);
logger.debug("Found customer {} for usernameOrEmail {}", customer, permalink);
return customer == null ? null : dozerBeanMapper.map(customer, CustomerPojo.class);
}
@Transactional
public void saveOrUpdate(final CustomerPojo customerJsonPojo) throws Exception {
Customer customer = dozerBeanMapper.map(customerJsonPojo, Customer.class);
logger.info("Saving customer {}", customer);
customerService.saveOrUpdateCustomer(customer);
}
public List<CustomerWishlistPojo> getWishlist(final Customer customer, final MarketArea marketArea) {
final CustomerMarketArea customerMarketArea = customer.getCurrentCustomerMarketArea(marketArea.getId());
Set<CustomerWishlist> wishlistProducts = customerMarketArea.getWishlistProducts();
List<CustomerWishlistPojo> wishlists = PojoUtil.mapAll(dozerBeanMapper, wishlistProducts, CustomerWishlistPojo.class);
return wishlists;
}
public void addProductSkuToWishlist(MarketArea marketArea, Customer customer, String catalogCategoryCode, String productSkuCode) throws Exception {
customerService.addProductSkuToWishlist(marketArea, customer, catalogCategoryCode, productSkuCode);
}
} | eric-stanley/qalingo-engine | apis/api-core/api-core-common/src/main/java/org/hoteia/qalingo/core/service/pojo/CustomerPojoService.java | Java | apache-2.0 | 3,861 |
/* 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.activiti.engine.impl.context;
import org.activiti.engine.impl.persistence.entity.DeploymentEntity;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.util.ProcessDefinitionUtil;
import org.activiti.engine.repository.ProcessDefinition;
/**
* @author Tom Baeyens
*/
public class ExecutionContext {
protected ExecutionEntity execution;
public ExecutionContext(ExecutionEntity execution) {
this.execution = execution;
}
public ExecutionEntity getExecution() {
return execution;
}
public ExecutionEntity getProcessInstance() {
return execution.getProcessInstance();
}
public ProcessDefinition getProcessDefinition() {
return ProcessDefinitionUtil.getProcessDefinition(execution.getProcessDefinitionId());
}
public DeploymentEntity getDeployment() {
String deploymentId = getProcessDefinition().getDeploymentId();
DeploymentEntity deployment = Context.getCommandContext().getDeploymentEntityManager().findById(deploymentId);
return deployment;
}
}
| roberthafner/flowable-engine | modules/flowable-engine/src/main/java/org/activiti/engine/impl/context/ExecutionContext.java | Java | apache-2.0 | 1,626 |
package nak.liblinear;
import static nak.liblinear.Linear.info;
/**
* Trust Region Newton Method optimization
*/
class Tron {
private final Function fun_obj;
private final double eps;
private final int max_iter;
public Tron( final Function fun_obj ) {
this(fun_obj, 0.1);
}
public Tron( final Function fun_obj, double eps ) {
this(fun_obj, eps, 1000);
}
public Tron( final Function fun_obj, double eps, int max_iter ) {
this.fun_obj = fun_obj;
this.eps = eps;
this.max_iter = max_iter;
}
void tron(double[] w) {
// Parameters for updating the iterates.
double eta0 = 1e-4, eta1 = 0.25, eta2 = 0.75;
// Parameters for updating the trust region size delta.
double sigma1 = 0.25, sigma2 = 0.5, sigma3 = 4;
int n = fun_obj.get_nr_variable();
int i, cg_iter;
double delta, snorm, one = 1.0;
double alpha, f, fnew, prered, actred, gs;
int search = 1, iter = 1;
double[] s = new double[n];
double[] r = new double[n];
double[] w_new = new double[n];
double[] g = new double[n];
for (i = 0; i < n; i++)
w[i] = 0;
f = fun_obj.fun(w);
fun_obj.grad(w, g);
delta = euclideanNorm(g);
double gnorm1 = delta;
double gnorm = gnorm1;
if (gnorm <= eps * gnorm1) search = 0;
iter = 1;
while (iter <= max_iter && search != 0) {
cg_iter = trcg(delta, g, s, r);
System.arraycopy(w, 0, w_new, 0, n);
daxpy(one, s, w_new);
gs = dot(g, s);
prered = -0.5 * (gs - dot(s, r));
fnew = fun_obj.fun(w_new);
// Compute the actual reduction.
actred = f - fnew;
// On the first iteration, adjust the initial step bound.
snorm = euclideanNorm(s);
if (iter == 1) delta = Math.min(delta, snorm);
// Compute prediction alpha*snorm of the step.
if (fnew - f - gs <= 0)
alpha = sigma3;
else
alpha = Math.max(sigma1, -0.5 * (gs / (fnew - f - gs)));
// Update the trust region bound according to the ratio of actual to
// predicted reduction.
if (actred < eta0 * prered)
delta = Math.min(Math.max(alpha, sigma1) * snorm, sigma2 * delta);
else if (actred < eta1 * prered)
delta = Math.max(sigma1 * delta, Math.min(alpha * snorm, sigma2 * delta));
else if (actred < eta2 * prered)
delta = Math.max(sigma1 * delta, Math.min(alpha * snorm, sigma3 * delta));
else
delta = Math.max(delta, Math.min(alpha * snorm, sigma3 * delta));
info("iter %2d act %5.3e pre %5.3e delta %5.3e f %5.3e |g| %5.3e CG %3d%n", iter, actred, prered, delta, f, gnorm, cg_iter);
if (actred > eta0 * prered) {
iter++;
System.arraycopy(w_new, 0, w, 0, n);
f = fnew;
fun_obj.grad(w, g);
gnorm = euclideanNorm(g);
if (gnorm <= eps * gnorm1) break;
}
if (f < -1.0e+32) {
info("WARNING: f < -1.0e+32%n");
break;
}
if (Math.abs(actred) <= 0 && prered <= 0) {
info("WARNING: actred and prered <= 0%n");
break;
}
if (Math.abs(actred) <= 1.0e-12 * Math.abs(f) && Math.abs(prered) <= 1.0e-12 * Math.abs(f)) {
info("WARNING: actred and prered too small%n");
break;
}
}
}
private int trcg(double delta, double[] g, double[] s, double[] r) {
int n = fun_obj.get_nr_variable();
double one = 1;
double[] d = new double[n];
double[] Hd = new double[n];
double rTr, rnewTrnew, cgtol;
for (int i = 0; i < n; i++) {
s[i] = 0;
r[i] = -g[i];
d[i] = r[i];
}
cgtol = 0.1 * euclideanNorm(g);
int cg_iter = 0;
rTr = dot(r, r);
while (true) {
if (euclideanNorm(r) <= cgtol) break;
cg_iter++;
fun_obj.Hv(d, Hd);
double alpha = rTr / dot(d, Hd);
daxpy(alpha, d, s);
if (euclideanNorm(s) > delta) {
info("cg reaches trust region boundary%n");
alpha = -alpha;
daxpy(alpha, d, s);
double std = dot(s, d);
double sts = dot(s, s);
double dtd = dot(d, d);
double dsq = delta * delta;
double rad = Math.sqrt(std * std + dtd * (dsq - sts));
if (std >= 0)
alpha = (dsq - sts) / (std + rad);
else
alpha = (rad - std) / dtd;
daxpy(alpha, d, s);
alpha = -alpha;
daxpy(alpha, Hd, r);
break;
}
alpha = -alpha;
daxpy(alpha, Hd, r);
rnewTrnew = dot(r, r);
double beta = rnewTrnew / rTr;
scale(beta, d);
daxpy(one, r, d);
rTr = rnewTrnew;
}
return (cg_iter);
}
/**
* constant times a vector plus a vector
*
* <pre>
* vector2 += constant * vector1
* </pre>
*
* @since 1.8
*/
private static void daxpy(double constant, double vector1[], double vector2[]) {
if (constant == 0) return;
assert vector1.length == vector2.length;
for (int i = 0; i < vector1.length; i++) {
vector2[i] += constant * vector1[i];
}
}
/**
* returns the dot product of two vectors
*
* @since 1.8
*/
private static double dot(double vector1[], double vector2[]) {
double product = 0;
assert vector1.length == vector2.length;
for (int i = 0; i < vector1.length; i++) {
product += vector1[i] * vector2[i];
}
return product;
}
/**
* returns the euclidean norm of a vector
*
* @since 1.8
*/
private static double euclideanNorm(double vector[]) {
int n = vector.length;
if (n < 1) {
return 0;
}
if (n == 1) {
return Math.abs(vector[0]);
}
// this algorithm is (often) more accurate than just summing up the squares and taking the square-root afterwards
double scale = 0; // scaling factor that is factored out
double sum = 1; // basic sum of squares from which scale has been factored out
for (int i = 0; i < n; i++) {
if (vector[i] != 0) {
double abs = Math.abs(vector[i]);
// try to get the best scaling factor
if (scale < abs) {
double t = scale / abs;
sum = 1 + sum * (t * t);
scale = abs;
} else {
double t = abs / scale;
sum += t * t;
}
}
}
return scale * Math.sqrt(sum);
}
/**
* scales a vector by a constant
*
* @since 1.8
*/
private static void scale(double constant, double vector[]) {
if (constant == 1.0) return;
for (int i = 0; i < vector.length; i++) {
vector[i] *= constant;
}
}
}
| scalanlp/nak | src/main/java/nak/liblinear/Tron.java | Java | apache-2.0 | 7,591 |
/*
* 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.psi.impl.source.xml;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElement;
import com.intellij.psi.XmlElementFactory;
import com.intellij.psi.impl.source.xml.behavior.DefaultXmlPsiPolicy;
import com.intellij.psi.search.PsiElementProcessor;
import com.intellij.psi.xml.*;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class XmlTagValueImpl implements XmlTagValue{
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.xml.XmlTagValueImpl");
private final XmlTag myTag;
private final XmlTagChild[] myElements;
private volatile XmlText[] myTextElements;
private volatile String myText;
private volatile String myTrimmedText;
public XmlTagValueImpl(@NotNull XmlTagChild[] bodyElements, @NotNull XmlTag tag) {
myTag = tag;
myElements = bodyElements;
}
@Override
@NotNull
public XmlTagChild[] getChildren() {
return myElements;
}
@Override
@NotNull
public XmlText[] getTextElements() {
XmlText[] textElements = myTextElements;
if (textElements == null) {
textElements = Arrays.stream(myElements)
.filter(element -> element instanceof XmlText)
.map(element -> (XmlText)element).toArray(XmlText[]::new);
myTextElements = textElements = textElements.length == 0 ? XmlText.EMPTY_ARRAY : textElements;
}
return textElements;
}
@Override
@NotNull
public String getText() {
String text = myText;
if (text == null) {
final StringBuilder consolidatedText = new StringBuilder();
for (final XmlTagChild element : myElements) {
consolidatedText.append(element.getText());
}
myText = text = consolidatedText.toString();
}
return text;
}
@Override
@NotNull
public TextRange getTextRange() {
if(myElements.length == 0){
final ASTNode child = XmlChildRole.START_TAG_END_FINDER.findChild( (ASTNode)myTag);
if(child != null)
return new TextRange(child.getStartOffset() + 1, child.getStartOffset() + 1);
return new TextRange(myTag.getTextRange().getEndOffset(), myTag.getTextRange().getEndOffset());
}
return new TextRange(myElements[0].getTextRange().getStartOffset(), myElements[myElements.length - 1].getTextRange().getEndOffset());
}
@Override
@NotNull
public String getTrimmedText() {
String trimmedText = myTrimmedText;
if (trimmedText == null) {
final StringBuilder consolidatedText = new StringBuilder();
final XmlText[] textElements = getTextElements();
for (final XmlText textElement : textElements) {
consolidatedText.append(textElement.getValue());
}
myTrimmedText = trimmedText = consolidatedText.toString().trim();
}
return trimmedText;
}
@Override
public void setText(String value) {
setText(value, false);
}
@Override
public void setEscapedText(String value) {
setText(value, true);
}
private void setText(String value, boolean defaultPolicy) {
try {
XmlText text = null;
if (value != null) {
final XmlText[] texts = getTextElements();
if (texts.length == 0) {
text = (XmlText)myTag.add(XmlElementFactory.getInstance(myTag.getProject()).createDisplayText("x"));
} else {
text = texts[0];
}
if (StringUtil.isEmpty(value)) {
text.delete();
}
else {
if (defaultPolicy && text instanceof XmlTextImpl) {
((XmlTextImpl)text).doSetValue(value, new DefaultXmlPsiPolicy());
} else {
text.setValue(value);
}
}
}
if(myElements.length > 0){
for (final XmlTagChild child : myElements) {
if (child != text) {
child.delete();
}
}
}
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
@Override
public boolean hasCDATA() {
for (XmlText xmlText : getTextElements()) {
PsiElement[] children = xmlText.getChildren();
for (PsiElement child : children) {
if (child.getNode().getElementType() == XmlElementType.XML_CDATA) {
return true;
}
}
}
return false;
}
public static XmlTagValue createXmlTagValue(XmlTag tag) {
final List<XmlTagChild> bodyElements = new ArrayList<>();
tag.processElements(new PsiElementProcessor() {
boolean insideBody;
@Override
public boolean execute(@NotNull PsiElement element) {
final ASTNode treeElement = element.getNode();
if (insideBody) {
if (treeElement != null && treeElement.getElementType() == XmlTokenType.XML_END_TAG_START) return false;
if (!(element instanceof XmlTagChild)) return true;
bodyElements.add((XmlTagChild)element);
}
else if (treeElement != null && treeElement.getElementType() == XmlTokenType.XML_TAG_END) insideBody = true;
return true;
}
}, tag);
XmlTagChild[] tagChildren = bodyElements.toArray(XmlTagChild.EMPTY_ARRAY);
return new XmlTagValueImpl(tagChildren, tag);
}
}
| paplorinc/intellij-community | xml/xml-psi-impl/src/com/intellij/psi/impl/source/xml/XmlTagValueImpl.java | Java | apache-2.0 | 5,970 |
/*
* 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.syncope.core.spring.security;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.security.auth.login.AccountNotFoundException;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple;
import org.apache.syncope.common.keymaster.client.api.ConfParamOps;
import org.apache.syncope.common.lib.SyncopeConstants;
import org.apache.syncope.common.lib.types.AnyTypeKind;
import org.apache.syncope.common.lib.types.AuditElements;
import org.apache.syncope.common.lib.types.EntitlementsHolder;
import org.apache.syncope.common.lib.types.IdRepoEntitlement;
import org.apache.syncope.core.persistence.api.ImplementationLookup;
import org.apache.syncope.core.persistence.api.dao.AccessTokenDAO;
import org.apache.syncope.core.persistence.api.dao.AnySearchDAO;
import org.apache.syncope.core.persistence.api.entity.AnyType;
import org.apache.syncope.core.persistence.api.entity.resource.Provision;
import org.apache.syncope.core.provisioning.api.utils.RealmUtils;
import org.apache.syncope.core.persistence.api.dao.AnyTypeDAO;
import org.apache.syncope.core.persistence.api.dao.DelegationDAO;
import org.apache.syncope.core.persistence.api.dao.GroupDAO;
import org.apache.syncope.core.persistence.api.dao.RealmDAO;
import org.apache.syncope.core.persistence.api.dao.RoleDAO;
import org.apache.syncope.core.persistence.api.dao.UserDAO;
import org.apache.syncope.core.persistence.api.dao.search.AttrCond;
import org.apache.syncope.core.persistence.api.dao.search.SearchCond;
import org.apache.syncope.core.persistence.api.entity.AccessToken;
import org.apache.syncope.core.persistence.api.entity.Delegation;
import org.apache.syncope.core.persistence.api.entity.DynRealm;
import org.apache.syncope.core.persistence.api.entity.Realm;
import org.apache.syncope.core.persistence.api.entity.Role;
import org.apache.syncope.core.persistence.api.entity.resource.ExternalResource;
import org.apache.syncope.core.persistence.api.entity.user.User;
import org.apache.syncope.core.provisioning.api.AuditManager;
import org.apache.syncope.core.provisioning.api.ConnectorManager;
import org.apache.syncope.core.provisioning.api.MappingManager;
import org.apache.syncope.core.spring.ApplicationContextProvider;
import org.identityconnectors.framework.common.objects.Uid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.transaction.annotation.Transactional;
/**
* Domain-sensible (via {@code @Transactional}) access to authentication / authorization data.
*
* @see JWTAuthenticationProvider
* @see UsernamePasswordAuthenticationProvider
* @see SyncopeAuthenticationDetails
*/
public class AuthDataAccessor {
protected static final Logger LOG = LoggerFactory.getLogger(AuthDataAccessor.class);
public static final String GROUP_OWNER_ROLE = "GROUP_OWNER";
protected static final Encryptor ENCRYPTOR = Encryptor.getInstance();
protected static final Set<SyncopeGrantedAuthority> ANONYMOUS_AUTHORITIES =
Set.of(new SyncopeGrantedAuthority(IdRepoEntitlement.ANONYMOUS));
protected static final Set<SyncopeGrantedAuthority> MUST_CHANGE_PASSWORD_AUTHORITIES =
Set.of(new SyncopeGrantedAuthority(IdRepoEntitlement.MUST_CHANGE_PASSWORD));
protected final SecurityProperties securityProperties;
protected final RealmDAO realmDAO;
protected final UserDAO userDAO;
protected final GroupDAO groupDAO;
protected final AnyTypeDAO anyTypeDAO;
protected final AnySearchDAO anySearchDAO;
protected final AccessTokenDAO accessTokenDAO;
protected final ConfParamOps confParamOps;
protected final RoleDAO roleDAO;
protected final DelegationDAO delegationDAO;
protected final ConnectorManager connectorManager;
protected final AuditManager auditManager;
protected final MappingManager mappingManager;
protected final ImplementationLookup implementationLookup;
private Map<String, JWTSSOProvider> jwtSSOProviders;
public AuthDataAccessor(
final SecurityProperties securityProperties,
final RealmDAO realmDAO,
final UserDAO userDAO,
final GroupDAO groupDAO,
final AnyTypeDAO anyTypeDAO,
final AnySearchDAO anySearchDAO,
final AccessTokenDAO accessTokenDAO,
final ConfParamOps confParamOps,
final RoleDAO roleDAO,
final DelegationDAO delegationDAO,
final ConnectorManager connectorManager,
final AuditManager auditManager,
final MappingManager mappingManager,
final ImplementationLookup implementationLookup) {
this.securityProperties = securityProperties;
this.realmDAO = realmDAO;
this.userDAO = userDAO;
this.groupDAO = groupDAO;
this.anyTypeDAO = anyTypeDAO;
this.anySearchDAO = anySearchDAO;
this.accessTokenDAO = accessTokenDAO;
this.confParamOps = confParamOps;
this.roleDAO = roleDAO;
this.delegationDAO = delegationDAO;
this.connectorManager = connectorManager;
this.auditManager = auditManager;
this.mappingManager = mappingManager;
this.implementationLookup = implementationLookup;
}
public JWTSSOProvider getJWTSSOProvider(final String issuer) {
synchronized (this) {
if (jwtSSOProviders == null) {
jwtSSOProviders = new HashMap<>();
implementationLookup.getJWTSSOProviderClasses().stream().
map(clazz -> (JWTSSOProvider) ApplicationContextProvider.getBeanFactory().
createBean(clazz, AbstractBeanDefinition.AUTOWIRE_BY_TYPE, true)).
forEach(jwtSSOProvider -> jwtSSOProviders.put(jwtSSOProvider.getIssuer(), jwtSSOProvider));
}
}
if (issuer == null) {
throw new AuthenticationCredentialsNotFoundException("A null issuer is not permitted");
}
JWTSSOProvider provider = jwtSSOProviders.get(issuer);
if (provider == null) {
throw new AuthenticationCredentialsNotFoundException(
"Could not find any registered JWTSSOProvider for issuer " + issuer);
}
return provider;
}
protected String getDelegationKey(final SyncopeAuthenticationDetails details, final String delegatedKey) {
if (details.getDelegatedBy() == null) {
return null;
}
String delegatingKey = SyncopeConstants.UUID_PATTERN.matcher(details.getDelegatedBy()).matches()
? details.getDelegatedBy()
: userDAO.findKey(details.getDelegatedBy());
if (delegatingKey == null) {
throw new SessionAuthenticationException(
"Delegating user " + details.getDelegatedBy() + " cannot be found");
}
LOG.debug("Delegation request: delegating:{}, delegated:{}", delegatingKey, delegatedKey);
return delegationDAO.findValidFor(delegatingKey, delegatedKey).
orElseThrow(() -> new SessionAuthenticationException(
"Delegation by " + delegatingKey + " was requested but none found"));
}
/**
* Attempts to authenticate the given credentials against internal storage and pass-through resources (if
* configured): the first succeeding causes global success.
*
* @param domain domain
* @param authentication given credentials
* @return {@code null} if no matching user was found, authentication result otherwise
*/
@Transactional(noRollbackFor = DisabledException.class)
public Triple<User, Boolean, String> authenticate(final String domain, final Authentication authentication) {
User user = null;
String[] authAttrValues = confParamOps.get(
domain, "authentication.attributes", new String[] { "username" }, String[].class);
for (int i = 0; user == null && i < authAttrValues.length; i++) {
if ("username".equals(authAttrValues[i])) {
user = userDAO.findByUsername(authentication.getName());
} else {
AttrCond attrCond = new AttrCond(AttrCond.Type.EQ);
attrCond.setSchema(authAttrValues[i]);
attrCond.setExpression(authentication.getName());
try {
List<User> users = anySearchDAO.search(SearchCond.getLeaf(attrCond), AnyTypeKind.USER);
if (users.size() == 1) {
user = users.get(0);
} else {
LOG.warn("Search condition {} does not uniquely match a user", attrCond);
}
} catch (IllegalArgumentException e) {
LOG.error("While searching user for authentication via {}", attrCond, e);
}
}
}
Boolean authenticated = null;
String delegationKey = null;
if (user != null) {
authenticated = false;
if (user.isSuspended() != null && user.isSuspended()) {
throw new DisabledException("User " + user.getUsername() + " is suspended");
}
String[] authStatuses = confParamOps.get(
domain, "authentication.statuses", new String[] {}, String[].class);
if (!ArrayUtils.contains(authStatuses, user.getStatus())) {
throw new DisabledException("User " + user.getUsername() + " not allowed to authenticate");
}
boolean userModified = false;
authenticated = authenticate(user, authentication.getCredentials().toString());
if (authenticated) {
delegationKey = getDelegationKey(
SyncopeAuthenticationDetails.class.cast(authentication.getDetails()), user.getKey());
if (confParamOps.get(domain, "log.lastlogindate", true, Boolean.class)) {
user.setLastLoginDate(new Date());
userModified = true;
}
if (user.getFailedLogins() != 0) {
user.setFailedLogins(0);
userModified = true;
}
} else {
user.setFailedLogins(user.getFailedLogins() + 1);
userModified = true;
}
if (userModified) {
userDAO.save(user);
}
}
return Triple.of(user, authenticated, delegationKey);
}
protected boolean authenticate(final User user, final String password) {
boolean authenticated = ENCRYPTOR.verify(password, user.getCipherAlgorithm(), user.getPassword());
LOG.debug("{} authenticated on internal storage: {}", user.getUsername(), authenticated);
for (Iterator<? extends ExternalResource> itor = getPassthroughResources(user).iterator();
itor.hasNext() && !authenticated;) {
ExternalResource resource = itor.next();
String connObjectKey = null;
try {
AnyType userType = anyTypeDAO.findUser();
Provision provision = resource.getProvision(userType).
orElseThrow(() -> new AccountNotFoundException(
"Unable to locate provision for user type " + userType.getKey()));
connObjectKey = mappingManager.getConnObjectKeyValue(user, provision).
orElseThrow(() -> new AccountNotFoundException(
"Unable to locate conn object key value for " + userType.getKey()));
Uid uid = connectorManager.getConnector(resource).authenticate(connObjectKey, password, null);
if (uid != null) {
authenticated = true;
}
} catch (Exception e) {
LOG.debug("Could not authenticate {} on {}", user.getUsername(), resource.getKey(), e);
}
LOG.debug("{} authenticated on {} as {}: {}",
user.getUsername(), resource.getKey(), connObjectKey, authenticated);
}
return authenticated;
}
protected Set<? extends ExternalResource> getPassthroughResources(final User user) {
Set<? extends ExternalResource> result = null;
// 1. look for assigned resources, pick the ones whose account policy has authentication resources
for (ExternalResource resource : userDAO.findAllResources(user)) {
if (resource.getAccountPolicy() != null && !resource.getAccountPolicy().getResources().isEmpty()) {
if (result == null) {
result = resource.getAccountPolicy().getResources();
} else {
result.retainAll(resource.getAccountPolicy().getResources());
}
}
}
// 2. look for realms, pick the ones whose account policy has authentication resources
for (Realm realm : realmDAO.findAncestors(user.getRealm())) {
if (realm.getAccountPolicy() != null && !realm.getAccountPolicy().getResources().isEmpty()) {
if (result == null) {
result = realm.getAccountPolicy().getResources();
} else {
result.retainAll(realm.getAccountPolicy().getResources());
}
}
}
return result == null ? Set.of() : result;
}
protected Set<SyncopeGrantedAuthority> getAdminAuthorities() {
return EntitlementsHolder.getInstance().getValues().stream().
map(entitlement -> new SyncopeGrantedAuthority(entitlement, SyncopeConstants.ROOT_REALM)).
collect(Collectors.toSet());
}
protected Set<SyncopeGrantedAuthority> buildAuthorities(final Map<String, Set<String>> entForRealms) {
Set<SyncopeGrantedAuthority> authorities = new HashSet<>();
entForRealms.forEach((entitlement, realms) -> {
Pair<Set<String>, Set<String>> normalized = RealmUtils.normalize(realms);
SyncopeGrantedAuthority authority = new SyncopeGrantedAuthority(entitlement);
authority.addRealms(normalized.getLeft());
authority.addRealms(normalized.getRight());
authorities.add(authority);
});
return authorities;
}
protected Set<SyncopeGrantedAuthority> getUserAuthorities(final User user) {
if (user.isMustChangePassword()) {
return MUST_CHANGE_PASSWORD_AUTHORITIES;
}
Map<String, Set<String>> entForRealms = new HashMap<>();
// Give entitlements as assigned by roles (with static or dynamic realms, where applicable) - assigned
// either statically and dynamically
userDAO.findAllRoles(user).stream().
filter(role -> !GROUP_OWNER_ROLE.equals(role.getKey())).
forEach(role -> role.getEntitlements().forEach(entitlement -> {
Set<String> realms = Optional.ofNullable(entForRealms.get(entitlement)).orElseGet(() -> {
Set<String> r = new HashSet<>();
entForRealms.put(entitlement, r);
return r;
});
realms.addAll(role.getRealms().stream().map(Realm::getFullPath).collect(Collectors.toSet()));
if (!entitlement.endsWith("_CREATE") && !entitlement.endsWith("_DELETE")) {
realms.addAll(role.getDynRealms().stream().map(DynRealm::getKey).collect(Collectors.toList()));
}
}));
// Give group entitlements for owned groups
groupDAO.findOwnedByUser(user.getKey()).forEach(group -> {
Role groupOwnerRole = roleDAO.find(GROUP_OWNER_ROLE);
if (groupOwnerRole == null) {
LOG.warn("Role {} was not found", GROUP_OWNER_ROLE);
} else {
groupOwnerRole.getEntitlements().forEach(entitlement -> {
Set<String> realms = Optional.ofNullable(entForRealms.get(entitlement)).orElseGet(() -> {
HashSet<String> r = new HashSet<>();
entForRealms.put(entitlement, r);
return r;
});
realms.add(RealmUtils.getGroupOwnerRealm(group.getRealm().getFullPath(), group.getKey()));
});
}
});
return buildAuthorities(entForRealms);
}
protected Set<SyncopeGrantedAuthority> getDelegatedAuthorities(final Delegation delegation) {
Map<String, Set<String>> entForRealms = new HashMap<>();
delegation.getRoles().stream().filter(role -> !GROUP_OWNER_ROLE.equals(role.getKey())).
forEach(role -> role.getEntitlements().forEach(entitlement -> {
Set<String> realms = Optional.ofNullable(entForRealms.get(entitlement)).orElseGet(() -> {
HashSet<String> r = new HashSet<>();
entForRealms.put(entitlement, r);
return r;
});
realms.addAll(role.getRealms().stream().map(Realm::getFullPath).collect(Collectors.toSet()));
if (!entitlement.endsWith("_CREATE") && !entitlement.endsWith("_DELETE")) {
realms.addAll(role.getDynRealms().stream().map(DynRealm::getKey).collect(Collectors.toList()));
}
}));
return buildAuthorities(entForRealms);
}
@Transactional
public Set<SyncopeGrantedAuthority> getAuthorities(final String username, final String delegationKey) {
Set<SyncopeGrantedAuthority> authorities;
if (securityProperties.getAnonymousUser().equals(username)) {
authorities = ANONYMOUS_AUTHORITIES;
} else if (securityProperties.getAdminUser().equals(username)) {
authorities = getAdminAuthorities();
} else if (delegationKey != null) {
Delegation delegation = Optional.ofNullable(delegationDAO.find(delegationKey)).
orElseThrow(() -> new UsernameNotFoundException(
"Could not find delegation " + delegationKey));
authorities = delegation.getRoles().isEmpty()
? getUserAuthorities(delegation.getDelegating())
: getDelegatedAuthorities(delegation);
} else {
User user = Optional.ofNullable(userDAO.findByUsername(username)).
orElseThrow(() -> new UsernameNotFoundException(
"Could not find any user with username " + username));
authorities = getUserAuthorities(user);
}
return authorities;
}
@Transactional
public Pair<String, Set<SyncopeGrantedAuthority>> authenticate(final JWTAuthentication authentication) {
String username;
Set<SyncopeGrantedAuthority> authorities;
if (securityProperties.getAdminUser().equals(authentication.getClaims().getSubject())) {
AccessToken accessToken = accessTokenDAO.find(authentication.getClaims().getJWTID());
if (accessToken == null) {
throw new AuthenticationCredentialsNotFoundException(
"Could not find an Access Token for JWT " + authentication.getClaims().getJWTID());
}
username = securityProperties.getAdminUser();
authorities = getAdminAuthorities();
} else {
JWTSSOProvider jwtSSOProvider = getJWTSSOProvider(authentication.getClaims().getIssuer());
Pair<User, Set<SyncopeGrantedAuthority>> resolved = jwtSSOProvider.resolve(authentication.getClaims());
if (resolved == null || resolved.getLeft() == null) {
throw new AuthenticationCredentialsNotFoundException(
"Could not find User " + authentication.getClaims().getSubject()
+ " for JWT " + authentication.getClaims().getJWTID());
}
User user = resolved.getLeft();
String delegationKey = getDelegationKey(authentication.getDetails(), user.getKey());
username = user.getUsername();
authorities = resolved.getRight() == null
? Set.of()
: delegationKey == null
? resolved.getRight()
: getAuthorities(username, delegationKey);
LOG.debug("JWT {} issued by {} resolved to User {} with authorities {}",
authentication.getClaims().getJWTID(),
authentication.getClaims().getIssuer(),
username + Optional.ofNullable(delegationKey).
map(d -> " [under delegation " + delegationKey + "]").orElse(StringUtils.EMPTY),
authorities);
if (BooleanUtils.isTrue(user.isSuspended())) {
throw new DisabledException("User " + username + " is suspended");
}
List<String> authStatuses = List.of(confParamOps.get(authentication.getDetails().getDomain(),
"authentication.statuses", new String[] {}, String[].class));
if (!authStatuses.contains(user.getStatus())) {
throw new DisabledException("User " + username + " not allowed to authenticate");
}
if (BooleanUtils.isTrue(user.isMustChangePassword())) {
LOG.debug("User {} must change password, resetting authorities", username);
authorities = MUST_CHANGE_PASSWORD_AUTHORITIES;
}
}
return Pair.of(username, authorities);
}
@Transactional
public void removeExpired(final String tokenKey) {
accessTokenDAO.delete(tokenKey);
}
@Transactional(readOnly = true)
public void audit(
final String username,
final String delegationKey,
final AuditElements.Result result,
final Object output,
final Object... input) {
auditManager.audit(
username + Optional.ofNullable(delegationKey).
map(d -> " [under delegation " + delegationKey + "]").orElse(StringUtils.EMPTY),
AuditElements.EventCategoryType.LOGIC, AuditElements.AUTHENTICATION_CATEGORY, null,
AuditElements.LOGIN_EVENT, result, null, output, input);
}
}
| apache/syncope | core/spring/src/main/java/org/apache/syncope/core/spring/security/AuthDataAccessor.java | Java | apache-2.0 | 23,971 |
/*
* Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License. See accompanying
* LICENSE file.
*/
package admin.keepalive;
import hydra.*;
//import util.*;
/**
*
* A class used to store keys for Admin API region "keep alive" Tests
*
*/
public class TestPrms extends BasePrms {
//---------------------------------------------------------------------
// Default Values
//---------------------------------------------------------------------
// Test-specific parameters
/** (boolean) controls whether CacheLoader is defined
*/
public static Long defineCacheLoaderRemote;
/*
* Returns boolean value of TestPrms.defineCacheLoaderRemote.
* Defaults to false.
*/
public static boolean getDefineCacheLoaderRemote() {
Long key = defineCacheLoaderRemote;
return (tasktab().booleanAt(key, tab().booleanAt(key, false)));
}
}
| papicella/snappy-store | tests/core/src/main/java/admin/keepalive/TestPrms.java | Java | apache-2.0 | 1,450 |
/* $Id$
*
* 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.etch.bindings.java.msg;
import java.util.Set;
import org.apache.etch.bindings.java.msg.Validator.Level;
/**
* Interface which defines the value factory which helps
* the idl compiler serialize and deserialize messages,
* convert values, etc.
*/
public interface ValueFactory
{
//////////
// Type //
//////////
/**
* Translates a type id into the appropriate Type object. If the type does
* not exist, and if dynamic typing is enabled, adds it to the dynamic types.
* @param id a type id.
* @return id translated into the appropriate Type.
*/
public Type getType( Integer id );
/**
* Translates a type name into the appropriate Type object. If the type does
* not exist, and if dynamic typing is enabled, adds it to the dynamic types.
* @param name a type name.
* @return name translated into the appropriate Type.
*/
public Type getType( String name );
/**
* Adds the type if it doesn't already exist. Use this to dynamically add
* types to a ValueFactory. The type is per instance of the ValueFactory,
* not global. Not available if dynamic typing is locked.
* @param type
*/
public void addType( Type type );
/**
* Locks the dynamic typing so that no new types may be created by addType
* or getType.
*/
public void lockDynamicTypes();
/**
* Unlocks the dynamic typing so that new types may be created by addType
* or getType.
*/
public void unlockDynamicTypes();
/**
* @return a collection of all the types.
*/
public Set<Type> getTypes();
/////////////////////
// STRING ENCODING //
/////////////////////
/**
* @return the encoding to use for strings.
*/
public String getStringEncoding();
////////////////
// MESSAGE ID //
////////////////
/**
* @param msg the message whose well-known message-id field is to be
* returned.
* @return the value of the well-known message-id field. This is a
* unique identifier for this message on a particular transport
* during a particular session. If there is no well-known message-id
* field defined, or if the message-id field has not been set, then
* return null.
*/
public Long getMessageId( Message msg );
/**
* Sets the value of the well-known message-id field. This is a
* unique identifier for this message on a particular transport
* during a particular session. If there is no well-known message-id
* field defined then nothing is done. If msgid is null, then the
* field is cleared.
* @param msg the message whose well-known message-id field is to
* be set.
* @param msgid the value of the well-known message-id field.
*/
public void setMessageId( Message msg, Long msgid );
/**
* @return well-known message field for message id.
*/
public Field get_mf__messageId();
/////////////////
// IN REPLY TO //
/////////////////
/**
* @param msg the message whose well-known in-reply-to field is to
* be returned.
* @return the value of the in-reply-to field, or null if there is
* none or if there is no such field defined.
*/
public Long getInReplyTo( Message msg );
/**
* @param msg the message whose well-known in-reply-to field is to
* be set.
* @param msgid the value of the well-known in-reply-to field. If
* there is no well-known in-reply-to field defined then nothing
* is done. If msgid is null, then the field is cleared.
*/
public void setInReplyTo( Message msg, Long msgid );
/**
* @return well-known message field for in reply to.
*/
public Field get_mf__inReplyTo();
//////////////////////
// VALUE CONVERSION //
//////////////////////
/**
* Converts a value to a struct value representation to be exported
* to a tagged data output.
* @param value a custom type defined by a service, or a well-known
* standard type (e.g., date).
* @return a struct value representing the value.
* @throws UnsupportedOperationException if the type cannot be exported.
*/
public StructValue exportCustomValue( Object value )
throws UnsupportedOperationException;
/**
* Converts a struct value imported from a tagged data input to
* a normal type.
* @param struct a struct value representation of a custom type, or a
* well known standard type.
* @return a custom type, or a well known standard type.
* @throws UnsupportedOperationException if the type cannot be imported.
*/
public Object importCustomValue( StructValue struct )
throws UnsupportedOperationException;
/**
* @param c the class of a custom value.
* @return the struct type of a custom value class.
* @throws UnsupportedOperationException
* @see #exportCustomValue(Object)
*/
public Type getCustomStructType( Class<?> c )
throws UnsupportedOperationException;
/**
* @return well-known message type for exception thrown by one-way
* message.
*/
public Type get_mt__exception();
/**
* @return the validation level of field StructValue.put and TaggedDataOutput.
*/
public Level getLevel();
/**
* Sets the validation level of field StructValue.put and TaggedDataOutput.
* @param level
* @return the old value
*/
public Level setLevel( Level level );
}
| OBIGOGIT/etch | binding-java/runtime/src/main/java/org/apache/etch/bindings/java/msg/ValueFactory.java | Java | apache-2.0 | 5,950 |
/*
* #%L
* ImageJ software for multidimensional image processing and analysis.
* %%
* Copyright (C) 2014 - 2017 Board of Regents of the University of
* Wisconsin-Madison, University of Konstanz and Brian Northan.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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 HOLDERS 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.
* #L%
*/
package net.imagej.ops.create.img;
import net.imagej.ops.Ops;
import net.imagej.ops.special.chain.UFViaUFSameIO;
import net.imagej.ops.special.function.Functions;
import net.imagej.ops.special.function.UnaryFunctionOp;
import net.imglib2.Interval;
import net.imglib2.img.Img;
import net.imglib2.type.numeric.real.DoubleType;
import org.scijava.plugin.Plugin;
/**
* Creates an {@link Img} from an {@link Interval} with no additional hints.
* {@link Interval} contents are not copied.
*
* @author Curtis Rueden
*/
@Plugin(type = Ops.Create.Img.class)
public class CreateImgFromInterval extends
UFViaUFSameIO<Interval, Img<DoubleType>> implements Ops.Create.Img
{
@Override
@SuppressWarnings({"rawtypes", "unchecked"})
public UnaryFunctionOp<Interval, Img<DoubleType>> createWorker(
final Interval input)
{
// NB: Intended to match CreateImgFromDimsAndType.
return (UnaryFunctionOp) Functions.unary(ops(), Ops.Create.Img.class,
Img.class, input, new DoubleType());
}
}
| gab1one/imagej-ops | src/main/java/net/imagej/ops/create/img/CreateImgFromInterval.java | Java | bsd-2-clause | 2,532 |
package org.hisp.dhis.system.filter;
/*
* Copyright (c) 2004-2015, University of Oslo
* 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 HISP 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.
*/
import com.google.common.collect.Sets;
import org.hisp.dhis.common.ValueType;
import org.hisp.dhis.commons.filter.Filter;
import org.hisp.dhis.dataelement.DataElement;
import java.util.Set;
/**
* @author Lars Helge Overland
*/
public class AggregatableDataElementFilter
implements Filter<DataElement>
{
public static final AggregatableDataElementFilter INSTANCE = new AggregatableDataElementFilter();
private static final Set<ValueType> VALUE_TYPES = Sets.newHashSet(
ValueType.BOOLEAN, ValueType.TRUE_ONLY, ValueType.TEXT, ValueType.LONG_TEXT, ValueType.LETTER,
ValueType.INTEGER, ValueType.INTEGER_POSITIVE, ValueType.INTEGER_NEGATIVE, ValueType.INTEGER_ZERO_OR_POSITIVE,
ValueType.NUMBER, ValueType.UNIT_INTERVAL, ValueType.PERCENTAGE, ValueType.COORDINATE
);
@Override
public boolean retain( DataElement object )
{
return object != null && VALUE_TYPES.contains( object.getValueType() );
}
}
| steffeli/inf5750-tracker-capture | dhis-support/dhis-support-system/src/main/java/org/hisp/dhis/system/filter/AggregatableDataElementFilter.java | Java | bsd-3-clause | 2,620 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.